blob: f23d1a02b141d5d72afe408272de3bb677452a05 [file] [log] [blame]
Chris Lattner3d1cee32008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Faisal Valifad9e132013-09-26 19:54:12 +000017#include "clang/AST/ASTLambda.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000018#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Richard Smith4ac537b2013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
Stephen Hines176edba2014-12-01 14:53:08 -080039#include "clang/Sema/Template.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000041#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000042#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000043#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000044
45using namespace clang;
46
Chris Lattner8123a952008-04-10 02:22:51 +000047//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
Chris Lattner9e979552008-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 Kramer85b45212009-11-28 19:45:26 +000057 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000058 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000059 Expr *DefaultArg;
60 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000061
Chris Lattner9e979552008-04-12 23:52:44 +000062 public:
Mike Stump1eb44332009-09-09 15:08:12 +000063 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000064 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000065
Chris Lattner9e979552008-04-12 23:52:44 +000066 bool VisitExpr(Expr *Node);
67 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000068 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000069 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000070 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000071 };
Chris Lattner8123a952008-04-10 02:22:51 +000072
Chris Lattner9e979552008-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 McCall7502c1d2011-02-13 04:07:26 +000076 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000077 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000078 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000079 }
80
Chris Lattner9e979552008-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 Gregor8e9bebd2008-10-21 16:13:35 +000085 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-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 Dunbar96a00142012-03-09 18:35:03 +000095 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000096 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000097 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000098 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000099 // C++ [dcl.fct.default]p7
100 // Local variables shall not be used in default argument
101 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000102 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000103 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000104 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000105 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000106 }
Chris Lattner8123a952008-04-10 02:22:51 +0000107
Douglas Gregor3996f232008-11-04 13:41:56 +0000108 return false;
109 }
Chris Lattner9e979552008-04-12 23:52:44 +0000110
Douglas Gregor796da182008-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 Dunbar96a00142012-03-09 18:35:03 +0000116 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000117 diag::err_param_default_argument_references_this)
118 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000119 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000120
John McCall045d2522013-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 Gregorf0459f82012-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 Lattner8123a952008-04-10 02:22:51 +0000148}
149
Richard Smith0b0ca472013-04-10 06:11:48 +0000150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000155 return;
156
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160 if (!Proto)
161 return;
Sean Hunt001cad92011-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 Smithb9d0b762012-07-27 04:22:15 +0000166 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000167 ClearExceptions();
168 ComputedEST = EST;
169 return;
170 }
171
Richard Smith7a614d82011-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
Sean Hunt001cad92011-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 Smithe6975e92012-04-17 00:58:00 +0000193 FunctionProtoType::NoexceptResult NR =
194 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-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.
Stephen Hines651f13c2014-04-23 16:59:28 -0700215 for (const auto &E : Proto->exceptions())
Stephen Hines176edba2014-12-01 14:53:08 -0800216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
Stephen Hines651f13c2014-04-23 16:59:28 -0700217 Exceptions.push_back(E);
Sean Hunt001cad92011-05-10 00:49:42 +0000218}
219
Richard Smith7a614d82011-06-11 17:19:42 +0000220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000221 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000222 return;
223
224 // FIXME:
225 //
226 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-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 Smith7a614d82011-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 Smithe6975e92012-04-17 00:58:00 +0000245 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000246 ComputedEST = EST_None;
247}
248
Anders Carlssoned961f92009-08-25 02:29:20 +0000249bool
John McCall9ae2f072010-08-23 23:25:46 +0000250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000251 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-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 Carlssoned961f92009-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 Jahanian745da3a2010-09-24 17:30:16 +0000264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000268 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000270 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000271 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700272 Arg = Result.getAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000273
Richard Smith6c3af3d2013-01-17 01:17:56 +0000274 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000275 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Anders Carlssoned961f92009-08-25 02:29:20 +0000277 // Okay: add the default argument to the parameter
278 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Douglas Gregor8cfb7a32010-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 Carlsson9351c172009-08-25 03:18:48 +0000292 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000293}
294
Chris Lattner8123a952008-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 Lattner3d1cee32008-04-08 05:04:30 +0000298void
John McCalld226f652010-08-21 09:40:31 +0000299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000300 Expr *DefaultArg) {
301 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000305 UnparsedDefaultArgLocs.erase(Param);
306
Chris Lattner3d1cee32008-04-08 05:04:30 +0000307 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000308 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000309 Diag(EqualLoc, diag::err_param_default_argument)
310 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 return;
313 }
314
Douglas Gregor6f526752010-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 Carlsson66e30672009-08-25 01:02:06 +0000321 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000322 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000324 Param->setInvalidDecl();
325 return;
326 }
Mike Stump1eb44332009-09-09 15:08:12 +0000327
John McCall9ae2f072010-08-23 23:25:46 +0000328 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000329}
330
Douglas Gregor61366e92008-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 McCalld226f652010-08-21 09:40:31 +0000335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 SourceLocation EqualLoc,
337 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000338 if (!param)
339 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
John McCalld226f652010-08-21 09:40:31 +0000341 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +0000342 Param->setUnparsedDefaultArg();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000343 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000344}
345
Douglas Gregor72b505b2008-12-16 21:30:33 +0000346/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
347/// the default argument for the parameter param failed.
Stephen Hines176edba2014-12-01 14:53:08 -0800348void Sema::ActOnParamDefaultArgumentError(Decl *param,
349 SourceLocation EqualLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000350 if (!param)
351 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000352
John McCalld226f652010-08-21 09:40:31 +0000353 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000354 Param->setInvalidDecl();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000355 UnparsedDefaultArgLocs.erase(Param);
Stephen Hines176edba2014-12-01 14:53:08 -0800356 Param->setDefaultArg(new(Context)
357 OpaqueValueExpr(EqualLoc,
358 Param->getType().getNonReferenceType(),
359 VK_RValue));
Douglas Gregor72b505b2008-12-16 21:30:33 +0000360}
361
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000362/// CheckExtraCXXDefaultArguments - Check for any extra default
363/// arguments in the declarator, which is not a function declaration
364/// or definition and therefore is not permitted to have default
365/// arguments. This routine should be invoked for every declarator
366/// that is not a function declaration or definition.
367void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
368 // C++ [dcl.fct.default]p3
369 // A default argument expression shall be specified only in the
370 // parameter-declaration-clause of a function declaration or in a
371 // template-parameter (14.1). It shall not be specified for a
372 // parameter pack. If it is specified in a
373 // parameter-declaration-clause, it shall not occur within a
374 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000375 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000377 DeclaratorChunk &chunk = D.getTypeObject(i);
378 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000379 if (MightBeFunction) {
380 // This is a function declaration. It can have default arguments, but
381 // keep looking in case its return type is a function type with default
382 // arguments.
383 MightBeFunction = false;
384 continue;
385 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700386 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
387 ++argIdx) {
388 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000389 if (Param->hasUnparsedDefaultArg()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700390 CachedTokens *Toks = chunk.Fun.Params[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000392 << SourceRange((*Toks)[1].getLocation(),
393 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000394 delete Toks;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700395 chunk.Fun.Params[argIdx].DefaultArgTokens = nullptr;
Douglas Gregor61366e92008-12-24 00:01:03 +0000396 } else if (Param->getDefaultArg()) {
397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
398 << Param->getDefaultArg()->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700399 Param->setDefaultArg(nullptr);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000400 }
401 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000402 } else if (chunk.Kind != DeclaratorChunk::Paren) {
403 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000404 }
405 }
406}
407
David Majnemerf6a144f2013-06-25 23:09:30 +0000408static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
409 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
410 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
411 if (!PVD->hasDefaultArg())
412 return false;
413 if (!PVD->hasInheritedDefaultArg())
414 return true;
415 }
416 return false;
417}
418
Craig Topper1a6eac82012-09-21 04:33:26 +0000419/// MergeCXXFunctionDecl - Merge two declarations of the same C++
420/// function, once we already know that they have the same
421/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
422/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000423bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
424 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000425 bool Invalid = false;
426
Chris Lattner3d1cee32008-04-08 05:04:30 +0000427 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000428 // For non-template functions, default arguments can be added in
429 // later declarations of a function in the same
430 // scope. Declarations in different scopes have completely
431 // distinct sets of default arguments. That is, declarations in
432 // inner scopes do not acquire default arguments from
433 // declarations in outer scopes, and vice versa. In a given
434 // function declaration, all parameters subsequent to a
435 // parameter with a default argument shall have default
436 // arguments supplied in this or previous declarations. A
437 // default argument shall not be redefined by a later
438 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000439 //
440 // C++ [dcl.fct.default]p6:
Richard Smitha41c97a2013-09-20 01:15:31 +0000441 // Except for member functions of class templates, the default arguments
442 // in a member function definition that appears outside of the class
443 // definition are added to the set of default arguments provided by the
Douglas Gregor6cc15182009-09-11 18:44:32 +0000444 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000445 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
446 ParmVarDecl *OldParam = Old->getParamDecl(p);
447 ParmVarDecl *NewParam = New->getParamDecl(p);
448
James Molloy9cda03f2012-03-13 08:55:35 +0000449 bool OldParamHasDfl = OldParam->hasDefaultArg();
450 bool NewParamHasDfl = NewParam->hasDefaultArg();
451
Richard Smitha41c97a2013-09-20 01:15:31 +0000452 // The declaration context corresponding to the scope is the semantic
453 // parent, unless this is a local function declaration, in which case
454 // it is that surrounding function.
Stephen Hines176edba2014-12-01 14:53:08 -0800455 DeclContext *ScopeDC = New->isLocalExternDecl()
456 ? New->getLexicalDeclContext()
457 : New->getDeclContext();
458 if (S && !isDeclInScope(Old, ScopeDC, S) &&
Richard Smitha41c97a2013-09-20 01:15:31 +0000459 !New->getDeclContext()->isRecord())
James Molloy9cda03f2012-03-13 08:55:35 +0000460 // Ignore default parameters of old decl if they are not in
Richard Smitha41c97a2013-09-20 01:15:31 +0000461 // the same scope and this is not an out-of-line definition of
462 // a member function.
James Molloy9cda03f2012-03-13 08:55:35 +0000463 OldParamHasDfl = false;
Stephen Hines176edba2014-12-01 14:53:08 -0800464 if (New->isLocalExternDecl() != Old->isLocalExternDecl())
465 // If only one of these is a local function declaration, then they are
466 // declared in different scopes, even though isDeclInScope may think
467 // they're in the same scope. (If both are local, the scope check is
468 // sufficent, and if neither is local, then they are in the same scope.)
469 OldParamHasDfl = false;
James Molloy9cda03f2012-03-13 08:55:35 +0000470
471 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000472
Francois Pichet8d051e02011-04-10 03:03:52 +0000473 unsigned DiagDefaultParamID =
474 diag::err_param_default_argument_redefinition;
475
476 // MSVC accepts that default parameters be redefined for member functions
477 // of template class. The new default parameter's value is ignored.
478 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000479 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000480 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
481 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000482 // Merge the old default argument into the new parameter.
483 NewParam->setHasInheritedDefaultArg();
484 if (OldParam->hasUninstantiatedDefaultArg())
485 NewParam->setUninstantiatedDefaultArg(
486 OldParam->getUninstantiatedDefaultArg());
487 else
488 NewParam->setDefaultArg(OldParam->getInit());
Stephen Hines176edba2014-12-01 14:53:08 -0800489 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000490 Invalid = false;
491 }
492 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000493
Francois Pichet8cf90492011-04-10 04:58:30 +0000494 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
495 // hint here. Alternatively, we could walk the type-source information
496 // for NewParam to find the last source location in the type... but it
497 // isn't worth the effort right now. This is the kind of test case that
498 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000499 // int f(int);
500 // void g(int (*fp)(int) = f);
501 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000502 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000503 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000504
505 // Look for the function declaration where the default argument was
506 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000507 for (FunctionDecl *Older = Old->getPreviousDecl();
508 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000509 if (!Older->getParamDecl(p)->hasDefaultArg())
510 break;
511
512 OldParam = Older->getParamDecl(p);
513 }
514
515 Diag(OldParam->getLocation(), diag::note_previous_definition)
516 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000517 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000518 // Merge the old default argument into the new parameter.
519 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000520 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000521 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000522 if (OldParam->hasUninstantiatedDefaultArg())
523 NewParam->setUninstantiatedDefaultArg(
524 OldParam->getUninstantiatedDefaultArg());
525 else
John McCall3d6c1782010-05-04 01:53:42 +0000526 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000527 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000528 if (New->getDescribedFunctionTemplate()) {
529 // Paragraph 4, quoted above, only applies to non-template functions.
530 Diag(NewParam->getLocation(),
531 diag::err_param_default_argument_template_redecl)
532 << NewParam->getDefaultArgRange();
533 Diag(Old->getLocation(), diag::note_template_prev_declaration)
534 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000535 } else if (New->getTemplateSpecializationKind()
536 != TSK_ImplicitInstantiation &&
537 New->getTemplateSpecializationKind() != TSK_Undeclared) {
538 // C++ [temp.expr.spec]p21:
539 // Default function arguments shall not be specified in a declaration
540 // or a definition for one of the following explicit specializations:
541 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000542 // - the explicit specialization of a member function template;
543 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000544 // template where the class template specialization to which the
545 // member function specialization belongs is implicitly
546 // instantiated.
547 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
548 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
549 << New->getDeclName()
550 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000551 } else if (New->getDeclContext()->isDependentContext()) {
552 // C++ [dcl.fct.default]p6 (DR217):
553 // Default arguments for a member function of a class template shall
554 // be specified on the initial declaration of the member function
555 // within the class template.
556 //
557 // Reading the tea leaves a bit in DR217 and its reference to DR205
558 // leads me to the conclusion that one cannot add default function
559 // arguments for an out-of-line definition of a member function of a
560 // dependent type.
561 int WhichKind = 2;
562 if (CXXRecordDecl *Record
563 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
564 if (Record->getDescribedClassTemplate())
565 WhichKind = 0;
566 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
567 WhichKind = 1;
568 else
569 WhichKind = 2;
570 }
571
572 Diag(NewParam->getLocation(),
573 diag::err_param_default_argument_member_template_redecl)
574 << WhichKind
575 << NewParam->getDefaultArgRange();
576 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000577 }
578 }
579
Richard Smithb8abff62012-11-28 03:45:24 +0000580 // DR1344: If a default argument is added outside a class definition and that
581 // default argument makes the function a special member function, the program
582 // is ill-formed. This can only happen for constructors.
583 if (isa<CXXConstructorDecl>(New) &&
584 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
585 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
586 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
587 if (NewSM != OldSM) {
588 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
589 assert(NewParam->hasDefaultArg());
590 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
591 << NewParam->getDefaultArgRange() << NewSM;
592 Diag(Old->getLocation(), diag::note_previous_declaration);
593 }
594 }
595
Stephen Hines651f13c2014-04-23 16:59:28 -0700596 const FunctionDecl *Def;
Richard Smithff234882012-02-20 23:28:05 +0000597 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000598 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000599 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000600 if (New->isConstexpr() != Old->isConstexpr()) {
601 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
602 << New << New->isConstexpr();
603 Diag(Old->getLocation(), diag::note_previous_declaration);
604 Invalid = true;
Stephen Hines651f13c2014-04-23 16:59:28 -0700605 } else if (!Old->isInlined() && New->isInlined() && Old->isDefined(Def)) {
606 // C++11 [dcl.fcn.spec]p4:
607 // If the definition of a function appears in a translation unit before its
608 // first declaration as inline, the program is ill-formed.
609 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
610 Diag(Def->getLocation(), diag::note_previous_definition);
611 Invalid = true;
Richard Smith9f569cc2011-10-01 02:31:28 +0000612 }
613
David Majnemerf6a144f2013-06-25 23:09:30 +0000614 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000615 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000616 // the only declaration of the function or function template in the
617 // translation unit.
618 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
619 functionDeclHasDefaultArgument(Old)) {
620 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
621 Diag(Old->getLocation(), diag::note_previous_declaration);
622 Invalid = true;
623 }
624
Douglas Gregore13ad832010-02-12 07:32:17 +0000625 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000626 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000627
Douglas Gregorcda9c672009-02-16 17:45:42 +0000628 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000629}
630
Sebastian Redl60618fa2011-03-12 11:50:43 +0000631/// \brief Merge the exception specifications of two variable declarations.
632///
633/// This is called when there's a redeclaration of a VarDecl. The function
634/// checks if the redeclaration might have an exception specification and
635/// validates compatibility and merges the specs if necessary.
636void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
637 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000638 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000639 return;
640
641 assert(Context.hasSameType(New->getType(), Old->getType()) &&
642 "Should only be called if types are otherwise the same.");
643
644 QualType NewType = New->getType();
645 QualType OldType = Old->getType();
646
647 // We're only interested in pointers and references to functions, as well
648 // as pointers to member functions.
649 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
650 NewType = R->getPointeeType();
651 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
652 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
653 NewType = P->getPointeeType();
654 OldType = OldType->getAs<PointerType>()->getPointeeType();
655 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
656 NewType = M->getPointeeType();
657 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
658 }
659
660 if (!NewType->isFunctionProtoType())
661 return;
662
663 // There's lots of special cases for functions. For function pointers, system
664 // libraries are hopefully not as broken so that we don't need these
665 // workarounds.
666 if (CheckEquivalentExceptionSpec(
667 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
668 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
669 New->setInvalidDecl();
670 }
671}
672
Chris Lattner3d1cee32008-04-08 05:04:30 +0000673/// CheckCXXDefaultArguments - Verify that the default arguments for a
674/// function declaration are well-formed according to C++
675/// [dcl.fct.default].
676void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
677 unsigned NumParams = FD->getNumParams();
678 unsigned p;
679
680 // Find first parameter with a default argument
681 for (p = 0; p < NumParams; ++p) {
682 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000683 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000684 break;
685 }
686
687 // C++ [dcl.fct.default]p4:
688 // In a given function declaration, all parameters
689 // subsequent to a parameter with a default argument shall
690 // have default arguments supplied in this or previous
691 // declarations. A default argument shall not be redefined
692 // by a later declaration (not even to the same value).
693 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000694 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000695 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000696 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000697 if (Param->isInvalidDecl())
698 /* We already complained about this parameter. */;
699 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000700 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000701 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000702 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000703 else
Mike Stump1eb44332009-09-09 15:08:12 +0000704 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000705 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattner3d1cee32008-04-08 05:04:30 +0000707 LastMissingDefaultArg = p;
708 }
709 }
710
711 if (LastMissingDefaultArg > 0) {
712 // Some default arguments were missing. Clear out all of the
713 // default arguments up to (and including) the last missing
714 // default argument, so that we leave the function parameters
715 // in a semantically valid state.
716 for (p = 0; p <= LastMissingDefaultArg; ++p) {
717 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000718 if (Param->hasDefaultArg()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700719 Param->setDefaultArg(nullptr);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000720 }
721 }
722 }
723}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000724
Richard Smith9f569cc2011-10-01 02:31:28 +0000725// CheckConstexprParameterTypes - Check whether a function's parameter types
726// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000727// diagnostic and return false.
728static bool CheckConstexprParameterTypes(Sema &SemaRef,
729 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000730 unsigned ArgIndex = 0;
731 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -0700732 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
733 e = FT->param_type_end();
734 i != e; ++i, ++ArgIndex) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000735 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
736 SourceLocation ParamLoc = PD->getLocation();
737 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000738 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000739 diag::err_constexpr_non_literal_param,
740 ArgIndex+1, PD->getSourceRange(),
741 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000742 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000743 }
Joao Matos17d35c32012-08-31 22:18:20 +0000744 return true;
745}
746
747/// \brief Get diagnostic %select index for tag kind for
748/// record diagnostic message.
749/// WARNING: Indexes apply to particular diagnostics only!
750///
751/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000752static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000753 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000754 case TTK_Struct: return 0;
755 case TTK_Interface: return 1;
756 case TTK_Class: return 2;
757 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000758 }
Joao Matos17d35c32012-08-31 22:18:20 +0000759}
760
761// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
762// the requirements of a constexpr function definition or a constexpr
763// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000764// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000765//
Richard Smith86c3ae42012-02-13 03:54:03 +0000766// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
767bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000768 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
769 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000770 // C++11 [dcl.constexpr]p4:
771 // The definition of a constexpr constructor shall satisfy the following
772 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000773 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000774 const CXXRecordDecl *RD = MD->getParent();
775 if (RD->getNumVBases()) {
776 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
777 << isa<CXXConstructorDecl>(NewFD)
778 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
Stephen Hines651f13c2014-04-23 16:59:28 -0700779 for (const auto &I : RD->vbases())
780 Diag(I.getLocStart(),
781 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000782 return false;
783 }
Richard Smith35340502012-01-13 04:54:00 +0000784 }
785
786 if (!isa<CXXConstructorDecl>(NewFD)) {
787 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000788 // The definition of a constexpr function shall satisfy the following
789 // constraints:
790 // - it shall not be virtual;
791 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
792 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000793 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000794
Richard Smith86c3ae42012-02-13 03:54:03 +0000795 // If it's not obvious why this function is virtual, find an overridden
796 // function which uses the 'virtual' keyword.
797 const CXXMethodDecl *WrittenVirtual = Method;
798 while (!WrittenVirtual->isVirtualAsWritten())
799 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
800 if (WrittenVirtual != Method)
801 Diag(WrittenVirtual->getLocation(),
802 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000803 return false;
804 }
805
806 // - its return type shall be a literal type;
Stephen Hines651f13c2014-04-23 16:59:28 -0700807 QualType RT = NewFD->getReturnType();
Richard Smith9f569cc2011-10-01 02:31:28 +0000808 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000809 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000810 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000811 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000812 }
813
Richard Smith35340502012-01-13 04:54:00 +0000814 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000815 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000816 return false;
817
Richard Smith9f569cc2011-10-01 02:31:28 +0000818 return true;
819}
820
821/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000822/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000823///
Richard Smitha10b9782013-04-22 15:31:51 +0000824/// \return true if the body is OK (maybe only as an extension), false if we
825/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000826static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000827 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
828 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000829 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
830 // contain only
Stephen Hines651f13c2014-04-23 16:59:28 -0700831 for (const auto *DclIt : DS->decls()) {
832 switch (DclIt->getKind()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000833 case Decl::StaticAssert:
834 case Decl::Using:
835 case Decl::UsingShadow:
836 case Decl::UsingDirective:
837 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000838 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000839 // - static_assert-declarations
840 // - using-declarations,
841 // - using-directives,
842 continue;
843
844 case Decl::Typedef:
845 case Decl::TypeAlias: {
846 // - typedef declarations and alias-declarations that do not define
847 // classes or enumerations,
Stephen Hines651f13c2014-04-23 16:59:28 -0700848 const auto *TN = cast<TypedefNameDecl>(DclIt);
Richard Smith9f569cc2011-10-01 02:31:28 +0000849 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
850 // Don't allow variably-modified types in constexpr functions.
851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
853 << TL.getSourceRange() << TL.getType()
854 << isa<CXXConstructorDecl>(Dcl);
855 return false;
856 }
857 continue;
858 }
859
860 case Decl::Enum:
861 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000862 // C++1y allows types to be defined, not just declared.
Stephen Hines651f13c2014-04-23 16:59:28 -0700863 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
Richard Smitha10b9782013-04-22 15:31:51 +0000864 SemaRef.Diag(DS->getLocStart(),
Stephen Hines176edba2014-12-01 14:53:08 -0800865 SemaRef.getLangOpts().CPlusPlus14
Richard Smitha10b9782013-04-22 15:31:51 +0000866 ? diag::warn_cxx11_compat_constexpr_type_definition
867 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000868 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000869 continue;
870
Richard Smitha10b9782013-04-22 15:31:51 +0000871 case Decl::EnumConstant:
872 case Decl::IndirectField:
873 case Decl::ParmVar:
874 // These can only appear with other declarations which are banned in
875 // C++11 and permitted in C++1y, so ignore them.
876 continue;
877
878 case Decl::Var: {
879 // C++1y [dcl.constexpr]p3 allows anything except:
880 // a definition of a variable of non-literal type or of static or
881 // thread storage duration or for which no initialization is performed.
Stephen Hines651f13c2014-04-23 16:59:28 -0700882 const auto *VD = cast<VarDecl>(DclIt);
Richard Smitha10b9782013-04-22 15:31:51 +0000883 if (VD->isThisDeclarationADefinition()) {
884 if (VD->isStaticLocal()) {
885 SemaRef.Diag(VD->getLocation(),
886 diag::err_constexpr_local_var_static)
887 << isa<CXXConstructorDecl>(Dcl)
888 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
889 return false;
890 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000891 if (!VD->getType()->isDependentType() &&
892 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000893 VD->getLocation(), VD->getType(),
894 diag::err_constexpr_local_var_non_literal_type,
895 isa<CXXConstructorDecl>(Dcl)))
896 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700897 if (!VD->getType()->isDependentType() &&
898 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
Richard Smitha10b9782013-04-22 15:31:51 +0000899 SemaRef.Diag(VD->getLocation(),
900 diag::err_constexpr_local_var_no_init)
901 << isa<CXXConstructorDecl>(Dcl);
902 return false;
903 }
904 }
905 SemaRef.Diag(VD->getLocation(),
Stephen Hines176edba2014-12-01 14:53:08 -0800906 SemaRef.getLangOpts().CPlusPlus14
Richard Smitha10b9782013-04-22 15:31:51 +0000907 ? diag::warn_cxx11_compat_constexpr_local_var
908 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000909 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000910 continue;
911 }
912
913 case Decl::NamespaceAlias:
914 case Decl::Function:
915 // These are disallowed in C++11 and permitted in C++1y. Allow them
916 // everywhere as an extension.
917 if (!Cxx1yLoc.isValid())
918 Cxx1yLoc = DS->getLocStart();
919 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000920
921 default:
922 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
923 << isa<CXXConstructorDecl>(Dcl);
924 return false;
925 }
926 }
927
928 return true;
929}
930
931/// Check that the given field is initialized within a constexpr constructor.
932///
933/// \param Dcl The constexpr constructor being checked.
934/// \param Field The field being checked. This may be a member of an anonymous
935/// struct or union nested within the class being checked.
936/// \param Inits All declarations, including anonymous struct/union members and
937/// indirect members, for which any initialization was provided.
938/// \param Diagnosed Set to true if an error is produced.
939static void CheckConstexprCtorInitializer(Sema &SemaRef,
940 const FunctionDecl *Dcl,
941 FieldDecl *Field,
942 llvm::SmallSet<Decl*, 16> &Inits,
943 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000944 if (Field->isInvalidDecl())
945 return;
946
Douglas Gregord61db332011-10-10 17:22:13 +0000947 if (Field->isUnnamedBitfield())
948 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000949
Stephen Hines651f13c2014-04-23 16:59:28 -0700950 // Anonymous unions with no variant members and empty anonymous structs do not
951 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
952 // indirect fields don't need initializing.
Richard Smith30ecfad2012-02-09 06:40:58 +0000953 if (Field->isAnonymousStructOrUnion() &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700954 (Field->getType()->isUnionType()
955 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
956 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
Richard Smith30ecfad2012-02-09 06:40:58 +0000957 return;
958
Richard Smith9f569cc2011-10-01 02:31:28 +0000959 if (!Inits.count(Field)) {
960 if (!Diagnosed) {
961 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
962 Diagnosed = true;
963 }
964 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
965 } else if (Field->isAnonymousStructOrUnion()) {
966 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
Stephen Hines651f13c2014-04-23 16:59:28 -0700967 for (auto *I : RD->fields())
Richard Smith9f569cc2011-10-01 02:31:28 +0000968 // If an anonymous union contains an anonymous struct of which any member
969 // is initialized, all members must be initialized.
Stephen Hines651f13c2014-04-23 16:59:28 -0700970 if (!RD->isUnion() || Inits.count(I))
971 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000972 }
973}
974
Richard Smitha10b9782013-04-22 15:31:51 +0000975/// Check the provided statement is allowed in a constexpr function
976/// definition.
977static bool
978CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000979 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000980 SourceLocation &Cxx1yLoc) {
981 // - its function-body shall be [...] a compound-statement that contains only
982 switch (S->getStmtClass()) {
983 case Stmt::NullStmtClass:
984 // - null statements,
985 return true;
986
987 case Stmt::DeclStmtClass:
988 // - static_assert-declarations
989 // - using-declarations,
990 // - using-directives,
991 // - typedef declarations and alias-declarations that do not define
992 // classes or enumerations,
993 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
994 return false;
995 return true;
996
997 case Stmt::ReturnStmtClass:
998 // - and exactly one return statement;
999 if (isa<CXXConstructorDecl>(Dcl)) {
1000 // C++1y allows return statements in constexpr constructors.
1001 if (!Cxx1yLoc.isValid())
1002 Cxx1yLoc = S->getLocStart();
1003 return true;
1004 }
1005
1006 ReturnStmts.push_back(S->getLocStart());
1007 return true;
1008
1009 case Stmt::CompoundStmtClass: {
1010 // C++1y allows compound-statements.
1011 if (!Cxx1yLoc.isValid())
1012 Cxx1yLoc = S->getLocStart();
1013
1014 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
Stephen Hines651f13c2014-04-23 16:59:28 -07001015 for (auto *BodyIt : CompStmt->body()) {
1016 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +00001017 Cxx1yLoc))
1018 return false;
1019 }
1020 return true;
1021 }
1022
1023 case Stmt::AttributedStmtClass:
1024 if (!Cxx1yLoc.isValid())
1025 Cxx1yLoc = S->getLocStart();
1026 return true;
1027
1028 case Stmt::IfStmtClass: {
1029 // C++1y allows if-statements.
1030 if (!Cxx1yLoc.isValid())
1031 Cxx1yLoc = S->getLocStart();
1032
1033 IfStmt *If = cast<IfStmt>(S);
1034 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1035 Cxx1yLoc))
1036 return false;
1037 if (If->getElse() &&
1038 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1039 Cxx1yLoc))
1040 return false;
1041 return true;
1042 }
1043
1044 case Stmt::WhileStmtClass:
1045 case Stmt::DoStmtClass:
1046 case Stmt::ForStmtClass:
1047 case Stmt::CXXForRangeStmtClass:
1048 case Stmt::ContinueStmtClass:
1049 // C++1y allows all of these. We don't allow them as extensions in C++11,
1050 // because they don't make sense without variable mutation.
Stephen Hines176edba2014-12-01 14:53:08 -08001051 if (!SemaRef.getLangOpts().CPlusPlus14)
Richard Smitha10b9782013-04-22 15:31:51 +00001052 break;
1053 if (!Cxx1yLoc.isValid())
1054 Cxx1yLoc = S->getLocStart();
1055 for (Stmt::child_range Children = S->children(); Children; ++Children)
1056 if (*Children &&
1057 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1058 Cxx1yLoc))
1059 return false;
1060 return true;
1061
1062 case Stmt::SwitchStmtClass:
1063 case Stmt::CaseStmtClass:
1064 case Stmt::DefaultStmtClass:
1065 case Stmt::BreakStmtClass:
1066 // C++1y allows switch-statements, and since they don't need variable
1067 // mutation, we can reasonably allow them in C++11 as an extension.
1068 if (!Cxx1yLoc.isValid())
1069 Cxx1yLoc = S->getLocStart();
1070 for (Stmt::child_range Children = S->children(); Children; ++Children)
1071 if (*Children &&
1072 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1073 Cxx1yLoc))
1074 return false;
1075 return true;
1076
1077 default:
1078 if (!isa<Expr>(S))
1079 break;
1080
1081 // C++1y allows expression-statements.
1082 if (!Cxx1yLoc.isValid())
1083 Cxx1yLoc = S->getLocStart();
1084 return true;
1085 }
1086
1087 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1088 << isa<CXXConstructorDecl>(Dcl);
1089 return false;
1090}
1091
Richard Smith9f569cc2011-10-01 02:31:28 +00001092/// Check the body for the given constexpr function declaration only contains
1093/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1094///
1095/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001096bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001097 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001098 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001099 // The definition of a constexpr function shall satisfy the following
1100 // constraints: [...]
1101 // - its function-body shall be = delete, = default, or a
1102 // compound-statement
1103 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001104 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001105 // In the definition of a constexpr constructor, [...]
1106 // - its function-body shall not be a function-try-block;
1107 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1108 << isa<CXXConstructorDecl>(Dcl);
1109 return false;
1110 }
1111
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001112 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001113
1114 // - its function-body shall be [...] a compound-statement that contains only
1115 // [... list of cases ...]
1116 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1117 SourceLocation Cxx1yLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001118 for (auto *BodyIt : CompBody->body()) {
1119 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
Richard Smitha10b9782013-04-22 15:31:51 +00001120 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001121 }
1122
Richard Smitha10b9782013-04-22 15:31:51 +00001123 if (Cxx1yLoc.isValid())
1124 Diag(Cxx1yLoc,
Stephen Hines176edba2014-12-01 14:53:08 -08001125 getLangOpts().CPlusPlus14
Richard Smitha10b9782013-04-22 15:31:51 +00001126 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1127 : diag::ext_constexpr_body_invalid_stmt)
1128 << isa<CXXConstructorDecl>(Dcl);
1129
Richard Smith9f569cc2011-10-01 02:31:28 +00001130 if (const CXXConstructorDecl *Constructor
1131 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1132 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001133 // DR1359:
1134 // - every non-variant non-static data member and base class sub-object
1135 // shall be initialized;
Stephen Hines651f13c2014-04-23 16:59:28 -07001136 // DR1460:
1137 // - if the class is a union having variant members, exactly one of them
Richard Smith30ecfad2012-02-09 06:40:58 +00001138 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001139 if (RD->isUnion()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001140 if (Constructor->getNumCtorInitializers() == 0 &&
1141 RD->hasVariantMembers()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001142 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1143 return false;
1144 }
Richard Smith6e433752011-10-10 16:38:04 +00001145 } else if (!Constructor->isDependentContext() &&
1146 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001147 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1148
1149 // Skip detailed checking if we have enough initializers, and we would
1150 // allow at most one initializer per member.
1151 bool AnyAnonStructUnionMembers = false;
1152 unsigned Fields = 0;
1153 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1154 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001155 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001156 AnyAnonStructUnionMembers = true;
1157 break;
1158 }
1159 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001160 // DR1460:
1161 // - if the class is a union-like class, but is not a union, for each of
1162 // its anonymous union members having variant members, exactly one of
1163 // them shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001164 if (AnyAnonStructUnionMembers ||
1165 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1166 // Check initialization of non-static data members. Base classes are
1167 // always initialized so do not need to be checked. Dependent bases
1168 // might not have initializers in the member initializer list.
1169 llvm::SmallSet<Decl*, 16> Inits;
Stephen Hines651f13c2014-04-23 16:59:28 -07001170 for (const auto *I: Constructor->inits()) {
1171 if (FieldDecl *FD = I->getMember())
Richard Smith9f569cc2011-10-01 02:31:28 +00001172 Inits.insert(FD);
Stephen Hines651f13c2014-04-23 16:59:28 -07001173 else if (IndirectFieldDecl *ID = I->getIndirectMember())
Richard Smith9f569cc2011-10-01 02:31:28 +00001174 Inits.insert(ID->chain_begin(), ID->chain_end());
1175 }
1176
1177 bool Diagnosed = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07001178 for (auto *I : RD->fields())
1179 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001180 if (Diagnosed)
1181 return false;
1182 }
1183 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001184 } else {
1185 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001186 // C++1y doesn't require constexpr functions to contain a 'return'
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001187 // statement. We still do, unless the return type might be void, because
Richard Smitha10b9782013-04-22 15:31:51 +00001188 // otherwise if there's no return statement, the function cannot
1189 // be used in a core constant expression.
Stephen Hines176edba2014-12-01 14:53:08 -08001190 bool OK = getLangOpts().CPlusPlus14 &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001191 (Dcl->getReturnType()->isVoidType() ||
1192 Dcl->getReturnType()->isDependentType());
Richard Smitha10b9782013-04-22 15:31:51 +00001193 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001194 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1195 : diag::err_constexpr_body_no_return);
1196 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001197 }
1198 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001199 Diag(ReturnStmts.back(),
Stephen Hines176edba2014-12-01 14:53:08 -08001200 getLangOpts().CPlusPlus14
Richard Smitha10b9782013-04-22 15:31:51 +00001201 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1202 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001203 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1204 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001205 }
1206 }
1207
Richard Smith5ba73e12012-02-04 00:33:54 +00001208 // C++11 [dcl.constexpr]p5:
1209 // if no function argument values exist such that the function invocation
1210 // substitution would produce a constant expression, the program is
1211 // ill-formed; no diagnostic required.
1212 // C++11 [dcl.constexpr]p3:
1213 // - every constructor call and implicit conversion used in initializing the
1214 // return value shall be one of those allowed in a constant expression.
1215 // C++11 [dcl.constexpr]p4:
1216 // - every constructor involved in initializing non-static data members and
1217 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001218 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001219 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001220 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001221 << isa<CXXConstructorDecl>(Dcl);
1222 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1223 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001224 // Don't return false here: we allow this for compatibility in
1225 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001226 }
1227
Richard Smith9f569cc2011-10-01 02:31:28 +00001228 return true;
1229}
1230
Douglas Gregorb48fe382008-10-31 09:07:45 +00001231/// isCurrentClassName - Determine whether the identifier II is the
1232/// name of the class type currently being defined. In the case of
1233/// nested classes, this will only return true if II is the name of
1234/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001235bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1236 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001237 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001238
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001239 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001240 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001241 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001242 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1243 } else
1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1245
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001246 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001247 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001248 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001249}
1250
Richard Smithb79b17b2013-10-15 00:00:26 +00001251/// \brief Determine whether the identifier II is a typo for the name of
1252/// the class type currently being defined. If so, update it to the identifier
1253/// that should have been used.
1254bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1255 assert(getLangOpts().CPlusPlus && "No class names in C!");
1256
1257 if (!getLangOpts().SpellChecking)
1258 return false;
1259
1260 CXXRecordDecl *CurDecl;
1261 if (SS && SS->isSet() && !SS->isInvalid()) {
1262 DeclContext *DC = computeDeclContext(*SS, true);
1263 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1264 } else
1265 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1266
1267 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1268 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1269 < II->getLength()) {
1270 II = CurDecl->getIdentifier();
1271 return true;
1272 }
1273
1274 return false;
1275}
1276
Douglas Gregor229d47a2012-11-10 07:24:09 +00001277/// \brief Determine whether the given class is a base class of the given
1278/// class, including looking at dependent bases.
1279static bool findCircularInheritance(const CXXRecordDecl *Class,
1280 const CXXRecordDecl *Current) {
1281 SmallVector<const CXXRecordDecl*, 8> Queue;
1282
1283 Class = Class->getCanonicalDecl();
1284 while (true) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001285 for (const auto &I : Current->bases()) {
1286 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001287 if (!Base)
1288 continue;
1289
1290 Base = Base->getDefinition();
1291 if (!Base)
1292 continue;
1293
1294 if (Base->getCanonicalDecl() == Class)
1295 return true;
1296
1297 Queue.push_back(Base);
1298 }
1299
1300 if (Queue.empty())
1301 return false;
1302
Robert Wilhelm344472e2013-08-23 16:11:15 +00001303 Current = Queue.pop_back_val();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001304 }
1305
1306 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001307}
1308
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001309/// \brief Perform propagation of DLL attributes from a derived class to a
1310/// templated base class for MS compatibility.
1311static void propagateDLLAttrToBaseClassTemplate(
1312 Sema &S, CXXRecordDecl *Class, Attr *ClassAttr,
1313 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
1314 if (getDLLAttr(
1315 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
1316 // If the base class template has a DLL attribute, don't try to change it.
1317 return;
1318 }
1319
1320 if (BaseTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1321 // If the base class is not already specialized, we can do the propagation.
1322 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
1323 NewAttr->setInherited(true);
1324 BaseTemplateSpec->addAttr(NewAttr);
1325 return;
1326 }
1327
1328 bool DifferentAttribute = false;
1329 if (Attr *SpecializationAttr = getDLLAttr(BaseTemplateSpec)) {
1330 if (!SpecializationAttr->isInherited()) {
1331 // The template has previously been specialized or instantiated with an
1332 // explicit attribute. We should not try to change it.
1333 return;
1334 }
1335 if (SpecializationAttr->getKind() == ClassAttr->getKind()) {
1336 // The specialization already has the right attribute.
1337 return;
1338 }
1339 DifferentAttribute = true;
1340 }
1341
1342 // The template was previously instantiated or explicitly specialized without
1343 // a dll attribute, or the template was previously instantiated with a
1344 // different inherited attribute. It's too late for us to change the
1345 // attribute, so warn that this is unsupported.
1346 S.Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
1347 << BaseTemplateSpec->isExplicitSpecialization() << DifferentAttribute;
1348 S.Diag(ClassAttr->getLocation(), diag::note_attribute);
1349 if (BaseTemplateSpec->isExplicitSpecialization()) {
1350 S.Diag(BaseTemplateSpec->getLocation(),
1351 diag::note_template_class_explicit_specialization_was_here)
1352 << BaseTemplateSpec;
1353 } else {
1354 S.Diag(BaseTemplateSpec->getPointOfInstantiation(),
1355 diag::note_template_class_instantiation_was_here)
1356 << BaseTemplateSpec;
1357 }
1358}
1359
Mike Stump1eb44332009-09-09 15:08:12 +00001360/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001361///
1362/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1363/// and returns NULL otherwise.
1364CXXBaseSpecifier *
1365Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1366 SourceRange SpecifierRange,
1367 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001368 TypeSourceInfo *TInfo,
1369 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001370 QualType BaseType = TInfo->getType();
1371
Douglas Gregor2943aed2009-03-03 04:44:36 +00001372 // C++ [class.union]p1:
1373 // A union shall not have base classes.
1374 if (Class->isUnion()) {
1375 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1376 << SpecifierRange;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001377 return nullptr;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001378 }
1379
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001380 if (EllipsisLoc.isValid() &&
1381 !TInfo->getType()->containsUnexpandedParameterPack()) {
1382 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1383 << TInfo->getTypeLoc().getSourceRange();
1384 EllipsisLoc = SourceLocation();
1385 }
Douglas Gregord777e282012-11-10 01:18:17 +00001386
1387 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1388
1389 if (BaseType->isDependentType()) {
1390 // Make sure that we don't have circular inheritance among our dependent
1391 // bases. For non-dependent bases, the check for completeness below handles
1392 // this.
1393 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1394 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1395 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001396 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001397 Diag(BaseLoc, diag::err_circular_inheritance)
1398 << BaseType << Context.getTypeDeclType(Class);
1399
1400 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1401 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1402 << BaseType;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001403
1404 return nullptr;
Douglas Gregord777e282012-11-10 01:18:17 +00001405 }
1406 }
1407
Mike Stump1eb44332009-09-09 15:08:12 +00001408 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001409 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001410 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001411 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001412
1413 // Base specifiers must be record types.
1414 if (!BaseType->isRecordType()) {
1415 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001416 return nullptr;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001417 }
1418
1419 // C++ [class.union]p1:
1420 // A union shall not be used as a base class.
1421 if (BaseType->isUnionType()) {
1422 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001423 return nullptr;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001424 }
1425
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001426 // For the MS ABI, propagate DLL attributes to base class templates.
1427 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1428 if (Attr *ClassAttr = getDLLAttr(Class)) {
1429 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1430 BaseType->getAsCXXRecordDecl())) {
1431 propagateDLLAttrToBaseClassTemplate(*this, Class, ClassAttr,
1432 BaseTemplate, BaseLoc);
1433 }
1434 }
1435 }
1436
Douglas Gregor2943aed2009-03-03 04:44:36 +00001437 // C++ [class.derived]p2:
1438 // The class-name in a base-specifier shall not be an incompletely
1439 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001440 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001441 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001442 Class->setInvalidDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001443 return nullptr;
John McCall572fc622010-08-17 07:23:57 +00001444 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001445
Eli Friedman1d954f62009-08-15 21:55:26 +00001446 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001447 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001448 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001449 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001450 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001451 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001452 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001453
David Majnemer28165b72013-11-02 12:00:36 +00001454 // A class which contains a flexible array member is not suitable for use as a
1455 // base class:
1456 // - If the layout determines that a base comes before another base,
1457 // the flexible array member would index into the subsequent base.
1458 // - If the layout determines that base comes before the derived class,
1459 // the flexible array member would index into the derived class.
1460 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1461 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1462 << CXXBaseDecl->getDeclName();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001463 return nullptr;
David Majnemer28165b72013-11-02 12:00:36 +00001464 }
1465
Anders Carlsson1d209272011-03-25 14:55:14 +00001466 // C++ [class]p3:
David Majnemer7041fcc2013-11-02 11:24:41 +00001467 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson1d209272011-03-25 14:55:14 +00001468 // base-clause, the program is ill-formed.
David Majnemer7121bdb2013-10-18 00:33:31 +00001469 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer7041fcc2013-11-02 11:24:41 +00001470 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemer7121bdb2013-10-18 00:33:31 +00001471 << CXXBaseDecl->getDeclName()
1472 << FA->isSpelledAsSealed();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001473 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
1474 << CXXBaseDecl->getDeclName() << FA->getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001475 return nullptr;
Anders Carlssondfc2f102011-01-22 17:51:53 +00001476 }
1477
John McCall572fc622010-08-17 07:23:57 +00001478 if (BaseDecl->isInvalidDecl())
1479 Class->setInvalidDecl();
David Majnemer7041fcc2013-11-02 11:24:41 +00001480
Anders Carlsson51f94042009-12-03 17:49:57 +00001481 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001482 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001483 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001484 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001485}
1486
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001487/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1488/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001489/// example:
1490/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001491/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001492BaseResult
John McCalld226f652010-08-21 09:40:31 +00001493Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001494 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001495 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001496 ParsedType basetype, SourceLocation BaseLoc,
1497 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001498 if (!classdecl)
1499 return true;
1500
Douglas Gregor40808ce2009-03-09 23:48:35 +00001501 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001502 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001503 if (!Class)
1504 return true;
1505
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001506 // We haven't yet attached the base specifiers.
1507 Class->setIsParsingBaseSpecifiers();
1508
Richard Smith05321402013-02-19 23:47:15 +00001509 // We do not support any C++11 attributes on base-specifiers yet.
1510 // Diagnose any attributes we see.
1511 if (!Attributes.empty()) {
1512 for (AttributeList *Attr = Attributes.getList(); Attr;
1513 Attr = Attr->getNext()) {
1514 if (Attr->isInvalid() ||
1515 Attr->getKind() == AttributeList::IgnoredAttribute)
1516 continue;
1517 Diag(Attr->getLoc(),
1518 Attr->getKind() == AttributeList::UnknownAttribute
1519 ? diag::warn_unknown_attribute_ignored
1520 : diag::err_base_specifier_attribute)
1521 << Attr->getName();
1522 }
1523 }
1524
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001525 TypeSourceInfo *TInfo = nullptr;
Nick Lewycky56062202010-07-26 16:56:01 +00001526 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001527
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001528 if (EllipsisLoc.isInvalid() &&
1529 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001530 UPPC_BaseType))
1531 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001532
Douglas Gregor2943aed2009-03-03 04:44:36 +00001533 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001534 Virtual, Access, TInfo,
1535 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001536 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001537 else
1538 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Douglas Gregor2943aed2009-03-03 04:44:36 +00001540 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001541}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001542
Douglas Gregor2943aed2009-03-03 04:44:36 +00001543/// \brief Performs the actual work of attaching the given base class
1544/// specifiers to a C++ class.
1545bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1546 unsigned NumBases) {
1547 if (NumBases == 0)
1548 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001549
1550 // Used to keep track of which base types we have already seen, so
1551 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001552 // that the key is always the unqualified canonical type of the base
1553 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001554 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1555
1556 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001557 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001558 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001559 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001560 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001561 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001562 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001563
1564 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1565 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001566 // C++ [class.mi]p3:
1567 // A class shall not be specified as a direct base class of a
1568 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001569 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001570 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001571 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001572 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001573
1574 // Delete the duplicate base class specifier; we're going to
1575 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001576 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001577
1578 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001579 } else {
1580 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001581 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001582 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001583 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1584 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1585 if (Class->isInterface() &&
1586 (!RD->isInterface() ||
1587 KnownBase->getAccessSpecifier() != AS_public)) {
1588 // The Microsoft extension __interface does not permit bases that
1589 // are not themselves public interfaces.
1590 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1591 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1592 << RD->getSourceRange();
1593 Invalid = true;
1594 }
1595 if (RD->hasAttr<WeakAttr>())
Stephen Hines651f13c2014-04-23 16:59:28 -07001596 Class->addAttr(WeakAttr::CreateImplicit(Context));
John McCalle402e722012-09-25 07:32:39 +00001597 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001598 }
1599 }
1600
1601 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001602 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001603
1604 // Delete the remaining (good) base class specifiers, since their
1605 // data has been copied into the CXXRecordDecl.
1606 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001607 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001608
1609 return Invalid;
1610}
1611
1612/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1613/// class, after checking whether there are any duplicate base
1614/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001615void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001616 unsigned NumBases) {
1617 if (!ClassDecl || !Bases || !NumBases)
1618 return;
1619
1620 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001621 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001622}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001623
Douglas Gregora8f32e02009-10-06 17:59:45 +00001624/// \brief Determine whether the type \p Derived is a C++ class that is
1625/// derived from the type \p Base.
1626bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001627 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001628 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001629
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001630 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001631 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001632 return false;
1633
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001634 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001635 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001636 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001637
1638 // If either the base or the derived type is invalid, don't try to
1639 // check whether one is derived from the other.
1640 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1641 return false;
1642
John McCall86ff3082010-02-04 22:26:26 +00001643 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1644 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001645}
1646
1647/// \brief Determine whether the type \p Derived is a C++ class that is
1648/// derived from the type \p Base.
1649bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001650 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001651 return false;
1652
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001653 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001654 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001655 return false;
1656
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001657 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001658 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001659 return false;
1660
Douglas Gregora8f32e02009-10-06 17:59:45 +00001661 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1662}
1663
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001664void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001665 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001666 assert(BasePathArray.empty() && "Base path array must be empty!");
1667 assert(Paths.isRecordingPaths() && "Must record paths!");
1668
1669 const CXXBasePath &Path = Paths.front();
1670
1671 // We first go backward and check if we have a virtual base.
1672 // FIXME: It would be better if CXXBasePath had the base specifier for
1673 // the nearest virtual base.
1674 unsigned Start = 0;
1675 for (unsigned I = Path.size(); I != 0; --I) {
1676 if (Path[I - 1].Base->isVirtual()) {
1677 Start = I - 1;
1678 break;
1679 }
1680 }
1681
1682 // Now add all bases.
1683 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001684 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001685}
1686
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001687/// \brief Determine whether the given base path includes a virtual
1688/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001689bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1690 for (CXXCastPath::const_iterator B = BasePath.begin(),
1691 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001692 B != BEnd; ++B)
1693 if ((*B)->isVirtual())
1694 return true;
1695
1696 return false;
1697}
1698
Douglas Gregora8f32e02009-10-06 17:59:45 +00001699/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1700/// conversion (where Derived and Base are class types) is
1701/// well-formed, meaning that the conversion is unambiguous (and
1702/// that all of the base classes are accessible). Returns true
1703/// and emits a diagnostic if the code is ill-formed, returns false
1704/// otherwise. Loc is the location where this routine should point to
1705/// if there is an error, and Range is the source range to highlight
1706/// if there is an error.
1707bool
1708Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001709 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001710 unsigned AmbigiousBaseConvID,
1711 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001712 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001713 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001714 // First, determine whether the path from Derived to Base is
1715 // ambiguous. This is slightly more expensive than checking whether
1716 // the Derived to Base conversion exists, because here we need to
1717 // explore multiple paths to determine if there is an ambiguity.
1718 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1719 /*DetectVirtual=*/false);
1720 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1721 assert(DerivationOkay &&
1722 "Can only be used with a derived-to-base conversion");
1723 (void)DerivationOkay;
1724
1725 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001726 if (InaccessibleBaseID) {
1727 // Check that the base class can be accessed.
1728 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1729 InaccessibleBaseID)) {
1730 case AR_inaccessible:
1731 return true;
1732 case AR_accessible:
1733 case AR_dependent:
1734 case AR_delayed:
1735 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001736 }
John McCall6b2accb2010-02-10 09:31:12 +00001737 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001738
1739 // Build a base path if necessary.
1740 if (BasePath)
1741 BuildBasePathArray(Paths, *BasePath);
1742 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001743 }
1744
David Majnemer2f686692013-06-22 06:43:58 +00001745 if (AmbigiousBaseConvID) {
1746 // We know that the derived-to-base conversion is ambiguous, and
1747 // we're going to produce a diagnostic. Perform the derived-to-base
1748 // search just one more time to compute all of the possible paths so
1749 // that we can print them out. This is more expensive than any of
1750 // the previous derived-to-base checks we've done, but at this point
1751 // performance isn't as much of an issue.
1752 Paths.clear();
1753 Paths.setRecordingPaths(true);
1754 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1755 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1756 (void)StillOkay;
1757
1758 // Build up a textual representation of the ambiguous paths, e.g.,
1759 // D -> B -> A, that will be used to illustrate the ambiguous
1760 // conversions in the diagnostic. We only print one of the paths
1761 // to each base class subobject.
1762 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1763
1764 Diag(Loc, AmbigiousBaseConvID)
1765 << Derived << Base << PathDisplayStr << Range << Name;
1766 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001767 return true;
1768}
1769
1770bool
1771Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001772 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001773 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001774 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001775 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001776 IgnoreAccess ? 0
1777 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001778 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001779 Loc, Range, DeclarationName(),
1780 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001781}
1782
1783
1784/// @brief Builds a string representing ambiguous paths from a
1785/// specific derived class to different subobjects of the same base
1786/// class.
1787///
1788/// This function builds a string that can be used in error messages
1789/// to show the different paths that one can take through the
1790/// inheritance hierarchy to go from the derived class to different
1791/// subobjects of a base class. The result looks something like this:
1792/// @code
1793/// struct D -> struct B -> struct A
1794/// struct D -> struct C -> struct A
1795/// @endcode
1796std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1797 std::string PathDisplayStr;
1798 std::set<unsigned> DisplayedPaths;
1799 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1800 Path != Paths.end(); ++Path) {
1801 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1802 // We haven't displayed a path to this particular base
1803 // class subobject yet.
1804 PathDisplayStr += "\n ";
1805 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1806 for (CXXBasePath::const_iterator Element = Path->begin();
1807 Element != Path->end(); ++Element)
1808 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1809 }
1810 }
1811
1812 return PathDisplayStr;
1813}
1814
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001815//===----------------------------------------------------------------------===//
1816// C++ class member Handling
1817//===----------------------------------------------------------------------===//
1818
Abramo Bagnara6206d532010-06-05 05:09:32 +00001819/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001820bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1821 SourceLocation ASLoc,
1822 SourceLocation ColonLoc,
1823 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001824 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001825 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001826 ASLoc, ColonLoc);
1827 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001828 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001829}
1830
Richard Smitha4b39652012-08-06 03:25:17 +00001831/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmandae92712013-09-05 23:51:03 +00001832void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001833 if (D->isInvalidDecl())
1834 return;
1835
Eli Friedmandae92712013-09-05 23:51:03 +00001836 // We only care about "override" and "final" declarations.
1837 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1838 return;
Anders Carlsson9e682d92011-01-20 05:57:14 +00001839
Eli Friedmandae92712013-09-05 23:51:03 +00001840 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001841
Eli Friedmandae92712013-09-05 23:51:03 +00001842 // We can't check dependent instance methods.
1843 if (MD && MD->isInstance() &&
1844 (MD->getParent()->hasAnyDependentBases() ||
1845 MD->getType()->isDependentType()))
1846 return;
1847
1848 if (MD && !MD->isVirtual()) {
1849 // If we have a non-virtual method, check if if hides a virtual method.
1850 // (In that case, it's most likely the method has the wrong type.)
1851 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1852 FindHiddenVirtualMethods(MD, OverloadedMethods);
1853
1854 if (!OverloadedMethods.empty()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001855 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1856 Diag(OA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001857 diag::override_keyword_hides_virtual_member_function)
1858 << "override" << (OverloadedMethods.size() > 1);
1859 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001860 Diag(FA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001861 diag::override_keyword_hides_virtual_member_function)
David Majnemer7121bdb2013-10-18 00:33:31 +00001862 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1863 << (OverloadedMethods.size() > 1);
Richard Smitha4b39652012-08-06 03:25:17 +00001864 }
Eli Friedmandae92712013-09-05 23:51:03 +00001865 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1866 MD->setInvalidDecl();
1867 return;
1868 }
1869 // Fall through into the general case diagnostic.
1870 // FIXME: We might want to attempt typo correction here.
1871 }
1872
1873 if (!MD || !MD->isVirtual()) {
1874 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1875 Diag(OA->getLocation(),
1876 diag::override_keyword_only_allowed_on_virtual_member_functions)
1877 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1878 D->dropAttr<OverrideAttr>();
1879 }
1880 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1881 Diag(FA->getLocation(),
1882 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemer7121bdb2013-10-18 00:33:31 +00001883 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1884 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmandae92712013-09-05 23:51:03 +00001885 D->dropAttr<FinalAttr>();
Richard Smitha4b39652012-08-06 03:25:17 +00001886 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001887 return;
1888 }
Richard Smitha4b39652012-08-06 03:25:17 +00001889
Richard Smitha4b39652012-08-06 03:25:17 +00001890 // C++11 [class.virtual]p5:
Stephen Hines176edba2014-12-01 14:53:08 -08001891 // If a function is marked with the virt-specifier override and
Richard Smitha4b39652012-08-06 03:25:17 +00001892 // does not override a member function of a base class, the program is
1893 // ill-formed.
1894 bool HasOverriddenMethods =
1895 MD->begin_overridden_methods() != MD->end_overridden_methods();
1896 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1897 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1898 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001899}
1900
Stephen Hines176edba2014-12-01 14:53:08 -08001901void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
1902 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
1903 return;
1904 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1905 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>() ||
1906 isa<CXXDestructorDecl>(MD))
1907 return;
1908
1909 SourceLocation Loc = MD->getLocation();
1910 SourceLocation SpellingLoc = Loc;
1911 if (getSourceManager().isMacroArgExpansion(Loc))
1912 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
1913 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
1914 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
1915 return;
1916
1917 if (MD->size_overridden_methods() > 0) {
1918 Diag(MD->getLocation(), diag::warn_function_marked_not_override_overriding)
1919 << MD->getDeclName();
1920 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
1921 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
1922 }
1923}
1924
Richard Smitha4b39652012-08-06 03:25:17 +00001925/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001926/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001927/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001928bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1929 const CXXMethodDecl *Old) {
David Majnemer7121bdb2013-10-18 00:33:31 +00001930 FinalAttr *FA = Old->getAttr<FinalAttr>();
1931 if (!FA)
Anders Carlssonf89e0422011-01-23 21:07:30 +00001932 return false;
1933
1934 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemer7121bdb2013-10-18 00:33:31 +00001935 << New->getDeclName()
1936 << FA->isSpelledAsSealed();
Anders Carlssonf89e0422011-01-23 21:07:30 +00001937 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1938 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001939}
1940
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001941static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001942 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1943 // FIXME: Destruction of ObjC lifetime types has side-effects.
1944 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1945 return !RD->isCompleteDefinition() ||
1946 !RD->hasTrivialDefaultConstructor() ||
1947 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001948 return false;
1949}
1950
John McCall76da55d2013-04-16 07:28:30 +00001951static AttributeList *getMSPropertyAttr(AttributeList *list) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001952 for (AttributeList *it = list; it != nullptr; it = it->getNext())
John McCall76da55d2013-04-16 07:28:30 +00001953 if (it->isDeclspecPropertyAttribute())
1954 return it;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001955 return nullptr;
John McCall76da55d2013-04-16 07:28:30 +00001956}
1957
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001958/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1959/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001960/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001961/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1962/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001963NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001964Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001965 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001966 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001967 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001968 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001969 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1970 DeclarationName Name = NameInfo.getName();
1971 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001972
1973 // For anonymous bitfields, the location should point to the type.
1974 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001975 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001976
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001977 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001978
John McCall4bde1e12010-06-04 08:34:12 +00001979 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001980 assert(!DS.isFriendSpecified());
1981
Richard Smith1ab0d902011-06-25 02:28:38 +00001982 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001983
John McCalle402e722012-09-25 07:32:39 +00001984 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1985 // The Microsoft extension __interface only permits public member functions
1986 // and prohibits constructors, destructors, operators, non-public member
1987 // functions, static methods and data members.
1988 unsigned InvalidDecl;
1989 bool ShowDeclName = true;
1990 if (!isFunc)
1991 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1992 else if (AS != AS_public)
1993 InvalidDecl = 2;
1994 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1995 InvalidDecl = 3;
1996 else switch (Name.getNameKind()) {
1997 case DeclarationName::CXXConstructorName:
1998 InvalidDecl = 4;
1999 ShowDeclName = false;
2000 break;
2001
2002 case DeclarationName::CXXDestructorName:
2003 InvalidDecl = 5;
2004 ShowDeclName = false;
2005 break;
2006
2007 case DeclarationName::CXXOperatorName:
2008 case DeclarationName::CXXConversionFunctionName:
2009 InvalidDecl = 6;
2010 break;
2011
2012 default:
2013 InvalidDecl = 0;
2014 break;
2015 }
2016
2017 if (InvalidDecl) {
2018 if (ShowDeclName)
2019 Diag(Loc, diag::err_invalid_member_in_interface)
2020 << (InvalidDecl-1) << Name;
2021 else
2022 Diag(Loc, diag::err_invalid_member_in_interface)
2023 << (InvalidDecl-1) << "";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002024 return nullptr;
John McCalle402e722012-09-25 07:32:39 +00002025 }
2026 }
2027
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002028 // C++ 9.2p6: A member shall not be declared to have automatic storage
2029 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00002030 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2031 // data members and cannot be applied to names declared const or static,
2032 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002033 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00002034 case DeclSpec::SCS_unspecified:
2035 case DeclSpec::SCS_typedef:
2036 case DeclSpec::SCS_static:
2037 break;
2038 case DeclSpec::SCS_mutable:
2039 if (isFunc) {
2040 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Richard Smithec642442013-04-12 22:46:28 +00002042 // FIXME: It would be nicer if the keyword was ignored only for this
2043 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002044 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00002045 }
2046 break;
2047 default:
2048 Diag(DS.getStorageClassSpecLoc(),
2049 diag::err_storageclass_invalid_for_member);
2050 D.getMutableDeclSpec().ClearStorageClassSpecs();
2051 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002052 }
2053
Sebastian Redl669d5d72008-11-14 23:42:31 +00002054 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2055 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00002056 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002057
David Blaikie1d87fba2013-01-30 01:22:18 +00002058 if (DS.isConstexprSpecified() && isInstField) {
2059 SemaDiagnosticBuilder B =
2060 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2061 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2062 if (InitStyle == ICIS_NoInit) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002063 B << 0 << 0;
2064 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2065 B << FixItHint::CreateRemoval(ConstexprLoc);
2066 else {
2067 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2068 D.getMutableDeclSpec().ClearConstexprSpec();
2069 const char *PrevSpec;
2070 unsigned DiagID;
2071 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2072 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2073 (void)Failed;
2074 assert(!Failed && "Making a constexpr member const shouldn't fail");
2075 }
David Blaikie1d87fba2013-01-30 01:22:18 +00002076 } else {
2077 B << 1;
2078 const char *PrevSpec;
2079 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00002080 if (D.getMutableDeclSpec().SetStorageClassSpec(
Stephen Hines651f13c2014-04-23 16:59:28 -07002081 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2082 Context.getPrintingPolicy())) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00002083 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00002084 "This is the only DeclSpec that should fail to be applied");
2085 B << 1;
2086 } else {
2087 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2088 isInstField = false;
2089 }
2090 }
2091 }
2092
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00002093 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00002094 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00002095 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00002096
2097 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00002098 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00002099 Diag(Loc, diag::err_bad_variable_name)
2100 << Name;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002101 return nullptr;
Douglas Gregorb5a01872011-10-09 18:55:59 +00002102 }
Douglas Gregorf2503652011-09-21 14:40:46 +00002103
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00002104 IdentifierInfo *II = Name.getAsIdentifierInfo();
2105
Douglas Gregorf2503652011-09-21 14:40:46 +00002106 // Member field could not be with "template" keyword.
2107 // So TemplateParameterLists should be empty in this case.
2108 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002109 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00002110 if (TemplateParams->size()) {
2111 // There is no such thing as a member field template.
2112 Diag(D.getIdentifierLoc(), diag::err_template_member)
2113 << II
2114 << SourceRange(TemplateParams->getTemplateLoc(),
2115 TemplateParams->getRAngleLoc());
2116 } else {
2117 // There is an extraneous 'template<>' for this member.
2118 Diag(TemplateParams->getTemplateLoc(),
2119 diag::err_template_member_noparams)
2120 << II
2121 << SourceRange(TemplateParams->getTemplateLoc(),
2122 TemplateParams->getRAngleLoc());
2123 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002124 return nullptr;
Douglas Gregorf2503652011-09-21 14:40:46 +00002125 }
2126
Douglas Gregor922fff22010-10-13 22:19:53 +00002127 if (SS.isSet() && !SS.isInvalid()) {
2128 // The user provided a superfluous scope specifier inside a class
2129 // definition:
2130 //
2131 // class X {
2132 // int X::member;
2133 // };
Douglas Gregor69605872012-03-28 16:01:27 +00002134 if (DeclContext *DC = computeDeclContext(SS, false))
2135 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00002136 else
2137 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2138 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00002139
Douglas Gregor922fff22010-10-13 22:19:53 +00002140 SS.clear();
2141 }
Douglas Gregorf2503652011-09-21 14:40:46 +00002142
John McCall76da55d2013-04-16 07:28:30 +00002143 AttributeList *MSPropertyAttr =
2144 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00002145 if (MSPropertyAttr) {
2146 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2147 BitWidth, InitStyle, AS, MSPropertyAttr);
2148 if (!Member)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002149 return nullptr;
Eli Friedmanb26f0122013-06-28 20:48:34 +00002150 isInstField = false;
2151 } else {
2152 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2153 BitWidth, InitStyle, AS);
2154 assert(Member && "HandleField never returns null");
2155 }
2156 } else {
2157 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2158
2159 Member = HandleDeclarator(S, D, TemplateParameterLists);
2160 if (!Member)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002161 return nullptr;
Eli Friedmanb26f0122013-06-28 20:48:34 +00002162
2163 // Non-instance-fields can't have a bitfield.
2164 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002165 if (Member->isInvalidDecl()) {
2166 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002167 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002168 // C++ 9.6p3: A bit-field shall not be a static member.
2169 // "static member 'A' cannot be a bit-field"
2170 Diag(Loc, diag::err_static_not_bitfield)
2171 << Name << BitWidth->getSourceRange();
2172 } else if (isa<TypedefDecl>(Member)) {
2173 // "typedef member 'x' cannot be a bit-field"
2174 Diag(Loc, diag::err_typedef_not_bitfield)
2175 << Name << BitWidth->getSourceRange();
2176 } else {
2177 // A function typedef ("typedef int f(); f a;").
2178 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2179 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00002180 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00002181 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00002182 }
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002184 BitWidth = nullptr;
Chris Lattner8b963ef2009-03-05 23:01:03 +00002185 Member->setInvalidDecl();
2186 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002187
2188 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Larisse Voufoef4579c2013-08-06 01:03:05 +00002190 // If we have declared a member function template or static data member
2191 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002192 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2193 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002194 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2195 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002196 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002197
Richard Smitha4b39652012-08-06 03:25:17 +00002198 if (VS.isOverrideSpecified())
Stephen Hines651f13c2014-04-23 16:59:28 -07002199 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
Richard Smitha4b39652012-08-06 03:25:17 +00002200 if (VS.isFinalSpecified())
David Majnemer7121bdb2013-10-18 00:33:31 +00002201 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2202 VS.isFinalSpelledSealed()));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002203
Douglas Gregorf5251602011-03-08 17:10:18 +00002204 if (VS.getLastLocation().isValid()) {
2205 // Update the end location of a method that has a virt-specifiers.
2206 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2207 MD->setRangeEnd(VS.getLastLocation());
2208 }
Richard Smitha4b39652012-08-06 03:25:17 +00002209
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002210 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002211
Douglas Gregor10bd3682008-11-17 22:58:34 +00002212 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002213
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002214 if (isInstField) {
2215 FieldDecl *FD = cast<FieldDecl>(Member);
2216 FieldCollector->Add(FD);
2217
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002218 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002219 // Remember all explicit private FieldDecls that have a name, no side
2220 // effects and are not part of a dependent type declaration.
2221 if (!FD->isImplicit() && FD->getDeclName() &&
2222 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002223 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002224 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002225 !InitializationHasSideEffects(*FD))
2226 UnusedPrivateFields.insert(FD);
2227 }
2228 }
2229
John McCalld226f652010-08-21 09:40:31 +00002230 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002231}
2232
Hans Wennborg471f9852012-09-18 15:58:06 +00002233namespace {
2234 class UninitializedFieldVisitor
2235 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2236 Sema &S;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002237 // List of Decls to generate a warning on. Also remove Decls that become
2238 // initialized.
Stephen Hines176edba2014-12-01 14:53:08 -08002239 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
2240 // Vector of decls to be removed from the Decl set prior to visiting the
2241 // nodes. These Decls may have been initialized in the prior initializer.
2242 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002243 // If non-null, add a note to the warning pointing back to the constructor.
2244 const CXXConstructorDecl *Constructor;
Stephen Hines176edba2014-12-01 14:53:08 -08002245 // Variables to hold state when processing an initializer list. When
2246 // InitList is true, special case initialization of FieldDecls matching
2247 // InitListFieldDecl.
2248 bool InitList;
2249 FieldDecl *InitListFieldDecl;
2250 llvm::SmallVector<unsigned, 4> InitFieldIndex;
2251
Hans Wennborg471f9852012-09-18 15:58:06 +00002252 public:
2253 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002254 UninitializedFieldVisitor(Sema &S,
Stephen Hines176edba2014-12-01 14:53:08 -08002255 llvm::SmallPtrSetImpl<ValueDecl*> &Decls)
2256 : Inherited(S.Context), S(S), Decls(Decls), Constructor(nullptr),
2257 InitList(false), InitListFieldDecl(nullptr) {}
Hans Wennborg471f9852012-09-18 15:58:06 +00002258
Stephen Hines176edba2014-12-01 14:53:08 -08002259 // Returns true if the use of ME is not an uninitialized use.
2260 bool IsInitListMemberExprInitialized(MemberExpr *ME,
2261 bool CheckReferenceOnly) {
2262 llvm::SmallVector<FieldDecl*, 4> Fields;
2263 bool ReferenceField = false;
2264 while (ME) {
2265 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
2266 if (!FD)
2267 return false;
2268 Fields.push_back(FD);
2269 if (FD->getType()->isReferenceType())
2270 ReferenceField = true;
2271 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
2272 }
2273
2274 // Binding a reference to an unintialized field is not an
2275 // uninitialized use.
2276 if (CheckReferenceOnly && !ReferenceField)
2277 return true;
2278
2279 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
2280 // Discard the first field since it is the field decl that is being
2281 // initialized.
2282 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
2283 UsedFieldIndex.push_back((*I)->getFieldIndex());
2284 }
2285
2286 for (auto UsedIter = UsedFieldIndex.begin(),
2287 UsedEnd = UsedFieldIndex.end(),
2288 OrigIter = InitFieldIndex.begin(),
2289 OrigEnd = InitFieldIndex.end();
2290 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
2291 if (*UsedIter < *OrigIter)
2292 return true;
2293 if (*UsedIter > *OrigIter)
2294 break;
2295 }
2296
2297 return false;
2298 }
2299
2300 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
2301 bool AddressOf) {
Richard Trieufbb08b52013-09-13 03:20:53 +00002302 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2303 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002304
Richard Trieufbb08b52013-09-13 03:20:53 +00002305 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2306 // or union.
2307 MemberExpr *FieldME = ME;
2308
Stephen Hines176edba2014-12-01 14:53:08 -08002309 bool AllPODFields = FieldME->getType().isPODType(S.Context);
Richard Trieufbb08b52013-09-13 03:20:53 +00002310
Stephen Hines176edba2014-12-01 14:53:08 -08002311 Expr *Base = ME;
2312 while (MemberExpr *SubME = dyn_cast<MemberExpr>(Base)) {
2313
2314 if (isa<VarDecl>(SubME->getMemberDecl()))
Richard Trieufbb08b52013-09-13 03:20:53 +00002315 return;
2316
Stephen Hines176edba2014-12-01 14:53:08 -08002317 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
Richard Trieufbb08b52013-09-13 03:20:53 +00002318 if (!FD->isAnonymousStructOrUnion())
Stephen Hines176edba2014-12-01 14:53:08 -08002319 FieldME = SubME;
Richard Trieufbb08b52013-09-13 03:20:53 +00002320
Stephen Hines176edba2014-12-01 14:53:08 -08002321 if (!FieldME->getType().isPODType(S.Context))
2322 AllPODFields = false;
2323
2324 Base = SubME->getBase()->IgnoreParenImpCasts();
Richard Trieufbb08b52013-09-13 03:20:53 +00002325 }
2326
Richard Trieu3ddec882013-09-16 20:46:50 +00002327 if (!isa<CXXThisExpr>(Base))
2328 return;
2329
Stephen Hines176edba2014-12-01 14:53:08 -08002330 if (AddressOf && AllPODFields)
2331 return;
2332
Richard Trieuef8f90c2013-09-20 03:03:06 +00002333 ValueDecl* FoundVD = FieldME->getMemberDecl();
2334
Richard Trieu858d2ba2013-10-25 00:56:00 +00002335 if (!Decls.count(FoundVD))
Richard Trieuef8f90c2013-09-20 03:03:06 +00002336 return;
2337
Richard Trieu858d2ba2013-10-25 00:56:00 +00002338 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieuef8f90c2013-09-20 03:03:06 +00002339
Stephen Hines176edba2014-12-01 14:53:08 -08002340 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
2341 // Special checking for initializer lists.
2342 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
2343 return;
2344 }
2345 } else {
2346 // Prevent double warnings on use of unbounded references.
2347 if (CheckReferenceOnly && !IsReference)
2348 return;
2349 }
Richard Trieu858d2ba2013-10-25 00:56:00 +00002350
2351 unsigned diag = IsReference
2352 ? diag::warn_reference_field_is_uninit
2353 : diag::warn_field_is_uninit;
2354 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2355 if (Constructor)
2356 S.Diag(Constructor->getLocation(),
2357 diag::note_uninit_in_this_constructor)
2358 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2359
Hans Wennborg471f9852012-09-18 15:58:06 +00002360 }
2361
Stephen Hines176edba2014-12-01 14:53:08 -08002362 void HandleValue(Expr *E, bool AddressOf) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002363 E = E->IgnoreParens();
2364
2365 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Stephen Hines176edba2014-12-01 14:53:08 -08002366 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
2367 AddressOf /*AddressOf*/);
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002368 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002369 }
2370
2371 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
Stephen Hines176edba2014-12-01 14:53:08 -08002372 Visit(CO->getCond());
2373 HandleValue(CO->getTrueExpr(), AddressOf);
2374 HandleValue(CO->getFalseExpr(), AddressOf);
Hans Wennborg471f9852012-09-18 15:58:06 +00002375 return;
2376 }
2377
2378 if (BinaryConditionalOperator *BCO =
2379 dyn_cast<BinaryConditionalOperator>(E)) {
Stephen Hines176edba2014-12-01 14:53:08 -08002380 Visit(BCO->getCond());
2381 HandleValue(BCO->getFalseExpr(), AddressOf);
2382 return;
2383 }
2384
2385 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
2386 HandleValue(OVE->getSourceExpr(), AddressOf);
Hans Wennborg471f9852012-09-18 15:58:06 +00002387 return;
2388 }
2389
2390 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2391 switch (BO->getOpcode()) {
2392 default:
Stephen Hines176edba2014-12-01 14:53:08 -08002393 break;
Hans Wennborg471f9852012-09-18 15:58:06 +00002394 case(BO_PtrMemD):
2395 case(BO_PtrMemI):
Stephen Hines176edba2014-12-01 14:53:08 -08002396 HandleValue(BO->getLHS(), AddressOf);
2397 Visit(BO->getRHS());
Hans Wennborg471f9852012-09-18 15:58:06 +00002398 return;
2399 case(BO_Comma):
Stephen Hines176edba2014-12-01 14:53:08 -08002400 Visit(BO->getLHS());
2401 HandleValue(BO->getRHS(), AddressOf);
Hans Wennborg471f9852012-09-18 15:58:06 +00002402 return;
2403 }
2404 }
Stephen Hines176edba2014-12-01 14:53:08 -08002405
2406 Visit(E);
2407 }
2408
2409 void CheckInitListExpr(InitListExpr *ILE) {
2410 InitFieldIndex.push_back(0);
2411 for (auto Child : ILE->children()) {
2412 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
2413 CheckInitListExpr(SubList);
2414 } else {
2415 Visit(Child);
2416 }
2417 ++InitFieldIndex.back();
2418 }
2419 InitFieldIndex.pop_back();
2420 }
2421
2422 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
2423 FieldDecl *Field) {
2424 // Remove Decls that may have been initialized in the previous
2425 // initializer.
2426 for (ValueDecl* VD : DeclsToRemove)
2427 Decls.erase(VD);
2428 DeclsToRemove.clear();
2429
2430 Constructor = FieldConstructor;
2431 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
2432
2433 if (ILE && Field) {
2434 InitList = true;
2435 InitListFieldDecl = Field;
2436 InitFieldIndex.clear();
2437 CheckInitListExpr(ILE);
2438 } else {
2439 InitList = false;
2440 Visit(E);
2441 }
2442
2443 if (Field)
2444 Decls.erase(Field);
Hans Wennborg471f9852012-09-18 15:58:06 +00002445 }
2446
Richard Trieufbb08b52013-09-13 03:20:53 +00002447 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002448 // All uses of unbounded reference fields will warn.
Stephen Hines176edba2014-12-01 14:53:08 -08002449 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002450 }
2451
Hans Wennborg471f9852012-09-18 15:58:06 +00002452 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
Stephen Hines176edba2014-12-01 14:53:08 -08002453 if (E->getCastKind() == CK_LValueToRValue) {
2454 HandleValue(E->getSubExpr(), false /*AddressOf*/);
2455 return;
2456 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002457
2458 Inherited::VisitImplicitCastExpr(E);
2459 }
2460
Richard Trieufbb08b52013-09-13 03:20:53 +00002461 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Stephen Hines176edba2014-12-01 14:53:08 -08002462 if (E->getConstructor()->isCopyConstructor()) {
2463 Expr *ArgExpr = E->getArg(0);
2464 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
2465 if (ILE->getNumInits() == 1)
2466 ArgExpr = ILE->getInit(0);
2467 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
Richard Trieufbb08b52013-09-13 03:20:53 +00002468 if (ICE->getCastKind() == CK_NoOp)
Stephen Hines176edba2014-12-01 14:53:08 -08002469 ArgExpr = ICE->getSubExpr();
2470 HandleValue(ArgExpr, false /*AddressOf*/);
2471 return;
2472 }
Richard Trieufbb08b52013-09-13 03:20:53 +00002473 Inherited::VisitCXXConstructExpr(E);
2474 }
2475
Hans Wennborg471f9852012-09-18 15:58:06 +00002476 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2477 Expr *Callee = E->getCallee();
Stephen Hines176edba2014-12-01 14:53:08 -08002478 if (isa<MemberExpr>(Callee)) {
2479 HandleValue(Callee, false /*AddressOf*/);
2480 for (auto Arg : E->arguments())
2481 Visit(Arg);
2482 return;
2483 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002484
2485 Inherited::VisitCXXMemberCallExpr(E);
2486 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002487
Stephen Hines176edba2014-12-01 14:53:08 -08002488 void VisitCallExpr(CallExpr *E) {
2489 // Treat std::move as a use.
2490 if (E->getNumArgs() == 1) {
2491 if (FunctionDecl *FD = E->getDirectCallee()) {
2492 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) {
2493 HandleValue(E->getArg(0), false /*AddressOf*/);
2494 return;
2495 }
2496 }
2497 }
2498
2499 Inherited::VisitCallExpr(E);
2500 }
2501
2502 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2503 Expr *Callee = E->getCallee();
2504
2505 if (isa<UnresolvedLookupExpr>(Callee))
2506 return Inherited::VisitCXXOperatorCallExpr(E);
2507
2508 Visit(Callee);
2509 for (auto Arg : E->arguments())
2510 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
2511 }
2512
Richard Trieuef8f90c2013-09-20 03:03:06 +00002513 void VisitBinaryOperator(BinaryOperator *E) {
2514 // If a field assignment is detected, remove the field from the
2515 // uninitiailized field set.
2516 if (E->getOpcode() == BO_Assign)
2517 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2518 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieu858d2ba2013-10-25 00:56:00 +00002519 if (!FD->getType()->isReferenceType())
Stephen Hines176edba2014-12-01 14:53:08 -08002520 DeclsToRemove.push_back(FD);
2521
2522 if (E->isCompoundAssignmentOp()) {
2523 HandleValue(E->getLHS(), false /*AddressOf*/);
2524 Visit(E->getRHS());
2525 return;
2526 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002527
2528 Inherited::VisitBinaryOperator(E);
2529 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002530
Stephen Hines176edba2014-12-01 14:53:08 -08002531 void VisitUnaryOperator(UnaryOperator *E) {
2532 if (E->isIncrementDecrementOp()) {
2533 HandleValue(E->getSubExpr(), false /*AddressOf*/);
Richard Trieu858d2ba2013-10-25 00:56:00 +00002534 return;
Stephen Hines176edba2014-12-01 14:53:08 -08002535 }
2536 if (E->getOpcode() == UO_AddrOf) {
2537 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
2538 HandleValue(ME->getBase(), true /*AddressOf*/);
2539 return;
2540 }
2541 }
2542
2543 Inherited::VisitUnaryOperator(E);
Richard Trieu858d2ba2013-10-25 00:56:00 +00002544 }
Stephen Hines176edba2014-12-01 14:53:08 -08002545 };
Richard Trieu858d2ba2013-10-25 00:56:00 +00002546
2547 // Diagnose value-uses of fields to initialize themselves, e.g.
2548 // foo(foo)
2549 // where foo is not also a parameter to the constructor.
2550 // Also diagnose across field uninitialized use such as
2551 // x(y), y(x)
2552 // TODO: implement -Wuninitialized and fold this into that framework.
2553 static void DiagnoseUninitializedFields(
2554 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2555
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002556 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
2557 Constructor->getLocation())) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002558 return;
2559 }
2560
2561 if (Constructor->isInvalidDecl())
2562 return;
2563
2564 const CXXRecordDecl *RD = Constructor->getParent();
2565
Stephen Hines176edba2014-12-01 14:53:08 -08002566 if (RD->getDescribedClassTemplate())
2567 return;
2568
Richard Trieu858d2ba2013-10-25 00:56:00 +00002569 // Holds fields that are uninitialized.
2570 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2571
2572 // At the beginning, all fields are uninitialized.
Stephen Hines651f13c2014-04-23 16:59:28 -07002573 for (auto *I : RD->decls()) {
2574 if (auto *FD = dyn_cast<FieldDecl>(I)) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002575 UninitializedFields.insert(FD);
Stephen Hines651f13c2014-04-23 16:59:28 -07002576 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002577 UninitializedFields.insert(IFD->getAnonField());
2578 }
2579 }
2580
Stephen Hines176edba2014-12-01 14:53:08 -08002581 if (UninitializedFields.empty())
2582 return;
2583
2584 UninitializedFieldVisitor UninitializedChecker(SemaRef,
2585 UninitializedFields);
2586
Stephen Hines651f13c2014-04-23 16:59:28 -07002587 for (const auto *FieldInit : Constructor->inits()) {
Stephen Hines176edba2014-12-01 14:53:08 -08002588 if (UninitializedFields.empty())
2589 break;
2590
Stephen Hines651f13c2014-04-23 16:59:28 -07002591 Expr *InitExpr = FieldInit->getInit();
Stephen Hines176edba2014-12-01 14:53:08 -08002592 if (!InitExpr)
2593 continue;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002594
Stephen Hines176edba2014-12-01 14:53:08 -08002595 if (CXXDefaultInitExpr *Default =
2596 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
2597 InitExpr = Default->getExpr();
2598 if (!InitExpr)
2599 continue;
2600 // In class initializers will point to the constructor.
2601 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
2602 FieldInit->getAnyMember());
2603 } else {
2604 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
2605 FieldInit->getAnyMember());
2606 }
Richard Trieu858d2ba2013-10-25 00:56:00 +00002607 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002608 }
2609} // namespace
2610
Stephen Hines651f13c2014-04-23 16:59:28 -07002611/// \brief Enter a new C++ default initializer scope. After calling this, the
2612/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
2613/// parsing or instantiating the initializer failed.
2614void Sema::ActOnStartCXXInClassMemberInitializer() {
2615 // Create a synthetic function scope to represent the call to the constructor
2616 // that notionally surrounds a use of this initializer.
2617 PushFunctionScope();
2618}
2619
2620/// \brief This is invoked after parsing an in-class initializer for a
2621/// non-static C++ class member, and after instantiating an in-class initializer
2622/// in a class template. Such actions are deferred until the class is complete.
2623void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
2624 SourceLocation InitLoc,
2625 Expr *InitExpr) {
2626 // Pop the notional constructor scope we created earlier.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002627 PopFunctionScopeInfo(nullptr, D);
Stephen Hines651f13c2014-04-23 16:59:28 -07002628
Richard Smith7a614d82011-06-11 17:19:42 +00002629 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002630 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2631 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002632
2633 if (!InitExpr) {
2634 FD->setInvalidDecl();
2635 FD->removeInClassInitializer();
2636 return;
2637 }
2638
Peter Collingbournefef21892011-10-23 18:59:44 +00002639 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2640 FD->setInvalidDecl();
2641 FD->removeInClassInitializer();
2642 return;
2643 }
2644
Richard Smith7a614d82011-06-11 17:19:42 +00002645 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002646 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002647 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002648 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002649 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002650 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002651 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2652 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002653 if (Init.isInvalid()) {
2654 FD->setInvalidDecl();
2655 return;
2656 }
Richard Smith7a614d82011-06-11 17:19:42 +00002657 }
2658
Richard Smith41956372013-01-14 22:39:08 +00002659 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002660 // The initialization of each base and member constitutes a
2661 // full-expression.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002662 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002663 if (Init.isInvalid()) {
2664 FD->setInvalidDecl();
2665 return;
2666 }
2667
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002668 InitExpr = Init.get();
Richard Smith7a614d82011-06-11 17:19:42 +00002669
2670 FD->setInClassInitializer(InitExpr);
2671}
2672
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002673/// \brief Find the direct and/or virtual base specifiers that
2674/// correspond to the given base type, for use in base initialization
2675/// within a constructor.
2676static bool FindBaseInitializer(Sema &SemaRef,
2677 CXXRecordDecl *ClassDecl,
2678 QualType BaseType,
2679 const CXXBaseSpecifier *&DirectBaseSpec,
2680 const CXXBaseSpecifier *&VirtualBaseSpec) {
2681 // First, check for a direct base class.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002682 DirectBaseSpec = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002683 for (const auto &Base : ClassDecl->bases()) {
2684 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002685 // We found a direct base of this type. That's what we're
2686 // initializing.
Stephen Hines651f13c2014-04-23 16:59:28 -07002687 DirectBaseSpec = &Base;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002688 break;
2689 }
2690 }
2691
2692 // Check for a virtual base class.
2693 // FIXME: We might be able to short-circuit this if we know in advance that
2694 // there are no virtual bases.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002695 VirtualBaseSpec = nullptr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002696 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2697 // We haven't found a base yet; search the class hierarchy for a
2698 // virtual base class.
2699 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2700 /*DetectVirtual=*/false);
2701 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2702 BaseType, Paths)) {
2703 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2704 Path != Paths.end(); ++Path) {
2705 if (Path->back().Base->isVirtual()) {
2706 VirtualBaseSpec = Path->back().Base;
2707 break;
2708 }
2709 }
2710 }
2711 }
2712
2713 return DirectBaseSpec || VirtualBaseSpec;
2714}
2715
Sebastian Redl6df65482011-09-24 17:48:25 +00002716/// \brief Handle a C++ member initializer using braced-init-list syntax.
2717MemInitResult
2718Sema::ActOnMemInitializer(Decl *ConstructorD,
2719 Scope *S,
2720 CXXScopeSpec &SS,
2721 IdentifierInfo *MemberOrBase,
2722 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002723 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002724 SourceLocation IdLoc,
2725 Expr *InitList,
2726 SourceLocation EllipsisLoc) {
2727 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002728 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002729 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002730}
2731
2732/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002733MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002734Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002735 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002736 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002737 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002738 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002739 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002740 SourceLocation IdLoc,
2741 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002742 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002743 SourceLocation RParenLoc,
2744 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002745 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002746 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002747 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002748 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002749}
2750
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002751namespace {
2752
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002753// Callback to only accept typo corrections that can be a valid C++ member
2754// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002755class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002756public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002757 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2758 : ClassDecl(ClassDecl) {}
2759
Stephen Hines651f13c2014-04-23 16:59:28 -07002760 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002761 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2762 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2763 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002764 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002765 }
2766 return false;
2767 }
2768
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002769private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002770 CXXRecordDecl *ClassDecl;
2771};
2772
2773}
2774
Sebastian Redl6df65482011-09-24 17:48:25 +00002775/// \brief Handle a C++ member initializer.
2776MemInitResult
2777Sema::BuildMemInitializer(Decl *ConstructorD,
2778 Scope *S,
2779 CXXScopeSpec &SS,
2780 IdentifierInfo *MemberOrBase,
2781 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002782 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002783 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002784 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002785 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002786 if (!ConstructorD)
2787 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002788
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002789 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002790
2791 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002792 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002793 if (!Constructor) {
2794 // The user wrote a constructor initializer on a function that is
2795 // not a C++ constructor. Ignore the error for now, because we may
2796 // have more member initializers coming; we'll diagnose it just
2797 // once in ActOnMemInitializers.
2798 return true;
2799 }
2800
2801 CXXRecordDecl *ClassDecl = Constructor->getParent();
2802
2803 // C++ [class.base.init]p2:
2804 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002805 // constructor's class and, if not found in that scope, are looked
2806 // up in the scope containing the constructor's definition.
2807 // [Note: if the constructor's class contains a member with the
2808 // same name as a direct or virtual base class of the class, a
2809 // mem-initializer-id naming the member or base class and composed
2810 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002811 // mem-initializer-id for the hidden base class may be specified
2812 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002813 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002814 // Look for a member, first.
Stephen Hines176edba2014-12-01 14:53:08 -08002815 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002816 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002817 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002818 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2819 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002820 if (EllipsisLoc.isValid())
2821 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002822 << MemberOrBase
2823 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002824
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002825 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002826 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002827 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002828 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002829 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002830 QualType BaseType;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002831 TypeSourceInfo *TInfo = nullptr;
John McCall2b194412009-12-21 10:41:20 +00002832
2833 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002834 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002835 } else if (DS.getTypeSpecType() == TST_decltype) {
2836 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002837 } else {
2838 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2839 LookupParsedName(R, S, &SS);
2840
2841 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2842 if (!TyD) {
2843 if (R.isAmbiguous()) return true;
2844
John McCallfd225442010-04-09 19:01:14 +00002845 // We don't want access-control diagnostics here.
2846 R.suppressDiagnostics();
2847
Douglas Gregor7a886e12010-01-19 06:46:48 +00002848 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2849 bool NotUnknownSpecialization = false;
2850 DeclContext *DC = computeDeclContext(SS, false);
2851 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2852 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2853
2854 if (!NotUnknownSpecialization) {
2855 // When the scope specifier can refer to a member of an unknown
2856 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002857 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2858 SS.getWithLocInContext(Context),
2859 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002860 if (BaseType.isNull())
2861 return true;
2862
Douglas Gregor7a886e12010-01-19 06:46:48 +00002863 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002864 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002865 }
2866 }
2867
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002868 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002869 TypoCorrection Corr;
Douglas Gregor7a886e12010-01-19 06:46:48 +00002870 if (R.empty() && BaseType.isNull() &&
Stephen Hines176edba2014-12-01 14:53:08 -08002871 (Corr = CorrectTypo(
2872 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2873 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
2874 CTK_ErrorRecovery, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002875 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002876 // We have found a non-static data member with a similar
2877 // name to what was typed; complain and initialize that
2878 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002879 diagnoseTypo(Corr,
2880 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2881 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002882 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002883 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002884 const CXXBaseSpecifier *DirectBaseSpec;
2885 const CXXBaseSpecifier *VirtualBaseSpec;
2886 if (FindBaseInitializer(*this, ClassDecl,
2887 Context.getTypeDeclType(Type),
2888 DirectBaseSpec, VirtualBaseSpec)) {
2889 // We have found a direct or virtual base class with a
2890 // similar name to what was typed; complain and initialize
2891 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002892 diagnoseTypo(Corr,
2893 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2894 << MemberOrBase << false,
2895 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002896
Richard Smith2d670972013-08-17 00:46:16 +00002897 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2898 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002899 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002900 diag::note_base_class_specified_here)
2901 << BaseSpec->getType()
2902 << BaseSpec->getSourceRange();
2903
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002904 TyD = Type;
2905 }
2906 }
2907 }
2908
Douglas Gregor7a886e12010-01-19 06:46:48 +00002909 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002910 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002911 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002912 return true;
2913 }
John McCall2b194412009-12-21 10:41:20 +00002914 }
2915
Douglas Gregor7a886e12010-01-19 06:46:48 +00002916 if (BaseType.isNull()) {
2917 BaseType = Context.getTypeDeclType(TyD);
Stephen Hines176edba2014-12-01 14:53:08 -08002918 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
Stephen Hines651f13c2014-04-23 16:59:28 -07002919 if (SS.isSet())
Douglas Gregor7a886e12010-01-19 06:46:48 +00002920 // FIXME: preserve source range information
Stephen Hines651f13c2014-04-23 16:59:28 -07002921 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
2922 BaseType);
John McCall2b194412009-12-21 10:41:20 +00002923 }
2924 }
Mike Stump1eb44332009-09-09 15:08:12 +00002925
John McCalla93c9342009-12-07 02:54:59 +00002926 if (!TInfo)
2927 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002928
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002929 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002930}
2931
Chandler Carruth81c64772011-09-03 01:14:15 +00002932/// Checks a member initializer expression for cases where reference (or
2933/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002934static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2935 Expr *Init,
2936 SourceLocation IdLoc) {
2937 QualType MemberTy = Member->getType();
2938
2939 // We only handle pointers and references currently.
2940 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2941 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2942 return;
2943
2944 const bool IsPointer = MemberTy->isPointerType();
2945 if (IsPointer) {
2946 if (const UnaryOperator *Op
2947 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2948 // The only case we're worried about with pointers requires taking the
2949 // address.
2950 if (Op->getOpcode() != UO_AddrOf)
2951 return;
2952
2953 Init = Op->getSubExpr();
2954 } else {
2955 // We only handle address-of expression initializers for pointers.
2956 return;
2957 }
2958 }
2959
Richard Smitha4bb99c2013-06-12 21:51:50 +00002960 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002961 // We only warn when referring to a non-reference parameter declaration.
2962 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2963 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002964 return;
2965
2966 S.Diag(Init->getExprLoc(),
2967 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2968 : diag::warn_bind_ref_member_to_parameter)
2969 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002970 } else {
2971 // Other initializers are fine.
2972 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002973 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002974
2975 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2976 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002977}
2978
John McCallf312b1e2010-08-26 23:41:50 +00002979MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002980Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002981 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002982 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2983 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2984 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002985 "Member must be a FieldDecl or IndirectFieldDecl");
2986
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002987 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002988 return true;
2989
Douglas Gregor464b2f02010-11-05 22:21:31 +00002990 if (Member->isInvalidDecl())
2991 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002992
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002993 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002994 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002995 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002996 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002997 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002998 } else {
2999 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003000 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003001 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00003002
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003003 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00003004
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003005 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003006 // Can't check initialization for a member of dependent type or when
3007 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00003008 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00003009 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003010 bool InitList = false;
3011 if (isa<InitListExpr>(Init)) {
3012 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003013 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003014 }
3015
Chandler Carruth894aed92010-12-06 09:23:57 +00003016 // Initialize the member.
3017 InitializedEntity MemberEntity =
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003018 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3019 : InitializedEntity::InitializeMember(IndirectMember,
3020 nullptr);
Chandler Carruth894aed92010-12-06 09:23:57 +00003021 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003022 InitList ? InitializationKind::CreateDirectList(IdLoc)
3023 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3024 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00003025
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003026 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003027 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3028 nullptr);
Chandler Carruth894aed92010-12-06 09:23:57 +00003029 if (MemberInit.isInvalid())
3030 return true;
3031
Richard Smith8a07cd32013-06-12 20:42:33 +00003032 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3033
Richard Smith41956372013-01-14 22:39:08 +00003034 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00003035 // The initialization of each base and member constitutes a
3036 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00003037 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00003038 if (MemberInit.isInvalid())
3039 return true;
3040
Richard Smithc83c2302012-12-19 01:39:02 +00003041 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003042 }
3043
Chandler Carruth894aed92010-12-06 09:23:57 +00003044 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003045 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3046 InitRange.getBegin(), Init,
3047 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00003048 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003049 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3050 InitRange.getBegin(), Init,
3051 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00003052 }
Eli Friedman59c04372009-07-29 19:44:27 +00003053}
3054
John McCallf312b1e2010-08-26 23:41:50 +00003055MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003056Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00003057 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00003058 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00003059 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00003060 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00003061 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00003062 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00003063
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003064 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003065 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003066 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3067 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003068 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003069 }
3070
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003071 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00003072 // Initialize the object.
3073 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3074 QualType(ClassDecl->getTypeForDecl(), 0));
3075 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003076 InitList ? InitializationKind::CreateDirectList(NameLoc)
3077 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
3078 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003079 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003080 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003081 Args, nullptr);
Sean Hunt41717662011-02-26 19:13:13 +00003082 if (DelegationInit.isInvalid())
3083 return true;
3084
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00003085 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
3086 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00003087
Richard Smith41956372013-01-14 22:39:08 +00003088 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00003089 // The initialization of each base and member constitutes a
3090 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00003091 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
3092 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00003093 if (DelegationInit.isInvalid())
3094 return true;
3095
Eli Friedmand21016f2012-05-19 23:35:23 +00003096 // If we are in a dependent context, template instantiation will
3097 // perform this type-checking again. Just save the arguments that we
3098 // received in a ParenListExpr.
3099 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3100 // of the information that we have about the base
3101 // initializer. However, deconstructing the ASTs is a dicey process,
3102 // and this approach is far more likely to get the corner cases right.
3103 if (CurContext->isDependentContext())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003104 DelegationInit = Init;
Eli Friedmand21016f2012-05-19 23:35:23 +00003105
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003106 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003107 DelegationInit.getAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003108 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00003109}
3110
3111MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00003112Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003113 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003114 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003115 SourceLocation BaseLoc
3116 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00003117
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003118 if (!BaseType->isDependentType() && !BaseType->isRecordType())
3119 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
3120 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
3121
3122 // C++ [class.base.init]p2:
3123 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00003124 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003125 // of that class, the mem-initializer is ill-formed. A
3126 // mem-initializer-list can initialize a base class using any
3127 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003128 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003129
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003130 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003131 if (EllipsisLoc.isValid()) {
3132 // This is a pack expansion.
3133 if (!BaseType->containsUnexpandedParameterPack()) {
3134 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003135 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00003136
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003137 EllipsisLoc = SourceLocation();
3138 }
3139 } else {
3140 // Check for any unexpanded parameter packs.
3141 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
3142 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00003143
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003144 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00003145 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003146 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003147
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003148 // Check for direct and virtual base classes.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003149 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
3150 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003151 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00003152 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
3153 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003154 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00003155
Douglas Gregor3956b1a2010-06-16 16:03:14 +00003156 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
3157 VirtualBaseSpec);
3158
3159 // C++ [base.class.init]p2:
3160 // Unless the mem-initializer-id names a nonstatic data member of the
3161 // constructor's class or a direct or virtual base of that class, the
3162 // mem-initializer is ill-formed.
3163 if (!DirectBaseSpec && !VirtualBaseSpec) {
3164 // If the class has any dependent bases, then it's possible that
3165 // one of those types will resolve to the same type as
3166 // BaseType. Therefore, just treat this as a dependent base
3167 // class initialization. FIXME: Should we try to check the
3168 // initialization anyway? It seems odd.
3169 if (ClassDecl->hasAnyDependentBases())
3170 Dependent = true;
3171 else
3172 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
3173 << BaseType << Context.getTypeDeclType(ClassDecl)
3174 << BaseTInfo->getTypeLoc().getLocalSourceRange();
3175 }
3176 }
3177
3178 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00003179 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00003180
Sebastian Redl6df65482011-09-24 17:48:25 +00003181 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
3182 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003183 InitRange.getBegin(), Init,
3184 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00003185 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003186
3187 // C++ [base.class.init]p2:
3188 // If a mem-initializer-id is ambiguous because it designates both
3189 // a direct non-virtual base class and an inherited virtual base
3190 // class, the mem-initializer is ill-formed.
3191 if (DirectBaseSpec && VirtualBaseSpec)
3192 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00003193 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003194
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003195 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003196 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003197 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003198
3199 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003200 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003201 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003202 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003203 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003204 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003205 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00003206
3207 InitializedEntity BaseEntity =
3208 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
3209 InitializationKind Kind =
3210 InitList ? InitializationKind::CreateDirectList(BaseLoc)
3211 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
3212 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003213 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003214 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003215 if (BaseInit.isInvalid())
3216 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00003217
Richard Smith41956372013-01-14 22:39:08 +00003218 // C++11 [class.base.init]p7:
3219 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003220 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00003221 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003222 if (BaseInit.isInvalid())
3223 return true;
3224
3225 // If we are in a dependent context, template instantiation will
3226 // perform this type-checking again. Just save the arguments that we
3227 // received in a ParenListExpr.
3228 // FIXME: This isn't quite ideal, since our ASTs don't capture all
3229 // of the information that we have about the base
3230 // initializer. However, deconstructing the ASTs is a dicey process,
3231 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00003232 if (CurContext->isDependentContext())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003233 BaseInit = Init;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003234
Sean Huntcbb67482011-01-08 20:30:50 +00003235 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00003236 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003237 InitRange.getBegin(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003238 BaseInit.getAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003239 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00003240}
3241
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003242// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00003243static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
3244 if (T.isNull()) T = E->getType();
3245 QualType TargetType = SemaRef.BuildReferenceType(
3246 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003247 SourceLocation ExprLoc = E->getLocStart();
3248 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
3249 TargetType, ExprLoc);
3250
3251 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
3252 SourceRange(ExprLoc, ExprLoc),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003253 E->getSourceRange()).get();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003254}
3255
Anders Carlssone5ef7402010-04-23 03:10:23 +00003256/// ImplicitInitializerKind - How an implicit base or member initializer should
3257/// initialize its base or member.
3258enum ImplicitInitializerKind {
3259 IIK_Default,
3260 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00003261 IIK_Move,
3262 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00003263};
3264
Anders Carlssondefefd22010-04-23 02:00:02 +00003265static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003266BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003267 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00003268 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00003269 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00003270 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00003271 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00003272 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
3273 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00003274
John McCall60d7b3a2010-08-24 06:29:42 +00003275 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00003276
3277 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00003278 case IIK_Inherit: {
3279 const CXXRecordDecl *Inherited =
3280 Constructor->getInheritedConstructor()->getParent();
3281 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
3282 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
3283 // C++11 [class.inhctor]p8:
3284 // Each expression in the expression-list is of the form
3285 // static_cast<T&&>(p), where p is the name of the corresponding
3286 // constructor parameter and T is the declared type of p.
3287 SmallVector<Expr*, 16> Args;
3288 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3289 ParmVarDecl *PD = Constructor->getParamDecl(I);
3290 ExprResult ArgExpr =
3291 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3292 VK_LValue, SourceLocation());
3293 if (ArgExpr.isInvalid())
3294 return true;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003295 Args.push_back(CastForMoving(SemaRef, ArgExpr.get(), PD->getType()));
Richard Smith07b0fdc2013-03-18 21:12:30 +00003296 }
3297
3298 InitializationKind InitKind = InitializationKind::CreateDirect(
3299 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003300 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00003301 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3302 break;
3303 }
3304 }
3305 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00003306 case IIK_Default: {
3307 InitializationKind InitKind
3308 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003309 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3310 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003311 break;
3312 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003313
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003314 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00003315 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003316 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00003317 ParmVarDecl *Param = Constructor->getParamDecl(0);
3318 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00003319
Anders Carlssone5ef7402010-04-23 03:10:23 +00003320 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003321 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003322 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00003323 Constructor->getLocation(), ParamType,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003324 VK_LValue, nullptr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003325
Eli Friedman5f2987c2012-02-02 03:46:19 +00003326 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3327
Anders Carlssonc7957502010-04-24 22:02:54 +00003328 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00003329 QualType ArgTy =
3330 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3331 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00003332
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003333 if (Moving) {
3334 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3335 }
3336
John McCallf871d0c2010-08-07 06:22:56 +00003337 CXXCastPath BasePath;
3338 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00003339 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3340 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003341 Moving ? VK_XValue : VK_LValue,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003342 &BasePath).get();
Anders Carlssonc7957502010-04-24 22:02:54 +00003343
Anders Carlssone5ef7402010-04-23 03:10:23 +00003344 InitializationKind InitKind
3345 = InitializationKind::CreateDirect(Constructor->getLocation(),
3346 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003347 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3348 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003349 break;
3350 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00003351 }
John McCall9ae2f072010-08-23 23:25:46 +00003352
Douglas Gregor53c374f2010-12-07 00:41:46 +00003353 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00003354 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00003355 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00003356
Anders Carlssondefefd22010-04-23 02:00:02 +00003357 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00003358 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00003359 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3360 SourceLocation()),
3361 BaseSpec->isVirtual(),
3362 SourceLocation(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003363 BaseInit.getAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003364 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00003365 SourceLocation());
3366
Anders Carlssondefefd22010-04-23 02:00:02 +00003367 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00003368}
3369
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003370static bool RefersToRValueRef(Expr *MemRef) {
3371 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3372 return Referenced->getType()->isRValueReferenceType();
3373}
3374
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003375static bool
3376BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003377 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003378 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00003379 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003380 if (Field->isInvalidDecl())
3381 return true;
3382
Chandler Carruthf186b542010-06-29 23:50:44 +00003383 SourceLocation Loc = Constructor->getLocation();
3384
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003385 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3386 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003387 ParmVarDecl *Param = Constructor->getParamDecl(0);
3388 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00003389
3390 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003391 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3392 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00003393
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003394 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003395 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003396 SourceLocation(), Param, false,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003397 Loc, ParamType, VK_LValue, nullptr);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003398
Eli Friedman5f2987c2012-02-02 03:46:19 +00003399 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3400
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003401 if (Moving) {
3402 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3403 }
3404
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003405 // Build a reference to this field within the parameter.
3406 CXXScopeSpec SS;
3407 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3408 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003409 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3410 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003411 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00003412 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00003413 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003414 ParamType, Loc,
3415 /*IsArrow=*/false,
3416 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003417 /*TemplateKWLoc=*/SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003418 /*FirstQualifierInScope=*/nullptr,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003419 MemberLookup,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003420 /*TemplateArgs=*/nullptr);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003421 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003422 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003423
3424 // C++11 [class.copy]p15:
3425 // - if a member m has rvalue reference type T&&, it is direct-initialized
3426 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003427 if (RefersToRValueRef(CtorArg.get())) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003428 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003429 }
3430
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003431 // When the field we are copying is an array, create index variables for
3432 // each dimension of the array. We use these index variables to subscript
3433 // the source array, and other clients (e.g., CodeGen) will perform the
3434 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003435 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003436 QualType BaseType = Field->getType();
3437 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003438 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003439 while (const ConstantArrayType *Array
3440 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003441 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003442 // Create the iteration variable for this array index.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003443 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003444 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003445 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003446 llvm::raw_svector_ostream OS(Str);
3447 OS << "__i" << IndexVariables.size();
3448 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3449 }
3450 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003451 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003452 IterationVarName, SizeType,
3453 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003454 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003455 IndexVariables.push_back(IterationVar);
3456
3457 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003458 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003459 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003460 assert(!IterationVarRef.isInvalid() &&
3461 "Reference to invented variable cannot fail!");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003462 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.get());
Eli Friedman8c382062012-01-23 02:35:22 +00003463 assert(!IterationVarRef.isInvalid() &&
3464 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003465
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003466 // Subscript the array with this iteration variable.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003467 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.get(), Loc,
3468 IterationVarRef.get(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003469 Loc);
3470 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003471 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003472
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003473 BaseType = Array->getElementType();
3474 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003475
3476 // The array subscript expression is an lvalue, which is wrong for moving.
3477 if (Moving && InitializingArray)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003478 CtorArg = CastForMoving(SemaRef, CtorArg.get());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003479
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003480 // Construct the entity that we will be initializing. For an array, this
3481 // will be first element in the array, which may require several levels
3482 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003483 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003484 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003485 if (Indirect)
3486 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3487 else
3488 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003489 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3490 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3491 0,
3492 Entities.back()));
3493
3494 // Direct-initialize to use the copy constructor.
3495 InitializationKind InitKind =
3496 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3497
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003498 Expr *CtorArgE = CtorArg.getAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003499 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003500
John McCall60d7b3a2010-08-24 06:29:42 +00003501 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003502 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003503 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003504 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003505 if (MemberInit.isInvalid())
3506 return true;
3507
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003508 if (Indirect) {
3509 assert(IndexVariables.size() == 0 &&
3510 "Indirect field improperly initialized");
3511 CXXMemberInit
3512 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3513 Loc, Loc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003514 MemberInit.getAs<Expr>(),
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003515 Loc);
3516 } else
3517 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003518 Loc, MemberInit.getAs<Expr>(),
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003519 Loc,
3520 IndexVariables.data(),
3521 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003522 return false;
3523 }
3524
Richard Smith07b0fdc2013-03-18 21:12:30 +00003525 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3526 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003527
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003528 QualType FieldBaseElementType =
3529 SemaRef.Context.getBaseElementType(Field->getType());
3530
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003531 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003532 InitializedEntity InitEntity
3533 = Indirect? InitializedEntity::InitializeMember(Indirect)
3534 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003535 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003536 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003537
3538 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3539 ExprResult MemberInit =
3540 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003541
Douglas Gregor53c374f2010-12-07 00:41:46 +00003542 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003543 if (MemberInit.isInvalid())
3544 return true;
3545
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003546 if (Indirect)
3547 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3548 Indirect, Loc,
3549 Loc,
3550 MemberInit.get(),
3551 Loc);
3552 else
3553 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3554 Field, Loc, Loc,
3555 MemberInit.get(),
3556 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003557 return false;
3558 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003559
Sean Hunt1f2f3842011-05-17 00:19:05 +00003560 if (!Field->getParent()->isUnion()) {
3561 if (FieldBaseElementType->isReferenceType()) {
3562 SemaRef.Diag(Constructor->getLocation(),
3563 diag::err_uninitialized_member_in_ctor)
3564 << (int)Constructor->isImplicit()
3565 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3566 << 0 << Field->getDeclName();
3567 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3568 return true;
3569 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003570
Sean Hunt1f2f3842011-05-17 00:19:05 +00003571 if (FieldBaseElementType.isConstQualified()) {
3572 SemaRef.Diag(Constructor->getLocation(),
3573 diag::err_uninitialized_member_in_ctor)
3574 << (int)Constructor->isImplicit()
3575 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3576 << 1 << Field->getDeclName();
3577 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3578 return true;
3579 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003580 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003581
David Blaikie4e4d0842012-03-11 07:00:24 +00003582 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003583 FieldBaseElementType->isObjCRetainableType() &&
3584 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3585 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003586 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003587 // Default-initialize Objective-C pointers to NULL.
3588 CXXMemberInit
3589 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3590 Loc, Loc,
3591 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3592 Loc);
3593 return false;
3594 }
3595
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003596 // Nothing to initialize.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003597 CXXMemberInit = nullptr;
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003598 return false;
3599}
John McCallf1860e52010-05-20 23:23:51 +00003600
3601namespace {
3602struct BaseAndFieldInfo {
3603 Sema &S;
3604 CXXConstructorDecl *Ctor;
3605 bool AnyErrorsInInits;
3606 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003607 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003608 SmallVector<CXXCtorInitializer*, 8> AllToInit;
Stephen Hines651f13c2014-04-23 16:59:28 -07003609 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
John McCallf1860e52010-05-20 23:23:51 +00003610
3611 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3612 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003613 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3614 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003615 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003616 else if (Generated && Ctor->isMoveConstructor())
3617 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003618 else if (Ctor->getInheritedConstructor())
3619 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003620 else
3621 IIK = IIK_Default;
3622 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003623
3624 bool isImplicitCopyOrMove() const {
3625 switch (IIK) {
3626 case IIK_Copy:
3627 case IIK_Move:
3628 return true;
3629
3630 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003631 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003632 return false;
3633 }
David Blaikie30263482012-01-20 21:50:17 +00003634
3635 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003636 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003637
3638 bool addFieldInitializer(CXXCtorInitializer *Init) {
3639 AllToInit.push_back(Init);
3640
3641 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003642 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003643 S.UnusedPrivateFields.remove(Init->getAnyMember());
3644
3645 return false;
3646 }
John McCallf1860e52010-05-20 23:23:51 +00003647
Stephen Hines651f13c2014-04-23 16:59:28 -07003648 bool isInactiveUnionMember(FieldDecl *Field) {
3649 RecordDecl *Record = Field->getParent();
3650 if (!Record->isUnion())
3651 return false;
3652
3653 if (FieldDecl *Active =
3654 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
3655 return Active != Field->getCanonicalDecl();
3656
3657 // In an implicit copy or move constructor, ignore any in-class initializer.
3658 if (isImplicitCopyOrMove())
3659 return true;
3660
3661 // If there's no explicit initialization, the field is active only if it
3662 // has an in-class initializer...
3663 if (Field->hasInClassInitializer())
3664 return false;
3665 // ... or it's an anonymous struct or union whose class has an in-class
3666 // initializer.
3667 if (!Field->isAnonymousStructOrUnion())
3668 return true;
3669 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
3670 return !FieldRD->hasInClassInitializer();
3671 }
3672
3673 /// \brief Determine whether the given field is, or is within, a union member
3674 /// that is inactive (because there was an initializer given for a different
3675 /// member of the union, or because the union was not initialized at all).
3676 bool isWithinInactiveUnionMember(FieldDecl *Field,
3677 IndirectFieldDecl *Indirect) {
3678 if (!Indirect)
3679 return isInactiveUnionMember(Field);
3680
3681 for (auto *C : Indirect->chain()) {
3682 FieldDecl *Field = dyn_cast<FieldDecl>(C);
3683 if (Field && isInactiveUnionMember(Field))
Richard Smitha4950662011-09-19 13:34:43 +00003684 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07003685 }
3686 return false;
3687 }
3688};
Richard Smitha4950662011-09-19 13:34:43 +00003689}
3690
Douglas Gregorddb21472011-11-02 23:04:16 +00003691/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3692/// array type.
3693static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3694 if (T->isIncompleteArrayType())
3695 return true;
3696
3697 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3698 if (!ArrayT->getSize())
3699 return true;
3700
3701 T = ArrayT->getElementType();
3702 }
3703
3704 return false;
3705}
3706
Richard Smith7a614d82011-06-11 17:19:42 +00003707static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003708 FieldDecl *Field,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003709 IndirectFieldDecl *Indirect = nullptr) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003710 if (Field->isInvalidDecl())
3711 return false;
John McCallf1860e52010-05-20 23:23:51 +00003712
Chandler Carruthe861c602010-06-30 02:59:29 +00003713 // Overwhelmingly common case: we have a direct initializer for this field.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003714 if (CXXCtorInitializer *Init =
3715 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
Richard Smith0b8220a2012-08-07 21:30:42 +00003716 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003717
Stephen Hines651f13c2014-04-23 16:59:28 -07003718 // C++11 [class.base.init]p8:
3719 // if the entity is a non-static data member that has a
3720 // brace-or-equal-initializer and either
3721 // -- the constructor's class is a union and no other variant member of that
3722 // union is designated by a mem-initializer-id or
3723 // -- the constructor's class is not a union, and, if the entity is a member
3724 // of an anonymous union, no other member of that union is designated by
3725 // a mem-initializer-id,
3726 // the entity is initialized as specified in [dcl.init].
3727 //
3728 // We also apply the same rules to handle anonymous structs within anonymous
3729 // unions.
3730 if (Info.isWithinInactiveUnionMember(Field, Indirect))
3731 return false;
3732
Douglas Gregorf4853882011-11-28 20:03:15 +00003733 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Stephen Hines176edba2014-12-01 14:53:08 -08003734 ExprResult DIE =
3735 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
3736 if (DIE.isInvalid())
3737 return true;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003738 CXXCtorInitializer *Init;
3739 if (Indirect)
Stephen Hines176edba2014-12-01 14:53:08 -08003740 Init = new (SemaRef.Context)
3741 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
3742 SourceLocation(), DIE.get(), SourceLocation());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003743 else
Stephen Hines176edba2014-12-01 14:53:08 -08003744 Init = new (SemaRef.Context)
3745 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
3746 SourceLocation(), DIE.get(), SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003747 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003748 }
3749
Douglas Gregorddb21472011-11-02 23:04:16 +00003750 // Don't initialize incomplete or zero-length arrays.
3751 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3752 return false;
3753
John McCallf1860e52010-05-20 23:23:51 +00003754 // Don't try to build an implicit initializer if there were semantic
3755 // errors in any of the initializers (and therefore we might be
3756 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003757 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003758 return false;
3759
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003760 CXXCtorInitializer *Init = nullptr;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003761 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3762 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003763 return true;
John McCallf1860e52010-05-20 23:23:51 +00003764
Richard Smith0b8220a2012-08-07 21:30:42 +00003765 if (!Init)
3766 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003767
Richard Smith0b8220a2012-08-07 21:30:42 +00003768 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003769}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003770
3771bool
3772Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3773 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003774 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003775 Constructor->setNumCtorInitializers(1);
3776 CXXCtorInitializer **initializer =
3777 new (Context) CXXCtorInitializer*[1];
3778 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3779 Constructor->setCtorInitializers(initializer);
3780
Sean Huntb76af9c2011-05-03 23:05:34 +00003781 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003782 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003783 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3784 }
3785
Sean Huntc1598702011-05-05 00:05:47 +00003786 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003787
Stephen Hines176edba2014-12-01 14:53:08 -08003788 DiagnoseUninitializedFields(*this, Constructor);
3789
Sean Hunt059ce0d2011-05-01 07:04:31 +00003790 return false;
3791}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003792
David Blaikie93c86172013-01-17 05:26:25 +00003793bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3794 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003795 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003796 // Just store the initializers as written, they will be checked during
3797 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003798 if (!Initializers.empty()) {
3799 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003800 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003801 new (Context) CXXCtorInitializer*[Initializers.size()];
3802 memcpy(baseOrMemberInitializers, Initializers.data(),
3803 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003804 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003805 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003806
3807 // Let template instantiation know whether we had errors.
3808 if (AnyErrors)
3809 Constructor->setInvalidDecl();
3810
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003811 return false;
3812 }
3813
John McCallf1860e52010-05-20 23:23:51 +00003814 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003815
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003816 // We need to build the initializer AST according to order of construction
3817 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003818 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003819 if (!ClassDecl)
3820 return true;
3821
Eli Friedman80c30da2009-11-09 19:20:36 +00003822 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003823
David Blaikie93c86172013-01-17 05:26:25 +00003824 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003825 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003826
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003827 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003828 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Stephen Hines651f13c2014-04-23 16:59:28 -07003829 else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003830 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
Stephen Hines651f13c2014-04-23 16:59:28 -07003831
3832 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
3833 for (auto *C : F->chain()) {
3834 FieldDecl *FD = dyn_cast<FieldDecl>(C);
3835 if (FD && FD->getParent()->isUnion())
3836 Info.ActiveUnionMember.insert(std::make_pair(
3837 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3838 }
3839 } else if (FieldDecl *FD = Member->getMember()) {
3840 if (FD->getParent()->isUnion())
3841 Info.ActiveUnionMember.insert(std::make_pair(
3842 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
3843 }
3844 }
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003845 }
3846
Anders Carlsson711f34a2010-04-21 19:52:01 +00003847 // Keep track of the direct virtual bases.
3848 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
Stephen Hines651f13c2014-04-23 16:59:28 -07003849 for (auto &I : ClassDecl->bases()) {
3850 if (I.isVirtual())
3851 DirectVBases.insert(&I);
Anders Carlsson711f34a2010-04-21 19:52:01 +00003852 }
3853
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003854 // Push virtual bases before others.
Stephen Hines651f13c2014-04-23 16:59:28 -07003855 for (auto &VBase : ClassDecl->vbases()) {
Sean Huntcbb67482011-01-08 20:30:50 +00003856 if (CXXCtorInitializer *Value
Stephen Hines651f13c2014-04-23 16:59:28 -07003857 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003858 // [class.base.init]p7, per DR257:
3859 // A mem-initializer where the mem-initializer-id names a virtual base
3860 // class is ignored during execution of a constructor of any class that
3861 // is not the most derived class.
3862 if (ClassDecl->isAbstract()) {
3863 // FIXME: Provide a fixit to remove the base specifier. This requires
3864 // tracking the location of the associated comma for a base specifier.
3865 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
Stephen Hines651f13c2014-04-23 16:59:28 -07003866 << VBase.getType() << ClassDecl;
Richard Smithcbc820a2013-07-22 02:56:56 +00003867 DiagnoseAbstractType(ClassDecl);
3868 }
3869
John McCallf1860e52010-05-20 23:23:51 +00003870 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003871 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3872 // [class.base.init]p8, per DR257:
3873 // If a given [...] base class is not named by a mem-initializer-id
3874 // [...] and the entity is not a virtual base class of an abstract
3875 // class, then [...] the entity is default-initialized.
Stephen Hines651f13c2014-04-23 16:59:28 -07003876 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003877 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003878 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Stephen Hines651f13c2014-04-23 16:59:28 -07003879 &VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003880 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003881 HadError = true;
3882 continue;
3883 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003884
John McCallf1860e52010-05-20 23:23:51 +00003885 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003886 }
3887 }
Mike Stump1eb44332009-09-09 15:08:12 +00003888
John McCallf1860e52010-05-20 23:23:51 +00003889 // Non-virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07003890 for (auto &Base : ClassDecl->bases()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003891 // Virtuals are in the virtual base list and already constructed.
Stephen Hines651f13c2014-04-23 16:59:28 -07003892 if (Base.isVirtual())
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003893 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003894
Sean Huntcbb67482011-01-08 20:30:50 +00003895 if (CXXCtorInitializer *Value
Stephen Hines651f13c2014-04-23 16:59:28 -07003896 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
John McCallf1860e52010-05-20 23:23:51 +00003897 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003898 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003899 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003900 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Stephen Hines651f13c2014-04-23 16:59:28 -07003901 &Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003902 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003903 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003904 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003905 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003906
John McCallf1860e52010-05-20 23:23:51 +00003907 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003908 }
3909 }
Mike Stump1eb44332009-09-09 15:08:12 +00003910
John McCallf1860e52010-05-20 23:23:51 +00003911 // Fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07003912 for (auto *Mem : ClassDecl->decls()) {
3913 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003914 // C++ [class.bit]p2:
3915 // A declaration for a bit-field that omits the identifier declares an
3916 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3917 // initialized.
3918 if (F->isUnnamedBitfield())
3919 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003920
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003921 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003922 // handle anonymous struct/union fields based on their individual
3923 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003924 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003925 continue;
3926
3927 if (CollectFieldInitializer(*this, Info, F))
3928 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003929 continue;
3930 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003931
3932 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003933 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003934 continue;
3935
Stephen Hines651f13c2014-04-23 16:59:28 -07003936 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003937 if (F->getType()->isIncompleteArrayType()) {
3938 assert(ClassDecl->hasFlexibleArrayMember() &&
3939 "Incomplete array type is not valid");
3940 continue;
3941 }
3942
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003943 // Initialize each field of an anonymous struct individually.
3944 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3945 HadError = true;
3946
3947 continue;
3948 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003949 }
Mike Stump1eb44332009-09-09 15:08:12 +00003950
David Blaikie93c86172013-01-17 05:26:25 +00003951 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003952 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003953 Constructor->setNumCtorInitializers(NumInitializers);
3954 CXXCtorInitializer **baseOrMemberInitializers =
3955 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003956 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003957 NumInitializers * sizeof(CXXCtorInitializer*));
3958 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003959
John McCallef027fe2010-03-16 21:39:52 +00003960 // Constructors implicitly reference the base and member
3961 // destructors.
3962 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3963 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003964 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003965
3966 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003967}
3968
David Blaikieee000bb2013-01-17 08:49:22 +00003969static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003970 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003971 const RecordDecl *RD = RT->getDecl();
3972 if (RD->isAnonymousStructOrUnion()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003973 for (auto *Field : RD->fields())
3974 PopulateKeysForFields(Field, IdealInits);
David Blaikieee000bb2013-01-17 08:49:22 +00003975 return;
3976 }
Eli Friedman6347f422009-07-21 19:28:10 +00003977 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003978 IdealInits.push_back(Field->getCanonicalDecl());
Eli Friedman6347f422009-07-21 19:28:10 +00003979}
3980
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003981static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3982 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003983}
3984
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003985static const void *GetKeyForMember(ASTContext &Context,
3986 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003987 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003988 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003989
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003990 return Member->getAnyMember()->getCanonicalDecl();
Eli Friedman6347f422009-07-21 19:28:10 +00003991}
3992
David Blaikie93c86172013-01-17 05:26:25 +00003993static void DiagnoseBaseOrMemInitializerOrder(
3994 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3995 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003996 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003997 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003998
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003999 // Don't check initializers order unless the warning is enabled at the
4000 // location of at least one initializer.
4001 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00004002 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00004003 CXXCtorInitializer *Init = Inits[InitIndex];
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004004 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4005 Init->getSourceLocation())) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004006 ShouldCheckOrder = true;
4007 break;
4008 }
4009 }
4010 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00004011 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004012
John McCalld6ca8da2010-04-10 07:37:23 +00004013 // Build the list of bases and members in the order that they'll
4014 // actually be initialized. The explicit initializers should be in
4015 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004016 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Anders Carlsson071d6102010-04-02 03:38:04 +00004018 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4019
John McCalld6ca8da2010-04-10 07:37:23 +00004020 // 1. Virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004021 for (const auto &VBase : ClassDecl->vbases())
4022 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00004023
John McCalld6ca8da2010-04-10 07:37:23 +00004024 // 2. Non-virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004025 for (const auto &Base : ClassDecl->bases()) {
4026 if (Base.isVirtual())
Anders Carlsson5c36fb22009-08-27 05:45:01 +00004027 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07004028 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00004029 }
Mike Stump1eb44332009-09-09 15:08:12 +00004030
John McCalld6ca8da2010-04-10 07:37:23 +00004031 // 3. Direct fields.
Stephen Hines651f13c2014-04-23 16:59:28 -07004032 for (auto *Field : ClassDecl->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +00004033 if (Field->isUnnamedBitfield())
4034 continue;
4035
Stephen Hines651f13c2014-04-23 16:59:28 -07004036 PopulateKeysForFields(Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00004037 }
4038
John McCalld6ca8da2010-04-10 07:37:23 +00004039 unsigned NumIdealInits = IdealInitKeys.size();
4040 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00004041
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004042 CXXCtorInitializer *PrevInit = nullptr;
David Blaikie93c86172013-01-17 05:26:25 +00004043 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00004044 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004045 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00004046
4047 // Scan forward to try to find this initializer in the idealized
4048 // initializers list.
4049 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4050 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00004051 break;
John McCalld6ca8da2010-04-10 07:37:23 +00004052
4053 // If we didn't find this initializer, it must be because we
4054 // scanned past it on a previous iteration. That can only
4055 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00004056 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00004057 Sema::SemaDiagnosticBuilder D =
4058 SemaRef.Diag(PrevInit->getSourceLocation(),
4059 diag::warn_initializer_out_of_order);
4060
Francois Pichet00eb3f92010-12-04 09:14:42 +00004061 if (PrevInit->isAnyMemberInitializer())
4062 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00004063 else
Douglas Gregor76852c22011-11-01 01:16:03 +00004064 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00004065
Francois Pichet00eb3f92010-12-04 09:14:42 +00004066 if (Init->isAnyMemberInitializer())
4067 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00004068 else
Douglas Gregor76852c22011-11-01 01:16:03 +00004069 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00004070
4071 // Move back to the initializer's location in the ideal list.
4072 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4073 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00004074 break;
John McCalld6ca8da2010-04-10 07:37:23 +00004075
4076 assert(IdealIndex != NumIdealInits &&
4077 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00004078 }
John McCalld6ca8da2010-04-10 07:37:23 +00004079
4080 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00004081 }
Anders Carlssona7b35212009-03-25 02:58:17 +00004082}
4083
John McCall3c3ccdb2010-04-10 09:28:51 +00004084namespace {
4085bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00004086 CXXCtorInitializer *Init,
4087 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00004088 if (!PrevInit) {
4089 PrevInit = Init;
4090 return false;
4091 }
4092
Douglas Gregordc392c12013-03-25 23:28:23 +00004093 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00004094 S.Diag(Init->getSourceLocation(),
4095 diag::err_multiple_mem_initialization)
4096 << Field->getDeclName()
4097 << Init->getSourceRange();
4098 else {
John McCallf4c73712011-01-19 06:33:43 +00004099 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00004100 assert(BaseClass && "neither field nor base");
4101 S.Diag(Init->getSourceLocation(),
4102 diag::err_multiple_base_initialization)
4103 << QualType(BaseClass, 0)
4104 << Init->getSourceRange();
4105 }
4106 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4107 << 0 << PrevInit->getSourceRange();
4108
4109 return true;
4110}
4111
Sean Huntcbb67482011-01-08 20:30:50 +00004112typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00004113typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4114
4115bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00004116 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00004117 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00004118 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00004119 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00004120 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00004121
4122 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00004123 if (Parent->isUnion()) {
4124 UnionEntry &En = Unions[Parent];
4125 if (En.first && En.first != Child) {
4126 S.Diag(Init->getSourceLocation(),
4127 diag::err_multiple_mem_union_initialization)
4128 << Field->getDeclName()
4129 << Init->getSourceRange();
4130 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4131 << 0 << En.second->getSourceRange();
4132 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00004133 }
4134 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00004135 En.first = Child;
4136 En.second = Init;
4137 }
David Blaikie6fe29652011-11-17 06:01:57 +00004138 if (!Parent->isAnonymousStructOrUnion())
4139 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00004140 }
4141
4142 Child = Parent;
4143 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00004144 }
John McCall3c3ccdb2010-04-10 09:28:51 +00004145
4146 return false;
4147}
4148}
4149
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004150/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00004151void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004152 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00004153 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004154 bool AnyErrors) {
4155 if (!ConstructorDecl)
4156 return;
4157
4158 AdjustDeclIfTemplate(ConstructorDecl);
4159
4160 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00004161 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004162
4163 if (!Constructor) {
4164 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4165 return;
4166 }
4167
John McCall3c3ccdb2010-04-10 09:28:51 +00004168 // Mapping for the duplicate initializers check.
4169 // For member initializers, this is keyed with a FieldDecl*.
4170 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004171 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00004172
4173 // Mapping for the inconsistent anonymous-union initializers check.
4174 RedundantUnionMap MemberUnions;
4175
Anders Carlssonea356fb2010-04-02 05:42:15 +00004176 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00004177 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00004178 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004179
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00004180 // Set the source order index.
4181 Init->setSourceOrder(i);
4182
Francois Pichet00eb3f92010-12-04 09:14:42 +00004183 if (Init->isAnyMemberInitializer()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004184 const void *Key = GetKeyForMember(Context, Init);
4185 if (CheckRedundantInit(*this, Init, Members[Key]) ||
John McCall3c3ccdb2010-04-10 09:28:51 +00004186 CheckRedundantUnionInit(*this, Init, MemberUnions))
4187 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00004188 } else if (Init->isBaseInitializer()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004189 const void *Key = GetKeyForMember(Context, Init);
John McCall3c3ccdb2010-04-10 09:28:51 +00004190 if (CheckRedundantInit(*this, Init, Members[Key]))
4191 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00004192 } else {
4193 assert(Init->isDelegatingInitializer());
4194 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00004195 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00004196 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00004197 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00004198 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00004199 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00004200 }
Sean Huntfe57eef2011-05-04 05:57:24 +00004201 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00004202 // Return immediately as the initializer is set.
4203 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004204 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004205 }
4206
Anders Carlssonea356fb2010-04-02 05:42:15 +00004207 if (HadError)
4208 return;
4209
David Blaikie93c86172013-01-17 05:26:25 +00004210 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00004211
David Blaikie93c86172013-01-17 05:26:25 +00004212 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu225e9822013-09-16 21:54:53 +00004213
Richard Trieu858d2ba2013-10-25 00:56:00 +00004214 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00004215}
4216
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004217void
John McCallef027fe2010-03-16 21:39:52 +00004218Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
4219 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00004220 // Ignore dependent contexts. Also ignore unions, since their members never
4221 // have destructors implicitly called.
4222 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00004223 return;
John McCall58e6f342010-03-16 05:22:47 +00004224
4225 // FIXME: all the access-control diagnostics are positioned on the
4226 // field/base declaration. That's probably good; that said, the
4227 // user might reasonably want to know why the destructor is being
4228 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00004229
Anders Carlsson9f853df2009-11-17 04:44:12 +00004230 // Non-static data members.
Stephen Hines651f13c2014-04-23 16:59:28 -07004231 for (auto *Field : ClassDecl->fields()) {
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00004232 if (Field->isInvalidDecl())
4233 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00004234
4235 // Don't destroy incomplete or zero-length arrays.
4236 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
4237 continue;
4238
Anders Carlsson9f853df2009-11-17 04:44:12 +00004239 QualType FieldType = Context.getBaseElementType(Field->getType());
4240
4241 const RecordType* RT = FieldType->getAs<RecordType>();
4242 if (!RT)
4243 continue;
4244
4245 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004246 if (FieldClassDecl->isInvalidDecl())
4247 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004248 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00004249 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00004250 // The destructor for an implicit anonymous union member is never invoked.
4251 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
4252 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00004253
Douglas Gregordb89f282010-07-01 22:47:18 +00004254 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004255 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00004256 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004257 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00004258 << Field->getDeclName()
4259 << FieldType);
4260
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004261 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004262 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00004263 }
4264
John McCall58e6f342010-03-16 05:22:47 +00004265 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
4266
Anders Carlsson9f853df2009-11-17 04:44:12 +00004267 // Bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004268 for (const auto &Base : ClassDecl->bases()) {
John McCall58e6f342010-03-16 05:22:47 +00004269 // Bases are always records in a well-formed non-dependent class.
Stephen Hines651f13c2014-04-23 16:59:28 -07004270 const RecordType *RT = Base.getType()->getAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00004271
4272 // Remember direct virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004273 if (Base.isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00004274 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00004275
John McCall58e6f342010-03-16 05:22:47 +00004276 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004277 // If our base class is invalid, we probably can't get its dtor anyway.
4278 if (BaseClassDecl->isInvalidDecl())
4279 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004280 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00004281 continue;
John McCall58e6f342010-03-16 05:22:47 +00004282
Douglas Gregordb89f282010-07-01 22:47:18 +00004283 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004284 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00004285
4286 // FIXME: caret should be on the start of the class name
Stephen Hines651f13c2014-04-23 16:59:28 -07004287 CheckDestructorAccess(Base.getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004288 PDiag(diag::err_access_dtor_base)
Stephen Hines651f13c2014-04-23 16:59:28 -07004289 << Base.getType()
4290 << Base.getSourceRange(),
John McCallb9abd8722012-04-07 03:04:20 +00004291 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00004292
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004293 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004294 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00004295 }
4296
4297 // Virtual bases.
Stephen Hines651f13c2014-04-23 16:59:28 -07004298 for (const auto &VBase : ClassDecl->vbases()) {
John McCall58e6f342010-03-16 05:22:47 +00004299 // Bases are always records in a well-formed non-dependent class.
Stephen Hines651f13c2014-04-23 16:59:28 -07004300 const RecordType *RT = VBase.getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00004301
4302 // Ignore direct virtual bases.
4303 if (DirectVirtualBases.count(RT))
4304 continue;
4305
John McCall58e6f342010-03-16 05:22:47 +00004306 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004307 // If our base class is invalid, we probably can't get its dtor anyway.
4308 if (BaseClassDecl->isInvalidDecl())
4309 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004310 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004311 continue;
John McCall58e6f342010-03-16 05:22:47 +00004312
Douglas Gregordb89f282010-07-01 22:47:18 +00004313 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004314 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00004315 if (CheckDestructorAccess(
4316 ClassDecl->getLocation(), Dtor,
4317 PDiag(diag::err_access_dtor_vbase)
Stephen Hines651f13c2014-04-23 16:59:28 -07004318 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
David Majnemer2f686692013-06-22 06:43:58 +00004319 Context.getTypeDeclType(ClassDecl)) ==
4320 AR_accessible) {
4321 CheckDerivedToBaseConversion(
Stephen Hines651f13c2014-04-23 16:59:28 -07004322 Context.getTypeDeclType(ClassDecl), VBase.getType(),
David Majnemer2f686692013-06-22 06:43:58 +00004323 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004324 SourceRange(), DeclarationName(), nullptr);
David Majnemer2f686692013-06-22 06:43:58 +00004325 }
John McCall58e6f342010-03-16 05:22:47 +00004326
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004327 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004328 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004329 }
4330}
4331
John McCalld226f652010-08-21 09:40:31 +00004332void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00004333 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004334 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004335
Mike Stump1eb44332009-09-09 15:08:12 +00004336 if (CXXConstructorDecl *Constructor
Richard Trieu858d2ba2013-10-25 00:56:00 +00004337 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie93c86172013-01-17 05:26:25 +00004338 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieu858d2ba2013-10-25 00:56:00 +00004339 DiagnoseUninitializedFields(*this, Constructor);
4340 }
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004341}
4342
Mike Stump1eb44332009-09-09 15:08:12 +00004343bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00004344 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004345 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4346 unsigned DiagID;
4347 AbstractDiagSelID SelID;
4348
4349 public:
4350 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4351 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004352
Stephen Hines651f13c2014-04-23 16:59:28 -07004353 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Eli Friedman2217f852012-08-14 02:06:07 +00004354 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004355 if (SelID == -1)
4356 S.Diag(Loc, DiagID) << T;
4357 else
4358 S.Diag(Loc, DiagID) << SelID << T;
4359 }
4360 } Diagnoser(DiagID, SelID);
4361
4362 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004363}
4364
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00004365bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004366 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004367 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004368 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004369
Anders Carlsson11f21a02009-03-23 19:10:31 +00004370 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004371 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004372
Ted Kremenek6217b802009-07-29 21:53:49 +00004373 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004374 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004375 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004376 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00004377
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004378 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004379 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004380 }
Mike Stump1eb44332009-09-09 15:08:12 +00004381
Ted Kremenek6217b802009-07-29 21:53:49 +00004382 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004383 if (!RT)
4384 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004385
John McCall86ff3082010-02-04 22:26:26 +00004386 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004387
John McCall94c3b562010-08-18 09:41:07 +00004388 // We can't answer whether something is abstract until it has a
4389 // definition. If it's currently being defined, we'll walk back
4390 // over all the declarations when we have a full definition.
4391 const CXXRecordDecl *Def = RD->getDefinition();
4392 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00004393 return false;
4394
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004395 if (!RD->isAbstract())
4396 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004397
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004398 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00004399 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00004400
John McCall94c3b562010-08-18 09:41:07 +00004401 return true;
4402}
4403
4404void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4405 // Check if we've already emitted the list of pure virtual functions
4406 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004407 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00004408 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004409
Richard Smithcbc820a2013-07-22 02:56:56 +00004410 // If the diagnostic is suppressed, don't emit the notes. We're only
4411 // going to emit them once, so try to attach them to a diagnostic we're
4412 // actually going to show.
4413 if (Diags.isLastDiagnosticIgnored())
4414 return;
4415
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004416 CXXFinalOverriderMap FinalOverriders;
4417 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00004418
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004419 // Keep a set of seen pure methods so we won't diagnose the same method
4420 // more than once.
4421 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4422
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004423 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4424 MEnd = FinalOverriders.end();
4425 M != MEnd;
4426 ++M) {
4427 for (OverridingMethods::iterator SO = M->second.begin(),
4428 SOEnd = M->second.end();
4429 SO != SOEnd; ++SO) {
4430 // C++ [class.abstract]p4:
4431 // A class is abstract if it contains or inherits at least one
4432 // pure virtual function for which the final overrider is pure
4433 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00004434
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004435 //
4436 if (SO->second.size() != 1)
4437 continue;
4438
4439 if (!SO->second.front().Method->isPure())
4440 continue;
4441
Stephen Hines176edba2014-12-01 14:53:08 -08004442 if (!SeenPureMethods.insert(SO->second.front().Method).second)
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004443 continue;
4444
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004445 Diag(SO->second.front().Method->getLocation(),
4446 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00004447 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004448 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004449 }
4450
4451 if (!PureVirtualClassDiagSet)
4452 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4453 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004454}
4455
Anders Carlsson8211eff2009-03-24 01:19:16 +00004456namespace {
John McCall94c3b562010-08-18 09:41:07 +00004457struct AbstractUsageInfo {
4458 Sema &S;
4459 CXXRecordDecl *Record;
4460 CanQualType AbstractType;
4461 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00004462
John McCall94c3b562010-08-18 09:41:07 +00004463 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4464 : S(S), Record(Record),
4465 AbstractType(S.Context.getCanonicalType(
4466 S.Context.getTypeDeclType(Record))),
4467 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00004468
John McCall94c3b562010-08-18 09:41:07 +00004469 void DiagnoseAbstractType() {
4470 if (Invalid) return;
4471 S.DiagnoseAbstractType(Record);
4472 Invalid = true;
4473 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00004474
John McCall94c3b562010-08-18 09:41:07 +00004475 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4476};
4477
4478struct CheckAbstractUsage {
4479 AbstractUsageInfo &Info;
4480 const NamedDecl *Ctx;
4481
4482 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4483 : Info(Info), Ctx(Ctx) {}
4484
4485 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4486 switch (TL.getTypeLocClass()) {
4487#define ABSTRACT_TYPELOC(CLASS, PARENT)
4488#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004489 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004490#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004491 }
John McCall94c3b562010-08-18 09:41:07 +00004492 }
Mike Stump1eb44332009-09-09 15:08:12 +00004493
John McCall94c3b562010-08-18 09:41:07 +00004494 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004495 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
4496 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
4497 if (!TL.getParam(I))
Douglas Gregor70191862011-02-22 23:21:06 +00004498 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07004499
4500 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
John McCall94c3b562010-08-18 09:41:07 +00004501 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004502 }
John McCall94c3b562010-08-18 09:41:07 +00004503 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004504
John McCall94c3b562010-08-18 09:41:07 +00004505 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4506 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4507 }
Mike Stump1eb44332009-09-09 15:08:12 +00004508
John McCall94c3b562010-08-18 09:41:07 +00004509 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4510 // Visit the type parameters from a permissive context.
4511 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4512 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4513 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4514 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4515 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4516 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004517 }
John McCall94c3b562010-08-18 09:41:07 +00004518 }
Mike Stump1eb44332009-09-09 15:08:12 +00004519
John McCall94c3b562010-08-18 09:41:07 +00004520 // Visit pointee types from a permissive context.
4521#define CheckPolymorphic(Type) \
4522 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4523 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4524 }
4525 CheckPolymorphic(PointerTypeLoc)
4526 CheckPolymorphic(ReferenceTypeLoc)
4527 CheckPolymorphic(MemberPointerTypeLoc)
4528 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004529 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004530
John McCall94c3b562010-08-18 09:41:07 +00004531 /// Handle all the types we haven't given a more specific
4532 /// implementation for above.
4533 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4534 // Every other kind of type that we haven't called out already
4535 // that has an inner type is either (1) sugar or (2) contains that
4536 // inner type in some way as a subobject.
4537 if (TypeLoc Next = TL.getNextTypeLoc())
4538 return Visit(Next, Sel);
4539
4540 // If there's no inner type and we're in a permissive context,
4541 // don't diagnose.
4542 if (Sel == Sema::AbstractNone) return;
4543
4544 // Check whether the type matches the abstract type.
4545 QualType T = TL.getType();
4546 if (T->isArrayType()) {
4547 Sel = Sema::AbstractArrayType;
4548 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004549 }
John McCall94c3b562010-08-18 09:41:07 +00004550 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4551 if (CT != Info.AbstractType) return;
4552
4553 // It matched; do some magic.
4554 if (Sel == Sema::AbstractArrayType) {
4555 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4556 << T << TL.getSourceRange();
4557 } else {
4558 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4559 << Sel << T << TL.getSourceRange();
4560 }
4561 Info.DiagnoseAbstractType();
4562 }
4563};
4564
4565void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4566 Sema::AbstractDiagSelID Sel) {
4567 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4568}
4569
4570}
4571
4572/// Check for invalid uses of an abstract type in a method declaration.
4573static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4574 CXXMethodDecl *MD) {
4575 // No need to do the check on definitions, which require that
4576 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004577 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004578 return;
4579
4580 // For safety's sake, just ignore it if we don't have type source
4581 // information. This should never happen for non-implicit methods,
4582 // but...
4583 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4584 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4585}
4586
4587/// Check for invalid uses of an abstract type within a class definition.
4588static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4589 CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004590 for (auto *D : RD->decls()) {
John McCall94c3b562010-08-18 09:41:07 +00004591 if (D->isImplicit()) continue;
4592
4593 // Methods and method templates.
4594 if (isa<CXXMethodDecl>(D)) {
4595 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4596 } else if (isa<FunctionTemplateDecl>(D)) {
4597 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4598 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4599
4600 // Fields and static variables.
4601 } else if (isa<FieldDecl>(D)) {
4602 FieldDecl *FD = cast<FieldDecl>(D);
4603 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4604 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4605 } else if (isa<VarDecl>(D)) {
4606 VarDecl *VD = cast<VarDecl>(D);
4607 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4608 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4609
4610 // Nested classes and class templates.
4611 } else if (isa<CXXRecordDecl>(D)) {
4612 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4613 } else if (isa<ClassTemplateDecl>(D)) {
4614 CheckAbstractClassUsage(Info,
4615 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4616 }
4617 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004618}
4619
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004620/// \brief Check class-level dllimport/dllexport attribute.
4621static void checkDLLAttribute(Sema &S, CXXRecordDecl *Class) {
4622 Attr *ClassAttr = getDLLAttr(Class);
Stephen Hines176edba2014-12-01 14:53:08 -08004623
4624 // MSVC inherits DLL attributes to partial class template specializations.
4625 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
4626 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
4627 if (Attr *TemplateAttr =
4628 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
4629 auto *A = cast<InheritableAttr>(TemplateAttr->clone(S.getASTContext()));
4630 A->setInherited(true);
4631 ClassAttr = A;
4632 }
4633 }
4634 }
4635
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004636 if (!ClassAttr)
4637 return;
4638
Stephen Hines176edba2014-12-01 14:53:08 -08004639 if (!Class->isExternallyVisible()) {
4640 S.Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
4641 << Class << ClassAttr;
4642 return;
4643 }
4644
4645 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
4646 !ClassAttr->isInherited()) {
4647 // Diagnose dll attributes on members of class with dll attribute.
4648 for (Decl *Member : Class->decls()) {
4649 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
4650 continue;
4651 InheritableAttr *MemberAttr = getDLLAttr(Member);
4652 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
4653 continue;
4654
4655 S.Diag(MemberAttr->getLocation(),
4656 diag::err_attribute_dll_member_of_dll_class)
4657 << MemberAttr << ClassAttr;
4658 S.Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
4659 Member->setInvalidDecl();
4660 }
4661 }
4662
4663 if (Class->getDescribedClassTemplate())
4664 // Don't inherit dll attribute until the template is instantiated.
4665 return;
4666
4667 // The class is either imported or exported.
4668 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
4669 const bool ClassImported = !ClassExported;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004670
4671 // Force declaration of implicit members so they can inherit the attribute.
4672 S.ForceDeclarationOfImplicitMembers(Class);
4673
4674 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
4675 // seem to be true in practice?
4676
Stephen Hines176edba2014-12-01 14:53:08 -08004677 TemplateSpecializationKind TSK =
4678 Class->getTemplateSpecializationKind();
4679
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004680 for (Decl *Member : Class->decls()) {
4681 VarDecl *VD = dyn_cast<VarDecl>(Member);
4682 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
4683
4684 // Only methods and static fields inherit the attributes.
4685 if (!VD && !MD)
4686 continue;
4687
Stephen Hines176edba2014-12-01 14:53:08 -08004688 if (MD) {
4689 // Don't process deleted methods.
4690 if (MD->isDeleted())
4691 continue;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004692
Stephen Hines176edba2014-12-01 14:53:08 -08004693 if (MD->isMoveAssignmentOperator() && ClassImported && MD->isInlined()) {
4694 // Current MSVC versions don't export the move assignment operators, so
4695 // don't attempt to import them if we have a definition.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004696 continue;
4697 }
Stephen Hines176edba2014-12-01 14:53:08 -08004698
4699 if (MD->isInlined() && ClassImported &&
4700 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4701 // MinGW does not import inline functions.
4702 continue;
4703 }
4704 }
4705
4706 if (!getDLLAttr(Member)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004707 auto *NewAttr =
4708 cast<InheritableAttr>(ClassAttr->clone(S.getASTContext()));
4709 NewAttr->setInherited(true);
4710 Member->addAttr(NewAttr);
4711 }
4712
Stephen Hines176edba2014-12-01 14:53:08 -08004713 if (MD && ClassExported) {
4714 if (MD->isUserProvided()) {
4715 // Instantiate non-default methods..
4716
4717 // .. except for certain kinds of template specializations.
4718 if (TSK == TSK_ExplicitInstantiationDeclaration)
4719 continue;
4720 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
4721 continue;
4722
4723 S.MarkFunctionReferenced(Class->getLocation(), MD);
4724 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
4725 MD->isCopyAssignmentOperator() ||
4726 MD->isMoveAssignmentOperator()) {
4727 // Instantiate non-trivial or explicitly defaulted methods, and the
4728 // copy assignment / move assignment operators.
4729 S.MarkFunctionReferenced(Class->getLocation(), MD);
4730 // Resolve its exception specification; CodeGen needs it.
4731 auto *FPT = MD->getType()->getAs<FunctionProtoType>();
4732 S.ResolveExceptionSpec(Class->getLocation(), FPT);
4733 S.ActOnFinishInlineMethodDef(MD);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004734 }
4735 }
4736 }
4737}
4738
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004739/// \brief Perform semantic checks on a class definition that has been
4740/// completing, introducing implicitly-declared members, checking for
4741/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004742void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004743 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004744 return;
4745
John McCall94c3b562010-08-18 09:41:07 +00004746 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4747 AbstractUsageInfo Info(*this, Record);
4748 CheckAbstractClassUsage(Info, Record);
4749 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004750
4751 // If this is not an aggregate type and has no user-declared constructor,
4752 // complain about any non-static data members of reference or const scalar
4753 // type, since they will never get initializers.
4754 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004755 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4756 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004757 bool Complained = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07004758 for (const auto *F : Record->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +00004759 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004760 continue;
4761
Douglas Gregor325e5932010-04-15 00:00:53 +00004762 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004763 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004764 if (!Complained) {
4765 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4766 << Record->getTagKind() << Record;
4767 Complained = true;
4768 }
4769
4770 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4771 << F->getType()->isReferenceType()
4772 << F->getDeclName();
4773 }
4774 }
4775 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004776
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004777 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004778 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004779
4780 if (Record->getIdentifier()) {
4781 // C++ [class.mem]p13:
4782 // If T is the name of a class, then each of the following shall have a
4783 // name different from T:
4784 // - every member of every anonymous union that is a member of class T.
4785 //
4786 // C++ [class.mem]p14:
4787 // In addition, if class T has a user-declared constructor (12.1), every
4788 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004789 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4790 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4791 ++I) {
4792 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004793 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4794 isa<IndirectFieldDecl>(D)) {
4795 Diag(D->getLocation(), diag::err_member_name_of_class)
4796 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004797 break;
4798 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004799 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004800 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004801
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004802 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004803 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004804 CXXDestructorDecl *dtor = Record->getDestructor();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004805 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
4806 !Record->hasAttr<FinalAttr>())
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004807 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4808 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4809 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004810
David Majnemer7121bdb2013-10-18 00:33:31 +00004811 if (Record->isAbstract()) {
4812 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4813 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4814 << FA->isSpelledAsSealed();
4815 DiagnoseAbstractType(Record);
4816 }
David Blaikieb6b5b972012-09-21 03:21:07 +00004817 }
4818
Stephen Hines176edba2014-12-01 14:53:08 -08004819 bool HasMethodWithOverrideControl = false,
4820 HasOverridingMethodWithoutOverrideControl = false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004821 if (!Record->isDependentType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004822 for (auto *M : Record->methods()) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004823 // See if a method overloads virtual methods in a base
4824 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004825 if (!M->isStatic())
Stephen Hines651f13c2014-04-23 16:59:28 -07004826 DiagnoseHiddenVirtualMethods(M);
Stephen Hines176edba2014-12-01 14:53:08 -08004827 if (M->hasAttr<OverrideAttr>())
4828 HasMethodWithOverrideControl = true;
4829 else if (M->size_overridden_methods() > 0)
4830 HasOverridingMethodWithoutOverrideControl = true;
Richard Smith1d28caf2012-12-11 01:14:52 +00004831 // Check whether the explicitly-defaulted special members are valid.
4832 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
Stephen Hines651f13c2014-04-23 16:59:28 -07004833 CheckExplicitlyDefaultedSpecialMember(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004834
4835 // For an explicitly defaulted or deleted special member, we defer
4836 // determining triviality until the class is complete. That time is now!
4837 if (!M->isImplicit() && !M->isUserProvided()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004838 CXXSpecialMember CSM = getSpecialMember(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004839 if (CSM != CXXInvalid) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004840 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
Richard Smith1d28caf2012-12-11 01:14:52 +00004841
4842 // Inform the class that we've finished declaring this member.
Stephen Hines651f13c2014-04-23 16:59:28 -07004843 Record->finishedDefaultedOrDeletedMember(M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004844 }
4845 }
4846 }
4847 }
4848
Stephen Hines176edba2014-12-01 14:53:08 -08004849 if (HasMethodWithOverrideControl &&
4850 HasOverridingMethodWithoutOverrideControl) {
4851 // At least one method has the 'override' control declared.
4852 // Diagnose all other overridden methods which do not have 'override' specified on them.
4853 for (auto *M : Record->methods())
4854 DiagnoseAbsenceOfOverrideControl(M);
4855 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004856 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4857 // function that is not a constructor declares that member function to be
4858 // const. [...] The class of which that function is a member shall be
4859 // a literal type.
4860 //
4861 // If the class has virtual bases, any constexpr members will already have
4862 // been diagnosed by the checks performed on the member declaration, so
4863 // suppress this (less useful) diagnostic.
4864 //
4865 // We delay this until we know whether an explicitly-defaulted (or deleted)
4866 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004867 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004868 !Record->isLiteral() && !Record->getNumVBases()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004869 for (const auto *M : Record->methods()) {
4870 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(M)) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004871 switch (Record->getTemplateSpecializationKind()) {
4872 case TSK_ImplicitInstantiation:
4873 case TSK_ExplicitInstantiationDeclaration:
4874 case TSK_ExplicitInstantiationDefinition:
4875 // If a template instantiates to a non-literal type, but its members
4876 // instantiate to constexpr functions, the template is technically
4877 // ill-formed, but we allow it for sanity.
4878 continue;
4879
4880 case TSK_Undeclared:
4881 case TSK_ExplicitSpecialization:
4882 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4883 diag::err_constexpr_method_non_literal);
4884 break;
4885 }
4886
4887 // Only produce one error per class.
4888 break;
4889 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004890 }
4891 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004892
Stephen Hines651f13c2014-04-23 16:59:28 -07004893 // ms_struct is a request to use the same ABI rules as MSVC. Check
4894 // whether this class uses any C++ features that are implemented
4895 // completely differently in MSVC, and if so, emit a diagnostic.
4896 // That diagnostic defaults to an error, but we allow projects to
4897 // map it down to a warning (or ignore it). It's a fairly common
4898 // practice among users of the ms_struct pragma to mass-annotate
4899 // headers, sweeping up a bunch of types that the project doesn't
4900 // really rely on MSVC-compatible layout for. We must therefore
4901 // support "ms_struct except for C++ stuff" as a secondary ABI.
4902 if (Record->isMsStruct(Context) &&
4903 (Record->isPolymorphic() || Record->getNumBases())) {
4904 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
Warren Huntb2969b12013-10-11 20:19:00 +00004905 }
4906
Richard Smith07b0fdc2013-03-18 21:12:30 +00004907 // Declare inheriting constructors. We do this eagerly here because:
4908 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004909 // constructors from different classes.
4910 // - The lazy declaration of the other implicit constructors is so as to not
4911 // waste space and performance on classes that are not meant to be
4912 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004913 // have inheriting constructors.
4914 DeclareInheritingConstructors(Record);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07004915
4916 checkDLLAttribute(*this, Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004917}
4918
Stephen Hines651f13c2014-04-23 16:59:28 -07004919/// Look up the special member function that would be called by a special
4920/// member function for a subobject of class type.
4921///
4922/// \param Class The class type of the subobject.
4923/// \param CSM The kind of special member function.
4924/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
4925/// \param ConstRHS True if this is a copy operation with a const object
4926/// on its RHS, that is, if the argument to the outer special member
4927/// function is 'const' and this is not a field marked 'mutable'.
4928static Sema::SpecialMemberOverloadResult *lookupCallFromSpecialMember(
4929 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
4930 unsigned FieldQuals, bool ConstRHS) {
4931 unsigned LHSQuals = 0;
4932 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
4933 LHSQuals = FieldQuals;
4934
4935 unsigned RHSQuals = FieldQuals;
4936 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4937 RHSQuals = 0;
4938 else if (ConstRHS)
4939 RHSQuals |= Qualifiers::Const;
4940
4941 return S.LookupSpecialMember(Class, CSM,
4942 RHSQuals & Qualifiers::Const,
4943 RHSQuals & Qualifiers::Volatile,
4944 false,
4945 LHSQuals & Qualifiers::Const,
4946 LHSQuals & Qualifiers::Volatile);
4947}
4948
Richard Smith7756afa2012-06-10 05:43:50 +00004949/// Is the special member function which would be selected to perform the
4950/// specified operation on the specified class type a constexpr constructor?
4951static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4952 Sema::CXXSpecialMember CSM,
Stephen Hines651f13c2014-04-23 16:59:28 -07004953 unsigned Quals, bool ConstRHS) {
Richard Smith7756afa2012-06-10 05:43:50 +00004954 Sema::SpecialMemberOverloadResult *SMOR =
Stephen Hines651f13c2014-04-23 16:59:28 -07004955 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
Richard Smith7756afa2012-06-10 05:43:50 +00004956 if (!SMOR || !SMOR->getMethod())
4957 // A constructor we wouldn't select can't be "involved in initializing"
4958 // anything.
4959 return true;
4960 return SMOR->getMethod()->isConstexpr();
4961}
4962
4963/// Determine whether the specified special member function would be constexpr
4964/// if it were implicitly defined.
4965static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4966 Sema::CXXSpecialMember CSM,
4967 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004968 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004969 return false;
4970
4971 // C++11 [dcl.constexpr]p4:
4972 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004973 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004974 switch (CSM) {
4975 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004976 // Since default constructor lookup is essentially trivial (and cannot
4977 // involve, for instance, template instantiation), we compute whether a
4978 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4979 //
4980 // This is important for performance; we need to know whether the default
4981 // constructor is constexpr to determine whether the type is a literal type.
4982 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4983
Richard Smith7756afa2012-06-10 05:43:50 +00004984 case Sema::CXXCopyConstructor:
4985 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004986 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004987 break;
4988
4989 case Sema::CXXCopyAssignment:
4990 case Sema::CXXMoveAssignment:
Stephen Hines176edba2014-12-01 14:53:08 -08004991 if (!S.getLangOpts().CPlusPlus14)
Richard Smitha8942d72013-05-07 03:19:20 +00004992 return false;
4993 // In C++1y, we need to perform overload resolution.
4994 Ctor = false;
4995 break;
4996
Richard Smith7756afa2012-06-10 05:43:50 +00004997 case Sema::CXXDestructor:
4998 case Sema::CXXInvalid:
4999 return false;
5000 }
5001
5002 // -- if the class is a non-empty union, or for each non-empty anonymous
5003 // union member of a non-union class, exactly one non-static data member
5004 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00005005 //
5006 // If we squint, this is guaranteed, since exactly one non-static data member
5007 // will be initialized (if the constructor isn't deleted), we just don't know
5008 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00005009 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00005010 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00005011
5012 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00005013 if (Ctor && ClassDecl->getNumVBases())
5014 return false;
5015
5016 // C++1y [class.copy]p26:
5017 // -- [the class] is a literal type, and
5018 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00005019 return false;
5020
5021 // -- every constructor involved in initializing [...] base class
5022 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00005023 // -- the assignment operator selected to copy/move each direct base
5024 // class is a constexpr function, and
Stephen Hines651f13c2014-04-23 16:59:28 -07005025 for (const auto &B : ClassDecl->bases()) {
5026 const RecordType *BaseType = B.getType()->getAs<RecordType>();
Richard Smith7756afa2012-06-10 05:43:50 +00005027 if (!BaseType) continue;
5028
5029 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07005030 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg))
Richard Smith7756afa2012-06-10 05:43:50 +00005031 return false;
5032 }
5033
5034 // -- every constructor involved in initializing non-static data members
5035 // [...] shall be a constexpr constructor;
5036 // -- every non-static data member and base class sub-object shall be
5037 // initialized
Stephen Hines651f13c2014-04-23 16:59:28 -07005038 // -- for each non-static data member of X that is of class type (or array
Richard Smitha8942d72013-05-07 03:19:20 +00005039 // thereof), the assignment operator selected to copy/move that member is
5040 // a constexpr function
Stephen Hines651f13c2014-04-23 16:59:28 -07005041 for (const auto *F : ClassDecl->fields()) {
Richard Smith7756afa2012-06-10 05:43:50 +00005042 if (F->isInvalidDecl())
5043 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07005044 QualType BaseType = S.Context.getBaseElementType(F->getType());
5045 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00005046 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07005047 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
5048 BaseType.getCVRQualifiers(),
5049 ConstArg && !F->isMutable()))
Richard Smith7756afa2012-06-10 05:43:50 +00005050 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00005051 }
5052 }
5053
5054 // All OK, it's constexpr!
5055 return true;
5056}
5057
Richard Smithb9d0b762012-07-27 04:22:15 +00005058static Sema::ImplicitExceptionSpecification
5059computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
5060 switch (S.getSpecialMember(MD)) {
5061 case Sema::CXXDefaultConstructor:
5062 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
5063 case Sema::CXXCopyConstructor:
5064 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
5065 case Sema::CXXCopyAssignment:
5066 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
5067 case Sema::CXXMoveConstructor:
5068 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
5069 case Sema::CXXMoveAssignment:
5070 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
5071 case Sema::CXXDestructor:
5072 return S.ComputeDefaultedDtorExceptionSpec(MD);
5073 case Sema::CXXInvalid:
5074 break;
5075 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00005076 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
5077 "only special members have implicit exception specs");
5078 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00005079}
5080
Reid Kleckneref072032013-08-27 23:08:25 +00005081static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
5082 CXXMethodDecl *MD) {
5083 FunctionProtoType::ExtProtoInfo EPI;
5084
5085 // Build an exception specification pointing back at this member.
Stephen Hines176edba2014-12-01 14:53:08 -08005086 EPI.ExceptionSpec.Type = EST_Unevaluated;
5087 EPI.ExceptionSpec.SourceDecl = MD;
Reid Kleckneref072032013-08-27 23:08:25 +00005088
5089 // Set the calling convention to the default for C++ instance methods.
5090 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
5091 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5092 /*IsCXXMethod=*/true));
5093 return EPI;
5094}
5095
Richard Smithb9d0b762012-07-27 04:22:15 +00005096void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
5097 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
5098 if (FPT->getExceptionSpecType() != EST_Unevaluated)
5099 return;
5100
Richard Smithdd25e802012-07-30 23:48:14 +00005101 // Evaluate the exception specification.
Stephen Hines176edba2014-12-01 14:53:08 -08005102 auto ESI = computeImplicitExceptionSpec(*this, Loc, MD).getExceptionSpec();
Stephen Hines651f13c2014-04-23 16:59:28 -07005103
Richard Smithdd25e802012-07-30 23:48:14 +00005104 // Update the type of the special member to use it.
Stephen Hines176edba2014-12-01 14:53:08 -08005105 UpdateExceptionSpec(MD, ESI);
Richard Smithdd25e802012-07-30 23:48:14 +00005106
5107 // A user-provided destructor can be defined outside the class. When that
5108 // happens, be sure to update the exception specification on both
5109 // declarations.
5110 const FunctionProtoType *CanonicalFPT =
5111 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
5112 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
Stephen Hines176edba2014-12-01 14:53:08 -08005113 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
Richard Smithb9d0b762012-07-27 04:22:15 +00005114}
5115
Richard Smith3003e1d2012-05-15 04:39:51 +00005116void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
5117 CXXRecordDecl *RD = MD->getParent();
5118 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00005119
Richard Smith3003e1d2012-05-15 04:39:51 +00005120 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
5121 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00005122
5123 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00005124 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00005125 bool First = MD == MD->getCanonicalDecl();
5126
5127 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00005128
5129 // C++11 [dcl.fct.def.default]p1:
5130 // A function that is explicitly defaulted shall
5131 // -- be a special member function (checked elsewhere),
5132 // -- have the same type (except for ref-qualifiers, and except that a
5133 // copy operation can take a non-const reference) as an implicit
5134 // declaration, and
5135 // -- not have default arguments.
5136 unsigned ExpectedParams = 1;
5137 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
5138 ExpectedParams = 0;
5139 if (MD->getNumParams() != ExpectedParams) {
5140 // This also checks for default arguments: a copy or move constructor with a
5141 // default argument is classified as a default constructor, and assignment
5142 // operations and destructors can't have default arguments.
5143 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
5144 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00005145 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00005146 } else if (MD->isVariadic()) {
5147 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
5148 << CSM << MD->getSourceRange();
5149 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00005150 }
5151
Richard Smith3003e1d2012-05-15 04:39:51 +00005152 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00005153
Richard Smith7756afa2012-06-10 05:43:50 +00005154 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00005155 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00005156 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00005157 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00005158 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00005159
Richard Smith3003e1d2012-05-15 04:39:51 +00005160 QualType ReturnType = Context.VoidTy;
5161 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
5162 // Check for return type matching.
Stephen Hines651f13c2014-04-23 16:59:28 -07005163 ReturnType = Type->getReturnType();
Richard Smith3003e1d2012-05-15 04:39:51 +00005164 QualType ExpectedReturnType =
5165 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
5166 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
5167 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
5168 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
5169 HadError = true;
5170 }
5171
5172 // A defaulted special member cannot have cv-qualifiers.
5173 if (Type->getTypeQuals()) {
5174 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Stephen Hines176edba2014-12-01 14:53:08 -08005175 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
Richard Smith3003e1d2012-05-15 04:39:51 +00005176 HadError = true;
5177 }
5178 }
5179
5180 // Check for parameter type matching.
Stephen Hines651f13c2014-04-23 16:59:28 -07005181 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00005182 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00005183 if (ExpectedParams && ArgType->isReferenceType()) {
5184 // Argument must be reference to possibly-const T.
5185 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00005186 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00005187
5188 if (ReferentType.isVolatileQualified()) {
5189 Diag(MD->getLocation(),
5190 diag::err_defaulted_special_member_volatile_param) << CSM;
5191 HadError = true;
5192 }
5193
Richard Smith7756afa2012-06-10 05:43:50 +00005194 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00005195 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
5196 Diag(MD->getLocation(),
5197 diag::err_defaulted_special_member_copy_const_param)
5198 << (CSM == CXXCopyAssignment);
5199 // FIXME: Explain why this special member can't be const.
5200 } else {
5201 Diag(MD->getLocation(),
5202 diag::err_defaulted_special_member_move_const_param)
5203 << (CSM == CXXMoveAssignment);
5204 }
5205 HadError = true;
5206 }
Richard Smith3003e1d2012-05-15 04:39:51 +00005207 } else if (ExpectedParams) {
5208 // A copy assignment operator can take its argument by value, but a
5209 // defaulted one cannot.
5210 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00005211 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00005212 HadError = true;
5213 }
Sean Huntbe631222011-05-17 20:44:43 +00005214
Richard Smith61802452011-12-22 02:22:31 +00005215 // C++11 [dcl.fct.def.default]p2:
5216 // An explicitly-defaulted function may be declared constexpr only if it
5217 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00005218 // Do not apply this rule to members of class templates, since core issue 1358
5219 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00005220 // functions which cannot be constexpr (for non-constructors in C++11 and for
5221 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00005222 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
5223 HasConstParam);
Stephen Hines176edba2014-12-01 14:53:08 -08005224 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
Richard Smitha8942d72013-05-07 03:19:20 +00005225 : isa<CXXConstructorDecl>(MD)) &&
5226 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00005227 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
5228 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00005229 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00005230 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00005231 }
Richard Smith1d28caf2012-12-11 01:14:52 +00005232
Richard Smith61802452011-12-22 02:22:31 +00005233 // and may have an explicit exception-specification only if it is compatible
5234 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00005235 if (Type->hasExceptionSpec()) {
5236 // Delay the check if this is the first declaration of the special member,
5237 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00005238 if (First) {
5239 // If the exception specification needs to be instantiated, do so now,
5240 // before we clobber it with an EST_Unevaluated specification below.
5241 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
5242 InstantiateExceptionSpec(MD->getLocStart(), MD);
5243 Type = MD->getType()->getAs<FunctionProtoType>();
5244 }
Richard Smith1d28caf2012-12-11 01:14:52 +00005245 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00005246 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00005247 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
5248 }
Richard Smith61802452011-12-22 02:22:31 +00005249
5250 // If a function is explicitly defaulted on its first declaration,
5251 if (First) {
5252 // -- it is implicitly considered to be constexpr if the implicit
5253 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00005254 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00005255
Richard Smith3003e1d2012-05-15 04:39:51 +00005256 // -- it is implicitly considered to have the same exception-specification
5257 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00005258 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
Stephen Hines176edba2014-12-01 14:53:08 -08005259 EPI.ExceptionSpec.Type = EST_Unevaluated;
5260 EPI.ExceptionSpec.SourceDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00005261 MD->setType(Context.getFunctionType(ReturnType,
Stephen Hines176edba2014-12-01 14:53:08 -08005262 llvm::makeArrayRef(&ArgType,
Jordan Rosebea522f2013-03-08 21:51:21 +00005263 ExpectedParams),
5264 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00005265 }
5266
Richard Smith3003e1d2012-05-15 04:39:51 +00005267 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00005268 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00005269 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00005270 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00005271 // C++11 [dcl.fct.def.default]p4:
5272 // [For a] user-provided explicitly-defaulted function [...] if such a
5273 // function is implicitly defined as deleted, the program is ill-formed.
5274 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
Stephen Hines651f13c2014-04-23 16:59:28 -07005275 ShouldDeleteSpecialMember(MD, CSM, /*Diagnose*/true);
Richard Smith3003e1d2012-05-15 04:39:51 +00005276 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00005277 }
5278 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00005279
Richard Smith3003e1d2012-05-15 04:39:51 +00005280 if (HadError)
5281 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00005282}
5283
Richard Smith1d28caf2012-12-11 01:14:52 +00005284/// Check whether the exception specification provided for an
5285/// explicitly-defaulted special member matches the exception specification
5286/// that would have been generated for an implicit special member, per
5287/// C++11 [dcl.fct.def.default]p2.
5288void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
5289 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
Stephen Hines176edba2014-12-01 14:53:08 -08005290 // If the exception specification was explicitly specified but hadn't been
5291 // parsed when the method was defaulted, grab it now.
5292 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
5293 SpecifiedType =
5294 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
5295
Richard Smith1d28caf2012-12-11 01:14:52 +00005296 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00005297 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
5298 /*IsCXXMethod=*/true);
5299 FunctionProtoType::ExtProtoInfo EPI(CC);
Stephen Hines176edba2014-12-01 14:53:08 -08005300 EPI.ExceptionSpec = computeImplicitExceptionSpec(*this, MD->getLocation(), MD)
5301 .getExceptionSpec();
Richard Smith1d28caf2012-12-11 01:14:52 +00005302 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00005303 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00005304
5305 // Ensure that it matches.
5306 CheckEquivalentExceptionSpec(
5307 PDiag(diag::err_incorrect_defaulted_exception_spec)
5308 << getSpecialMember(MD), PDiag(),
5309 ImplicitType, SourceLocation(),
5310 SpecifiedType, MD->getLocation());
5311}
5312
Alp Toker08235662013-10-18 05:54:19 +00005313void Sema::CheckDelayedMemberExceptionSpecs() {
5314 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
5315 2> Checks;
5316 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smith1d28caf2012-12-11 01:14:52 +00005317
Alp Toker08235662013-10-18 05:54:19 +00005318 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
5319 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
5320
5321 // Perform any deferred checking of exception specifications for virtual
5322 // destructors.
5323 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
5324 const CXXDestructorDecl *Dtor = Checks[i].first;
5325 assert(!Dtor->getParent()->isDependentType() &&
5326 "Should not ever add destructors of templates into the list.");
5327 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
5328 }
5329
5330 // Check that any explicitly-defaulted methods have exception specifications
5331 // compatible with their implicit exception specifications.
5332 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
5333 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
5334 Specs[I].second);
Richard Smith1d28caf2012-12-11 01:14:52 +00005335}
5336
Richard Smith7d5088a2012-02-18 02:02:13 +00005337namespace {
5338struct SpecialMemberDeletionInfo {
5339 Sema &S;
5340 CXXMethodDecl *MD;
5341 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005342 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00005343
5344 // Properties of the special member, computed for convenience.
Stephen Hines651f13c2014-04-23 16:59:28 -07005345 bool IsConstructor, IsAssignment, IsMove, ConstArg;
Richard Smith7d5088a2012-02-18 02:02:13 +00005346 SourceLocation Loc;
5347
5348 bool AllFieldsAreConst;
5349
5350 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005351 Sema::CXXSpecialMember CSM, bool Diagnose)
5352 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00005353 IsConstructor(false), IsAssignment(false), IsMove(false),
Stephen Hines651f13c2014-04-23 16:59:28 -07005354 ConstArg(false), Loc(MD->getLocation()),
Richard Smith7d5088a2012-02-18 02:02:13 +00005355 AllFieldsAreConst(true) {
5356 switch (CSM) {
5357 case Sema::CXXDefaultConstructor:
5358 case Sema::CXXCopyConstructor:
5359 IsConstructor = true;
5360 break;
5361 case Sema::CXXMoveConstructor:
5362 IsConstructor = true;
5363 IsMove = true;
5364 break;
5365 case Sema::CXXCopyAssignment:
5366 IsAssignment = true;
5367 break;
5368 case Sema::CXXMoveAssignment:
5369 IsAssignment = true;
5370 IsMove = true;
5371 break;
5372 case Sema::CXXDestructor:
5373 break;
5374 case Sema::CXXInvalid:
5375 llvm_unreachable("invalid special member kind");
5376 }
5377
5378 if (MD->getNumParams()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005379 if (const ReferenceType *RT =
5380 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
5381 ConstArg = RT->getPointeeType().isConstQualified();
Richard Smith7d5088a2012-02-18 02:02:13 +00005382 }
5383 }
5384
5385 bool inUnion() const { return MD->getParent()->isUnion(); }
5386
5387 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00005388 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
Stephen Hines651f13c2014-04-23 16:59:28 -07005389 unsigned Quals, bool IsMutable) {
5390 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
5391 ConstArg && !IsMutable);
Richard Smith7d5088a2012-02-18 02:02:13 +00005392 }
5393
Richard Smith6c4c36c2012-03-30 20:53:28 +00005394 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00005395
Richard Smith6c4c36c2012-03-30 20:53:28 +00005396 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00005397 bool shouldDeleteForField(FieldDecl *FD);
5398 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00005399
Richard Smith517bb842012-07-18 03:51:16 +00005400 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
5401 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005402 bool shouldDeleteForSubobjectCall(Subobject Subobj,
5403 Sema::SpecialMemberOverloadResult *SMOR,
5404 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00005405
5406 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00005407};
5408}
5409
John McCall12d8d802012-04-09 20:53:23 +00005410/// Is the given special member inaccessible when used on the given
5411/// sub-object.
5412bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
5413 CXXMethodDecl *target) {
5414 /// If we're operating on a base class, the object type is the
5415 /// type of this special member.
5416 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005417 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00005418 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
5419 objectTy = S.Context.getTypeDeclType(MD->getParent());
5420 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
5421
5422 // If we're operating on a field, the object type is the type of the field.
5423 } else {
5424 objectTy = S.Context.getTypeDeclType(target->getParent());
5425 }
5426
5427 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
5428}
5429
Richard Smith6c4c36c2012-03-30 20:53:28 +00005430/// Check whether we should delete a special member due to the implicit
5431/// definition containing a call to a special member of a subobject.
5432bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
5433 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
5434 bool IsDtorCallInCtor) {
5435 CXXMethodDecl *Decl = SMOR->getMethod();
5436 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5437
5438 int DiagKind = -1;
5439
5440 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
5441 DiagKind = !Decl ? 0 : 1;
5442 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5443 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00005444 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00005445 DiagKind = 3;
5446 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
5447 !Decl->isTrivial()) {
5448 // A member of a union must have a trivial corresponding special member.
5449 // As a weird special case, a destructor call from a union's constructor
5450 // must be accessible and non-deleted, but need not be trivial. Such a
5451 // destructor is never actually called, but is semantically checked as
5452 // if it were.
5453 DiagKind = 4;
5454 }
5455
5456 if (DiagKind == -1)
5457 return false;
5458
5459 if (Diagnose) {
5460 if (Field) {
5461 S.Diag(Field->getLocation(),
5462 diag::note_deleted_special_member_class_subobject)
5463 << CSM << MD->getParent() << /*IsField*/true
5464 << Field << DiagKind << IsDtorCallInCtor;
5465 } else {
5466 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5467 S.Diag(Base->getLocStart(),
5468 diag::note_deleted_special_member_class_subobject)
5469 << CSM << MD->getParent() << /*IsField*/false
5470 << Base->getType() << DiagKind << IsDtorCallInCtor;
5471 }
5472
5473 if (DiagKind == 1)
5474 S.NoteDeletedFunction(Decl);
5475 // FIXME: Explain inaccessibility if DiagKind == 3.
5476 }
5477
5478 return true;
5479}
5480
Richard Smith9a561d52012-02-26 09:11:52 +00005481/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00005482/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00005483bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00005484 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005485 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Stephen Hines651f13c2014-04-23 16:59:28 -07005486 bool IsMutable = Field && Field->isMutable();
Richard Smith7d5088a2012-02-18 02:02:13 +00005487
5488 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00005489 // -- any direct or virtual base class, or non-static data member with no
5490 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00005491 // either M has no default constructor or overload resolution as applied
5492 // to M's default constructor results in an ambiguity or in a function
5493 // that is deleted or inaccessible
5494 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5495 // -- a direct or virtual base class B that cannot be copied/moved because
5496 // overload resolution, as applied to B's corresponding special member,
5497 // results in an ambiguity or a function that is deleted or inaccessible
5498 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00005499 // C++11 [class.dtor]p5:
5500 // -- any direct or virtual base class [...] has a type with a destructor
5501 // that is deleted or inaccessible
5502 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00005503 Field && Field->hasInClassInitializer()) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005504 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
5505 false))
Richard Smith1c931be2012-04-02 18:40:40 +00005506 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005507
Richard Smith6c4c36c2012-03-30 20:53:28 +00005508 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5509 // -- any direct or virtual base class or non-static data member has a
5510 // type with a destructor that is deleted or inaccessible
5511 if (IsConstructor) {
5512 Sema::SpecialMemberOverloadResult *SMOR =
5513 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5514 false, false, false, false, false);
5515 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5516 return true;
5517 }
5518
Richard Smith9a561d52012-02-26 09:11:52 +00005519 return false;
5520}
5521
5522/// Check whether we should delete a special member function due to the class
5523/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005524bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00005525 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00005526 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00005527}
5528
5529/// Check whether we should delete a special member function due to the class
5530/// having a particular non-static data member.
5531bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5532 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5533 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5534
5535 if (CSM == Sema::CXXDefaultConstructor) {
5536 // For a default constructor, all references must be initialized in-class
5537 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005538 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5539 if (Diagnose)
5540 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5541 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005542 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005543 }
Richard Smith79363f52012-02-27 06:07:25 +00005544 // C++11 [class.ctor]p5: any non-variant non-static data member of
5545 // const-qualified type (or array thereof) with no
5546 // brace-or-equal-initializer does not have a user-provided default
5547 // constructor.
5548 if (!inUnion() && FieldType.isConstQualified() &&
5549 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005550 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5551 if (Diagnose)
5552 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005553 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00005554 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005555 }
5556
5557 if (inUnion() && !FieldType.isConstQualified())
5558 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005559 } else if (CSM == Sema::CXXCopyConstructor) {
5560 // For a copy constructor, data members must not be of rvalue reference
5561 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005562 if (FieldType->isRValueReferenceType()) {
5563 if (Diagnose)
5564 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5565 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00005566 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005567 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005568 } else if (IsAssignment) {
5569 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005570 if (FieldType->isReferenceType()) {
5571 if (Diagnose)
5572 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5573 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005574 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005575 }
5576 if (!FieldRecord && FieldType.isConstQualified()) {
5577 // C++11 [class.copy]p23:
5578 // -- a non-static data member of const non-class type (or array thereof)
5579 if (Diagnose)
5580 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005581 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005582 return true;
5583 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005584 }
5585
5586 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005587 // Some additional restrictions exist on the variant members.
5588 if (!inUnion() && FieldRecord->isUnion() &&
5589 FieldRecord->isAnonymousStructOrUnion()) {
5590 bool AllVariantFieldsAreConst = true;
5591
Richard Smithdf8dc862012-03-29 19:00:10 +00005592 // FIXME: Handle anonymous unions declared within anonymous unions.
Stephen Hines651f13c2014-04-23 16:59:28 -07005593 for (auto *UI : FieldRecord->fields()) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005594 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00005595
5596 if (!UnionFieldType.isConstQualified())
5597 AllVariantFieldsAreConst = false;
5598
Richard Smith9a561d52012-02-26 09:11:52 +00005599 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5600 if (UnionFieldRecord &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005601 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
Richard Smith517bb842012-07-18 03:51:16 +00005602 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00005603 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005604 }
5605
5606 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00005607 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005608 !FieldRecord->field_empty()) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005609 if (Diagnose)
5610 S.Diag(FieldRecord->getLocation(),
5611 diag::note_deleted_default_ctor_all_const)
5612 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00005613 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005614 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005615
Richard Smithdf8dc862012-03-29 19:00:10 +00005616 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00005617 // This is technically non-conformant, but sanity demands it.
5618 return false;
5619 }
5620
Richard Smith517bb842012-07-18 03:51:16 +00005621 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5622 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00005623 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005624 }
5625
5626 return false;
5627}
5628
5629/// C++11 [class.ctor] p5:
5630/// A defaulted default constructor for a class X is defined as deleted if
5631/// X is a union and all of its variant members are of const-qualified type.
5632bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00005633 // This is a silly definition, because it gives an empty union a deleted
5634 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005635 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005636 !MD->getParent()->field_empty()) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005637 if (Diagnose)
5638 S.Diag(MD->getParent()->getLocation(),
5639 diag::note_deleted_default_ctor_all_const)
5640 << MD->getParent() << /*not anonymous union*/0;
5641 return true;
5642 }
5643 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005644}
5645
5646/// Determine whether a defaulted special member function should be defined as
5647/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5648/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005649bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5650 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00005651 if (MD->isInvalidDecl())
5652 return false;
Sean Hunte16da072011-10-10 06:18:57 +00005653 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00005654 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00005655 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005656 return false;
5657
Richard Smith7d5088a2012-02-18 02:02:13 +00005658 // C++11 [expr.lambda.prim]p19:
5659 // The closure type associated with a lambda-expression has a
5660 // deleted (8.4.3) default constructor and a deleted copy
5661 // assignment operator.
5662 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005663 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5664 if (Diagnose)
5665 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005666 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005667 }
5668
Richard Smith5bdaac52012-04-02 20:59:25 +00005669 // For an anonymous struct or union, the copy and assignment special members
5670 // will never be used, so skip the check. For an anonymous union declared at
5671 // namespace scope, the constructor and destructor are used.
5672 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5673 RD->isAnonymousStructOrUnion())
5674 return false;
5675
Richard Smith6c4c36c2012-03-30 20:53:28 +00005676 // C++11 [class.copy]p7, p18:
5677 // If the class definition declares a move constructor or move assignment
5678 // operator, an implicitly declared copy constructor or copy assignment
5679 // operator is defined as deleted.
5680 if (MD->isImplicit() &&
5681 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005682 CXXMethodDecl *UserDeclaredMove = nullptr;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005683
5684 // In Microsoft mode, a user-declared move only causes the deletion of the
5685 // corresponding copy operation, not both copy operations.
5686 if (RD->hasUserDeclaredMoveConstructor() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005687 (!getLangOpts().MSVCCompat || CSM == CXXCopyConstructor)) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005688 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005689
5690 // Find any user-declared move constructor.
Stephen Hines651f13c2014-04-23 16:59:28 -07005691 for (auto *I : RD->ctors()) {
Richard Smith55798652012-12-08 04:10:18 +00005692 if (I->isMoveConstructor()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005693 UserDeclaredMove = I;
Richard Smith55798652012-12-08 04:10:18 +00005694 break;
5695 }
5696 }
Richard Smith1c931be2012-04-02 18:40:40 +00005697 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005698 } else if (RD->hasUserDeclaredMoveAssignment() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005699 (!getLangOpts().MSVCCompat || CSM == CXXCopyAssignment)) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005700 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005701
5702 // Find any user-declared move assignment operator.
Stephen Hines651f13c2014-04-23 16:59:28 -07005703 for (auto *I : RD->methods()) {
Richard Smith55798652012-12-08 04:10:18 +00005704 if (I->isMoveAssignmentOperator()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005705 UserDeclaredMove = I;
Richard Smith55798652012-12-08 04:10:18 +00005706 break;
5707 }
5708 }
Richard Smith1c931be2012-04-02 18:40:40 +00005709 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005710 }
5711
5712 if (UserDeclaredMove) {
5713 Diag(UserDeclaredMove->getLocation(),
5714 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005715 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005716 << UserDeclaredMove->isMoveAssignmentOperator();
5717 return true;
5718 }
5719 }
Sean Hunte16da072011-10-10 06:18:57 +00005720
Richard Smith5bdaac52012-04-02 20:59:25 +00005721 // Do access control from the special member function
5722 ContextRAII MethodContext(*this, MD);
5723
Richard Smith9a561d52012-02-26 09:11:52 +00005724 // C++11 [class.dtor]p5:
5725 // -- for a virtual destructor, lookup of the non-array deallocation function
5726 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005727 if (CSM == CXXDestructor && MD->isVirtual()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005728 FunctionDecl *OperatorDelete = nullptr;
Richard Smith9a561d52012-02-26 09:11:52 +00005729 DeclarationName Name =
5730 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5731 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005732 OperatorDelete, false)) {
5733 if (Diagnose)
5734 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005735 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005736 }
Richard Smith9a561d52012-02-26 09:11:52 +00005737 }
5738
Richard Smith6c4c36c2012-03-30 20:53:28 +00005739 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005740
Stephen Hines651f13c2014-04-23 16:59:28 -07005741 for (auto &BI : RD->bases())
5742 if (!BI.isVirtual() &&
5743 SMI.shouldDeleteForBase(&BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005744 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005745
Richard Smithe0883602013-07-22 18:06:23 +00005746 // Per DR1611, do not consider virtual bases of constructors of abstract
5747 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005748 if (!RD->isAbstract() || !SMI.IsConstructor) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005749 for (auto &BI : RD->vbases())
5750 if (SMI.shouldDeleteForBase(&BI))
Richard Smithcbc820a2013-07-22 02:56:56 +00005751 return true;
5752 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005753
Stephen Hines651f13c2014-04-23 16:59:28 -07005754 for (auto *FI : RD->fields())
Richard Smith7d5088a2012-02-18 02:02:13 +00005755 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07005756 SMI.shouldDeleteForField(FI))
Sean Hunte3406822011-05-20 21:43:47 +00005757 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005758
Richard Smith7d5088a2012-02-18 02:02:13 +00005759 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005760 return true;
5761
Stephen Hines176edba2014-12-01 14:53:08 -08005762 if (getLangOpts().CUDA) {
5763 // We should delete the special member in CUDA mode if target inference
5764 // failed.
5765 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
5766 Diagnose);
5767 }
5768
Sean Huntcdee3fe2011-05-11 22:34:38 +00005769 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005770}
5771
Richard Smithac713512012-12-08 02:53:02 +00005772/// Perform lookup for a special member of the specified kind, and determine
5773/// whether it is trivial. If the triviality can be determined without the
5774/// lookup, skip it. This is intended for use when determining whether a
5775/// special member of a containing object is trivial, and thus does not ever
5776/// perform overload resolution for default constructors.
5777///
5778/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5779/// member that was most likely to be intended to be trivial, if any.
5780static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5781 Sema::CXXSpecialMember CSM, unsigned Quals,
Stephen Hines651f13c2014-04-23 16:59:28 -07005782 bool ConstRHS, CXXMethodDecl **Selected) {
Richard Smithac713512012-12-08 02:53:02 +00005783 if (Selected)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005784 *Selected = nullptr;
Richard Smithac713512012-12-08 02:53:02 +00005785
5786 switch (CSM) {
5787 case Sema::CXXInvalid:
5788 llvm_unreachable("not a special member");
5789
5790 case Sema::CXXDefaultConstructor:
5791 // C++11 [class.ctor]p5:
5792 // A default constructor is trivial if:
5793 // - all the [direct subobjects] have trivial default constructors
5794 //
5795 // Note, no overload resolution is performed in this case.
5796 if (RD->hasTrivialDefaultConstructor())
5797 return true;
5798
5799 if (Selected) {
5800 // If there's a default constructor which could have been trivial, dig it
5801 // out. Otherwise, if there's any user-provided default constructor, point
5802 // to that as an example of why there's not a trivial one.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005803 CXXConstructorDecl *DefCtor = nullptr;
Richard Smithac713512012-12-08 02:53:02 +00005804 if (RD->needsImplicitDefaultConstructor())
5805 S.DeclareImplicitDefaultConstructor(RD);
Stephen Hines651f13c2014-04-23 16:59:28 -07005806 for (auto *CI : RD->ctors()) {
Richard Smithac713512012-12-08 02:53:02 +00005807 if (!CI->isDefaultConstructor())
5808 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07005809 DefCtor = CI;
Richard Smithac713512012-12-08 02:53:02 +00005810 if (!DefCtor->isUserProvided())
5811 break;
5812 }
5813
5814 *Selected = DefCtor;
5815 }
5816
5817 return false;
5818
5819 case Sema::CXXDestructor:
5820 // C++11 [class.dtor]p5:
5821 // A destructor is trivial if:
5822 // - all the direct [subobjects] have trivial destructors
5823 if (RD->hasTrivialDestructor())
5824 return true;
5825
5826 if (Selected) {
5827 if (RD->needsImplicitDestructor())
5828 S.DeclareImplicitDestructor(RD);
5829 *Selected = RD->getDestructor();
5830 }
5831
5832 return false;
5833
5834 case Sema::CXXCopyConstructor:
5835 // C++11 [class.copy]p12:
5836 // A copy constructor is trivial if:
5837 // - the constructor selected to copy each direct [subobject] is trivial
5838 if (RD->hasTrivialCopyConstructor()) {
5839 if (Quals == Qualifiers::Const)
5840 // We must either select the trivial copy constructor or reach an
5841 // ambiguity; no need to actually perform overload resolution.
5842 return true;
5843 } else if (!Selected) {
5844 return false;
5845 }
5846 // In C++98, we are not supposed to perform overload resolution here, but we
5847 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5848 // cases like B as having a non-trivial copy constructor:
5849 // struct A { template<typename T> A(T&); };
5850 // struct B { mutable A a; };
5851 goto NeedOverloadResolution;
5852
5853 case Sema::CXXCopyAssignment:
5854 // C++11 [class.copy]p25:
5855 // A copy assignment operator is trivial if:
5856 // - the assignment operator selected to copy each direct [subobject] is
5857 // trivial
5858 if (RD->hasTrivialCopyAssignment()) {
5859 if (Quals == Qualifiers::Const)
5860 return true;
5861 } else if (!Selected) {
5862 return false;
5863 }
5864 // In C++98, we are not supposed to perform overload resolution here, but we
5865 // treat that as a language defect.
5866 goto NeedOverloadResolution;
5867
5868 case Sema::CXXMoveConstructor:
5869 case Sema::CXXMoveAssignment:
5870 NeedOverloadResolution:
5871 Sema::SpecialMemberOverloadResult *SMOR =
Stephen Hines651f13c2014-04-23 16:59:28 -07005872 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
Richard Smithac713512012-12-08 02:53:02 +00005873
5874 // The standard doesn't describe how to behave if the lookup is ambiguous.
5875 // We treat it as not making the member non-trivial, just like the standard
5876 // mandates for the default constructor. This should rarely matter, because
5877 // the member will also be deleted.
5878 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5879 return true;
5880
5881 if (!SMOR->getMethod()) {
5882 assert(SMOR->getKind() ==
5883 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5884 return false;
5885 }
5886
5887 // We deliberately don't check if we found a deleted special member. We're
5888 // not supposed to!
5889 if (Selected)
5890 *Selected = SMOR->getMethod();
5891 return SMOR->getMethod()->isTrivial();
5892 }
5893
5894 llvm_unreachable("unknown special method kind");
5895}
5896
Benjamin Kramera574c892013-02-15 12:30:38 +00005897static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005898 for (auto *CI : RD->ctors())
Richard Smithac713512012-12-08 02:53:02 +00005899 if (!CI->isImplicit())
Stephen Hines651f13c2014-04-23 16:59:28 -07005900 return CI;
Richard Smithac713512012-12-08 02:53:02 +00005901
5902 // Look for constructor templates.
5903 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5904 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5905 if (CXXConstructorDecl *CD =
5906 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5907 return CD;
5908 }
5909
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005910 return nullptr;
Richard Smithac713512012-12-08 02:53:02 +00005911}
5912
5913/// The kind of subobject we are checking for triviality. The values of this
5914/// enumeration are used in diagnostics.
5915enum TrivialSubobjectKind {
5916 /// The subobject is a base class.
5917 TSK_BaseClass,
5918 /// The subobject is a non-static data member.
5919 TSK_Field,
5920 /// The object is actually the complete object.
5921 TSK_CompleteObject
5922};
5923
5924/// Check whether the special member selected for a given type would be trivial.
5925static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -07005926 QualType SubType, bool ConstRHS,
Richard Smithac713512012-12-08 02:53:02 +00005927 Sema::CXXSpecialMember CSM,
5928 TrivialSubobjectKind Kind,
5929 bool Diagnose) {
5930 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5931 if (!SubRD)
5932 return true;
5933
5934 CXXMethodDecl *Selected;
5935 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005936 ConstRHS, Diagnose ? &Selected : nullptr))
Richard Smithac713512012-12-08 02:53:02 +00005937 return true;
5938
5939 if (Diagnose) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005940 if (ConstRHS)
5941 SubType.addConst();
5942
Richard Smithac713512012-12-08 02:53:02 +00005943 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5944 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5945 << Kind << SubType.getUnqualifiedType();
5946 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5947 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5948 } else if (!Selected)
5949 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5950 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5951 else if (Selected->isUserProvided()) {
5952 if (Kind == TSK_CompleteObject)
5953 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5954 << Kind << SubType.getUnqualifiedType() << CSM;
5955 else {
5956 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5957 << Kind << SubType.getUnqualifiedType() << CSM;
5958 S.Diag(Selected->getLocation(), diag::note_declared_at);
5959 }
5960 } else {
5961 if (Kind != TSK_CompleteObject)
5962 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5963 << Kind << SubType.getUnqualifiedType() << CSM;
5964
5965 // Explain why the defaulted or deleted special member isn't trivial.
5966 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5967 }
5968 }
5969
5970 return false;
5971}
5972
5973/// Check whether the members of a class type allow a special member to be
5974/// trivial.
5975static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5976 Sema::CXXSpecialMember CSM,
5977 bool ConstArg, bool Diagnose) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005978 for (const auto *FI : RD->fields()) {
Richard Smithac713512012-12-08 02:53:02 +00005979 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5980 continue;
5981
5982 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5983
5984 // Pretend anonymous struct or union members are members of this class.
5985 if (FI->isAnonymousStructOrUnion()) {
5986 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5987 CSM, ConstArg, Diagnose))
5988 return false;
5989 continue;
5990 }
5991
5992 // C++11 [class.ctor]p5:
5993 // A default constructor is trivial if [...]
5994 // -- no non-static data member of its class has a
5995 // brace-or-equal-initializer
5996 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5997 if (Diagnose)
Stephen Hines651f13c2014-04-23 16:59:28 -07005998 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
Richard Smithac713512012-12-08 02:53:02 +00005999 return false;
6000 }
6001
6002 // Objective C ARC 4.3.5:
6003 // [...] nontrivally ownership-qualified types are [...] not trivially
6004 // default constructible, copy constructible, move constructible, copy
6005 // assignable, move assignable, or destructible [...]
6006 if (S.getLangOpts().ObjCAutoRefCount &&
6007 FieldType.hasNonTrivialObjCLifetime()) {
6008 if (Diagnose)
6009 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
6010 << RD << FieldType.getObjCLifetime();
6011 return false;
6012 }
6013
Stephen Hines651f13c2014-04-23 16:59:28 -07006014 bool ConstRHS = ConstArg && !FI->isMutable();
6015 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
6016 CSM, TSK_Field, Diagnose))
Richard Smithac713512012-12-08 02:53:02 +00006017 return false;
6018 }
6019
6020 return true;
6021}
6022
6023/// Diagnose why the specified class does not have a trivial special member of
6024/// the given kind.
6025void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
6026 QualType Ty = Context.getRecordType(RD);
Richard Smithac713512012-12-08 02:53:02 +00006027
Stephen Hines651f13c2014-04-23 16:59:28 -07006028 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
6029 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
Richard Smithac713512012-12-08 02:53:02 +00006030 TSK_CompleteObject, /*Diagnose*/true);
6031}
6032
6033/// Determine whether a defaulted or deleted special member function is trivial,
6034/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
6035/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
6036bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
6037 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00006038 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
6039
6040 CXXRecordDecl *RD = MD->getParent();
6041
6042 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00006043
Richard Smitha8d478e2013-11-04 02:02:27 +00006044 // C++11 [class.copy]p12, p25: [DR1593]
6045 // A [special member] is trivial if [...] its parameter-type-list is
6046 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smithac713512012-12-08 02:53:02 +00006047 switch (CSM) {
6048 case CXXDefaultConstructor:
6049 case CXXDestructor:
6050 // Trivial default constructors and destructors cannot have parameters.
6051 break;
6052
6053 case CXXCopyConstructor:
6054 case CXXCopyAssignment: {
6055 // Trivial copy operations always have const, non-volatile parameter types.
6056 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00006057 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00006058 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
6059 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
6060 if (Diagnose)
6061 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6062 << Param0->getSourceRange() << Param0->getType()
6063 << Context.getLValueReferenceType(
6064 Context.getRecordType(RD).withConst());
6065 return false;
6066 }
6067 break;
6068 }
6069
6070 case CXXMoveConstructor:
6071 case CXXMoveAssignment: {
6072 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00006073 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00006074 const RValueReferenceType *RT =
6075 Param0->getType()->getAs<RValueReferenceType>();
6076 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
6077 if (Diagnose)
6078 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
6079 << Param0->getSourceRange() << Param0->getType()
6080 << Context.getRValueReferenceType(Context.getRecordType(RD));
6081 return false;
6082 }
6083 break;
6084 }
6085
6086 case CXXInvalid:
6087 llvm_unreachable("not a special member");
6088 }
6089
Richard Smithac713512012-12-08 02:53:02 +00006090 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
6091 if (Diagnose)
6092 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
6093 diag::note_nontrivial_default_arg)
6094 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
6095 return false;
6096 }
6097 if (MD->isVariadic()) {
6098 if (Diagnose)
6099 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
6100 return false;
6101 }
6102
6103 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6104 // A copy/move [constructor or assignment operator] is trivial if
6105 // -- the [member] selected to copy/move each direct base class subobject
6106 // is trivial
6107 //
6108 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6109 // A [default constructor or destructor] is trivial if
6110 // -- all the direct base classes have trivial [default constructors or
6111 // destructors]
Stephen Hines651f13c2014-04-23 16:59:28 -07006112 for (const auto &BI : RD->bases())
6113 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
6114 ConstArg, CSM, TSK_BaseClass, Diagnose))
Richard Smithac713512012-12-08 02:53:02 +00006115 return false;
6116
6117 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
6118 // A copy/move [constructor or assignment operator] for a class X is
6119 // trivial if
6120 // -- for each non-static data member of X that is of class type (or array
6121 // thereof), the constructor selected to copy/move that member is
6122 // trivial
6123 //
6124 // C++11 [class.copy]p12, C++11 [class.copy]p25:
6125 // A [default constructor or destructor] is trivial if
6126 // -- for all of the non-static data members of its class that are of class
6127 // type (or array thereof), each such class has a trivial [default
6128 // constructor or destructor]
6129 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
6130 return false;
6131
6132 // C++11 [class.dtor]p5:
6133 // A destructor is trivial if [...]
6134 // -- the destructor is not virtual
6135 if (CSM == CXXDestructor && MD->isVirtual()) {
6136 if (Diagnose)
6137 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
6138 return false;
6139 }
6140
6141 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
6142 // A [special member] for class X is trivial if [...]
6143 // -- class X has no virtual functions and no virtual base classes
6144 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
6145 if (!Diagnose)
6146 return false;
6147
6148 if (RD->getNumVBases()) {
6149 // Check for virtual bases. We already know that the corresponding
6150 // member in all bases is trivial, so vbases must all be direct.
6151 CXXBaseSpecifier &BS = *RD->vbases_begin();
6152 assert(BS.isVirtual());
6153 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
6154 return false;
6155 }
6156
6157 // Must have a virtual method.
Stephen Hines651f13c2014-04-23 16:59:28 -07006158 for (const auto *MI : RD->methods()) {
Richard Smithac713512012-12-08 02:53:02 +00006159 if (MI->isVirtual()) {
6160 SourceLocation MLoc = MI->getLocStart();
6161 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
6162 return false;
6163 }
6164 }
6165
6166 llvm_unreachable("dynamic class with no vbases and no virtual functions");
6167 }
6168
6169 // Looks like it's trivial!
6170 return true;
6171}
6172
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006173/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00006174namespace {
6175 struct FindHiddenVirtualMethodData {
6176 Sema *S;
6177 CXXMethodDecl *Method;
6178 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006179 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00006180 };
6181}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006182
David Blaikie5f750682012-10-19 00:53:08 +00006183/// \brief Check whether any most overriden method from MD in Methods
6184static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
Stephen Hines176edba2014-12-01 14:53:08 -08006185 const llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie5f750682012-10-19 00:53:08 +00006186 if (MD->size_overridden_methods() == 0)
6187 return Methods.count(MD->getCanonicalDecl());
6188 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6189 E = MD->end_overridden_methods();
6190 I != E; ++I)
6191 if (CheckMostOverridenMethods(*I, Methods))
6192 return true;
6193 return false;
6194}
6195
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006196/// \brief Member lookup function that determines whether a given C++
6197/// method overloads virtual methods in a base class without overriding any,
6198/// to be used with CXXRecordDecl::lookupInBases().
6199static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
6200 CXXBasePath &Path,
6201 void *UserData) {
6202 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
6203
6204 FindHiddenVirtualMethodData &Data
6205 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
6206
6207 DeclarationName Name = Data.Method->getDeclName();
6208 assert(Name.getNameKind() == DeclarationName::Identifier);
6209
6210 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006211 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006212 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00006213 !Path.Decls.empty();
6214 Path.Decls = Path.Decls.slice(1)) {
6215 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006216 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00006217 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006218 foundSameNameMethod = true;
6219 // Interested only in hidden virtual methods.
6220 if (!MD->isVirtual())
6221 continue;
6222 // If the method we are checking overrides a method from its base
Stephen Hines176edba2014-12-01 14:53:08 -08006223 // don't warn about the other overloaded methods. Clang deviates from GCC
6224 // by only diagnosing overloads of inherited virtual functions that do not
6225 // override any other virtual functions in the base. GCC's
6226 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
6227 // function from a base class. These cases may be better served by a
6228 // warning (not specific to virtual functions) on call sites when the call
6229 // would select a different function from the base class, were it visible.
6230 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006231 if (!Data.S->IsOverload(Data.Method, MD, false))
6232 return true;
6233 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00006234 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006235 overloadedMethods.push_back(MD);
6236 }
6237 }
6238
6239 if (foundSameNameMethod)
6240 Data.OverloadedMethods.append(overloadedMethods.begin(),
6241 overloadedMethods.end());
6242 return foundSameNameMethod;
6243}
6244
David Blaikie5f750682012-10-19 00:53:08 +00006245/// \brief Add the most overriden methods from MD to Methods
6246static void AddMostOverridenMethods(const CXXMethodDecl *MD,
Stephen Hines176edba2014-12-01 14:53:08 -08006247 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
David Blaikie5f750682012-10-19 00:53:08 +00006248 if (MD->size_overridden_methods() == 0)
6249 Methods.insert(MD->getCanonicalDecl());
6250 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6251 E = MD->end_overridden_methods();
6252 I != E; ++I)
6253 AddMostOverridenMethods(*I, Methods);
6254}
6255
Eli Friedmandae92712013-09-05 23:51:03 +00006256/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006257/// overriding any.
Eli Friedmandae92712013-09-05 23:51:03 +00006258void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
6259 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramerc4704422012-05-19 16:03:58 +00006260 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006261 return;
6262
6263 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
6264 /*bool RecordPaths=*/false,
6265 /*bool DetectVirtual=*/false);
6266 FindHiddenVirtualMethodData Data;
6267 Data.Method = MD;
6268 Data.S = this;
6269
6270 // Keep the base methods that were overriden or introduced in the subclass
6271 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmandae92712013-09-05 23:51:03 +00006272 CXXRecordDecl *DC = MD->getParent();
David Blaikie3bc93e32012-12-19 00:45:41 +00006273 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
6274 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
6275 NamedDecl *ND = *I;
6276 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00006277 ND = shad->getTargetDecl();
6278 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6279 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006280 }
6281
Eli Friedmandae92712013-09-05 23:51:03 +00006282 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
6283 OverloadedMethods = Data.OverloadedMethods;
6284}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006285
Eli Friedmandae92712013-09-05 23:51:03 +00006286void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
6287 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
6288 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
6289 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
6290 PartialDiagnostic PD = PDiag(
6291 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
6292 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
6293 Diag(overloadedMD->getLocation(), PD);
6294 }
6295}
6296
6297/// \brief Diagnose methods which overload virtual methods in a base class
6298/// without overriding any.
6299void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
6300 if (MD->isInvalidDecl())
6301 return;
6302
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006303 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
Eli Friedmandae92712013-09-05 23:51:03 +00006304 return;
6305
6306 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
6307 FindHiddenVirtualMethods(MD, OverloadedMethods);
6308 if (!OverloadedMethods.empty()) {
6309 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
6310 << MD << (OverloadedMethods.size() > 1);
6311
6312 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00006313 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00006314}
6315
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00006316void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00006317 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00006318 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00006319 SourceLocation RBrac,
6320 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006321 if (!TagDecl)
6322 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006323
Douglas Gregor42af25f2009-05-11 19:58:34 +00006324 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00006325
Rafael Espindolaf729ce02012-07-12 04:32:30 +00006326 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
6327 if (l->getKind() != AttributeList::AT_Visibility)
6328 continue;
6329 l->setInvalid();
6330 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
6331 l->getName();
6332 }
6333
David Blaikie77b6de02011-09-22 02:58:26 +00006334 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00006335 // strict aliasing violation!
6336 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00006337 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00006338
Douglas Gregor23c94db2010-07-02 17:43:08 +00006339 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00006340 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00006341}
6342
Douglas Gregor396b7cd2008-11-03 17:51:48 +00006343/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
6344/// special functions, such as the default constructor, copy
6345/// constructor, or destructor, to the given C++ class (C++
6346/// [special]p1). This routine can only be executed just before the
6347/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00006348void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00006349 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00006350 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00006351
Richard Smithbc2a35d2012-12-08 08:32:28 +00006352 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00006353 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00006354
Richard Smithbc2a35d2012-12-08 08:32:28 +00006355 // If the properties or semantics of the copy constructor couldn't be
6356 // determined while the class was being declared, force a declaration
6357 // of it now.
6358 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
6359 DeclareImplicitCopyConstructor(ClassDecl);
6360 }
6361
Richard Smith80ad52f2013-01-02 11:42:31 +00006362 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00006363 ++ASTContext::NumImplicitMoveConstructors;
6364
Richard Smithbc2a35d2012-12-08 08:32:28 +00006365 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
6366 DeclareImplicitMoveConstructor(ClassDecl);
6367 }
6368
Douglas Gregora376d102010-07-02 21:50:04 +00006369 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
6370 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00006371
6372 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00006373 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00006374 // it shows up in the right place in the vtable and that we diagnose
6375 // problems with the implicit exception specification.
6376 if (ClassDecl->isDynamicClass() ||
6377 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00006378 DeclareImplicitCopyAssignment(ClassDecl);
6379 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00006380
Richard Smith80ad52f2013-01-02 11:42:31 +00006381 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00006382 ++ASTContext::NumImplicitMoveAssignmentOperators;
6383
6384 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00006385 if (ClassDecl->isDynamicClass() ||
6386 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00006387 DeclareImplicitMoveAssignment(ClassDecl);
6388 }
6389
Douglas Gregor4923aa22010-07-02 20:37:36 +00006390 if (!ClassDecl->hasUserDeclaredDestructor()) {
6391 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00006392
6393 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00006394 // have to declare the destructor immediately. This ensures that, e.g., it
6395 // shows up in the right place in the vtable and that we diagnose problems
6396 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00006397 if (ClassDecl->isDynamicClass() ||
6398 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00006399 DeclareImplicitDestructor(ClassDecl);
6400 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00006401}
6402
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006403unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00006404 if (!D)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006405 return 0;
Francois Pichet8387e2a2011-04-22 22:18:13 +00006406
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006407 // The order of template parameters is not important here. All names
6408 // get added to the same scope.
6409 SmallVector<TemplateParameterList *, 4> ParameterLists;
6410
6411 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
6412 D = TD->getTemplatedDecl();
6413
6414 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
6415 ParameterLists.push_back(PSD->getTemplateParameters());
6416
6417 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
6418 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
6419 ParameterLists.push_back(DD->getTemplateParameterList(i));
6420
6421 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6422 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
6423 ParameterLists.push_back(FTD->getTemplateParameters());
6424 }
6425 }
6426
6427 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6428 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
6429 ParameterLists.push_back(TD->getTemplateParameterList(i));
6430
6431 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
6432 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
6433 ParameterLists.push_back(CTD->getTemplateParameters());
6434 }
6435 }
6436
6437 unsigned Count = 0;
6438 for (TemplateParameterList *Params : ParameterLists) {
6439 if (Params->size() > 0)
6440 // Ignore explicit specializations; they don't contribute to the template
6441 // depth.
6442 ++Count;
6443 for (NamedDecl *Param : *Params) {
6444 if (Param->getDeclName()) {
6445 S->AddDecl(Param);
6446 IdResolver.AddDecl(Param);
Francois Pichet8387e2a2011-04-22 22:18:13 +00006447 }
6448 }
6449 }
Francois Pichet8387e2a2011-04-22 22:18:13 +00006450
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006451 return Count;
Douglas Gregor6569d682009-05-27 23:11:45 +00006452}
6453
John McCalld226f652010-08-21 09:40:31 +00006454void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00006455 if (!RecordD) return;
6456 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00006457 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00006458 PushDeclContext(S, Record);
6459}
6460
John McCalld226f652010-08-21 09:40:31 +00006461void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00006462 if (!RecordD) return;
6463 PopDeclContext();
6464}
6465
Stephen Hines651f13c2014-04-23 16:59:28 -07006466/// This is used to implement the constant expression evaluation part of the
6467/// attribute enable_if extension. There is nothing in standard C++ which would
6468/// require reentering parameters.
6469void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
6470 if (!Param)
6471 return;
6472
6473 S->AddDecl(Param);
6474 if (Param->getDeclName())
6475 IdResolver.AddDecl(Param);
6476}
6477
Douglas Gregor72b505b2008-12-16 21:30:33 +00006478/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6479/// parsing a top-level (non-nested) C++ class, and we are now
6480/// parsing those parts of the given Method declaration that could
6481/// not be parsed earlier (C++ [class.mem]p2), such as default
6482/// arguments. This action should enter the scope of the given
6483/// Method declaration as if we had just parsed the qualified method
6484/// name. However, it should not bring the parameters into scope;
6485/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00006486void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006487}
6488
6489/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6490/// C++ method declaration. We're (re-)introducing the given
6491/// function parameter into scope for use in parsing later parts of
6492/// the method declaration. For example, we could see an
6493/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00006494void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006495 if (!ParamD)
6496 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006497
John McCalld226f652010-08-21 09:40:31 +00006498 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00006499
6500 // If this parameter has an unparsed default argument, clear it out
6501 // to make way for the parsed default argument.
6502 if (Param->hasUnparsedDefaultArg())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006503 Param->setDefaultArg(nullptr);
Douglas Gregor61366e92008-12-24 00:01:03 +00006504
John McCalld226f652010-08-21 09:40:31 +00006505 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006506 if (Param->getDeclName())
6507 IdResolver.AddDecl(Param);
6508}
6509
6510/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6511/// processing the delayed method declaration for Method. The method
6512/// declaration is now considered finished. There may be a separate
6513/// ActOnStartOfFunctionDef action later (not necessarily
6514/// immediately!) for this method, if it was also defined inside the
6515/// class body.
John McCalld226f652010-08-21 09:40:31 +00006516void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006517 if (!MethodD)
6518 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006519
Douglas Gregorefd5bda2009-08-24 11:57:43 +00006520 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00006521
John McCalld226f652010-08-21 09:40:31 +00006522 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006523
6524 // Now that we have our default arguments, check the constructor
6525 // again. It could produce additional diagnostics or affect whether
6526 // the class has implicitly-declared destructors, among other
6527 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00006528 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6529 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006530
6531 // Check the default arguments, which we may have added.
6532 if (!Method->isInvalidDecl())
6533 CheckCXXDefaultArguments(Method);
6534}
6535
Douglas Gregor42a552f2008-11-05 20:51:48 +00006536/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00006537/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00006538/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006539/// emit diagnostics and set the invalid bit to true. In any case, the type
6540/// will be updated to reflect a well-formed type for the constructor and
6541/// returned.
6542QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006543 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006544 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006545
6546 // C++ [class.ctor]p3:
6547 // A constructor shall not be virtual (10.3) or static (9.4). A
6548 // constructor can be invoked for a const, volatile or const
6549 // volatile object. A constructor shall not be declared const,
6550 // volatile, or const volatile (9.3.2).
6551 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00006552 if (!D.isInvalidType())
6553 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6554 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6555 << SourceRange(D.getIdentifierLoc());
6556 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006557 }
John McCalld931b082010-08-26 03:08:43 +00006558 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006559 if (!D.isInvalidType())
6560 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6561 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6562 << SourceRange(D.getIdentifierLoc());
6563 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006564 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006565 }
Mike Stump1eb44332009-09-09 15:08:12 +00006566
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006567 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6568 diagnoseIgnoredQualifiers(
6569 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
6570 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
6571 D.getDeclSpec().getRestrictSpecLoc(),
6572 D.getDeclSpec().getAtomicSpecLoc());
6573 D.setInvalidType();
6574 }
6575
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006576 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006577 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00006578 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006579 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6580 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006581 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006582 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6583 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006584 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006585 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6586 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00006587 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006588 }
Mike Stump1eb44332009-09-09 15:08:12 +00006589
Douglas Gregorc938c162011-01-26 05:01:58 +00006590 // C++0x [class.ctor]p4:
6591 // A constructor shall not be declared with a ref-qualifier.
6592 if (FTI.hasRefQualifier()) {
6593 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6594 << FTI.RefQualifierIsLValueRef
6595 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6596 D.setInvalidType();
6597 }
6598
Douglas Gregor42a552f2008-11-05 20:51:48 +00006599 // Rebuild the function type "R" without any type qualifiers (in
6600 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00006601 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00006602 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07006603 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
John McCalle23cf432010-12-14 08:05:40 +00006604 return R;
6605
6606 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6607 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006608 EPI.RefQualifier = RQ_None;
Stephen Hines651f13c2014-04-23 16:59:28 -07006609
6610 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006611}
6612
Douglas Gregor72b505b2008-12-16 21:30:33 +00006613/// CheckConstructor - Checks a fully-formed constructor for
6614/// well-formedness, issuing any diagnostics required. Returns true if
6615/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00006616void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00006617 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00006618 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6619 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00006620 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006621
6622 // C++ [class.copy]p3:
6623 // A declaration of a constructor for a class X is ill-formed if
6624 // its first parameter is of type (optionally cv-qualified) X and
6625 // either there are no other parameters or else all other
6626 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00006627 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006628 ((Constructor->getNumParams() == 1) ||
6629 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00006630 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6631 Constructor->getTemplateSpecializationKind()
6632 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006633 QualType ParamType = Constructor->getParamDecl(0)->getType();
6634 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6635 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00006636 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006637 const char *ConstRef
6638 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6639 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00006640 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006641 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00006642
6643 // FIXME: Rather that making the constructor invalid, we should endeavor
6644 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00006645 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006646 }
6647 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00006648}
6649
John McCall15442822010-08-04 01:04:25 +00006650/// CheckDestructor - Checks a fully-formed destructor definition for
6651/// well-formedness, issuing any diagnostics required. Returns true
6652/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006653bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006654 CXXRecordDecl *RD = Destructor->getParent();
6655
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006656 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006657 SourceLocation Loc;
6658
6659 if (!Destructor->isImplicit())
6660 Loc = Destructor->getLocation();
6661 else
6662 Loc = RD->getLocation();
6663
6664 // If we have a virtual destructor, look up the deallocation function
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006665 FunctionDecl *OperatorDelete = nullptr;
Anders Carlsson6d701392009-11-15 22:49:34 +00006666 DeclarationName Name =
6667 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006668 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00006669 return true;
Bill Wendlingc12b43a2013-12-07 23:53:50 +00006670 // If there's no class-specific operator delete, look up the global
6671 // non-array delete.
6672 if (!OperatorDelete)
6673 OperatorDelete = FindUsualDeallocationFunction(Loc, true, Name);
John McCall5efd91a2010-07-03 18:33:00 +00006674
Eli Friedman5f2987c2012-02-02 03:46:19 +00006675 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00006676
6677 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00006678 }
Anders Carlsson37909802009-11-30 21:24:50 +00006679
6680 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00006681}
6682
Douglas Gregor42a552f2008-11-05 20:51:48 +00006683/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6684/// the well-formednes of the destructor declarator @p D with type @p
6685/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006686/// emit diagnostics and set the declarator to invalid. Even if this happens,
6687/// will be updated to reflect a well-formed type for the destructor and
6688/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00006689QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006690 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006691 // C++ [class.dtor]p1:
6692 // [...] A typedef-name that names a class is a class-name
6693 // (7.1.3); however, a typedef-name that names a class shall not
6694 // be used as the identifier in the declarator for a destructor
6695 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006696 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006697 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006698 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006699 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006700 else if (const TemplateSpecializationType *TST =
6701 DeclaratorType->getAs<TemplateSpecializationType>())
6702 if (TST->isTypeAlias())
6703 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6704 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006705
6706 // C++ [class.dtor]p2:
6707 // A destructor is used to destroy objects of its class type. A
6708 // destructor takes no parameters, and no return type can be
6709 // specified for it (not even void). The address of a destructor
6710 // shall not be taken. A destructor shall not be static. A
6711 // destructor can be invoked for a const, volatile or const
6712 // volatile object. A destructor shall not be declared const,
6713 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006714 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006715 if (!D.isInvalidType())
6716 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6717 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006718 << SourceRange(D.getIdentifierLoc())
6719 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6720
John McCalld931b082010-08-26 03:08:43 +00006721 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006722 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006723 if (!D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006724 // Destructors don't have return types, but the parser will
6725 // happily parse something like:
6726 //
6727 // class X {
6728 // float ~X();
6729 // };
6730 //
6731 // The return type will be eliminated later.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07006732 if (D.getDeclSpec().hasTypeSpecifier())
6733 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6734 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6735 << SourceRange(D.getIdentifierLoc());
6736 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
6737 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
6738 SourceLocation(),
6739 D.getDeclSpec().getConstSpecLoc(),
6740 D.getDeclSpec().getVolatileSpecLoc(),
6741 D.getDeclSpec().getRestrictSpecLoc(),
6742 D.getDeclSpec().getAtomicSpecLoc());
6743 D.setInvalidType();
6744 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006745 }
Mike Stump1eb44332009-09-09 15:08:12 +00006746
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006747 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006748 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006749 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006750 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6751 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006752 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006753 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6754 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006755 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006756 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6757 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006758 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006759 }
6760
Douglas Gregorc938c162011-01-26 05:01:58 +00006761 // C++0x [class.dtor]p2:
6762 // A destructor shall not be declared with a ref-qualifier.
6763 if (FTI.hasRefQualifier()) {
6764 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6765 << FTI.RefQualifierIsLValueRef
6766 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6767 D.setInvalidType();
6768 }
6769
Douglas Gregor42a552f2008-11-05 20:51:48 +00006770 // Make sure we don't have any parameters.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006771 if (FTIHasNonVoidParameters(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006772 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6773
6774 // Delete the parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006775 FTI.freeParams();
Chris Lattner65401802009-04-25 08:28:21 +00006776 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006777 }
6778
Mike Stump1eb44332009-09-09 15:08:12 +00006779 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006780 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006781 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006782 D.setInvalidType();
6783 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006784
6785 // Rebuild the function type "R" without any type qualifiers or
6786 // parameters (in case any of the errors above fired) and with
6787 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006788 // types.
John McCalle23cf432010-12-14 08:05:40 +00006789 if (!D.isInvalidType())
6790 return R;
6791
Douglas Gregord92ec472010-07-01 05:10:53 +00006792 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006793 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6794 EPI.Variadic = false;
6795 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006796 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006797 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006798}
6799
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006800/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6801/// well-formednes of the conversion function declarator @p D with
6802/// type @p R. If there are any errors in the declarator, this routine
6803/// will emit diagnostics and return true. Otherwise, it will return
6804/// false. Either way, the type @p R will be updated to reflect a
6805/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006806void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006807 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006808 // C++ [class.conv.fct]p1:
6809 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006810 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006811 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006812 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006813 if (!D.isInvalidType())
6814 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006815 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6816 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006817 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006818 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006819 }
John McCalla3f81372010-04-13 00:04:31 +00006820
6821 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6822
Chris Lattner6e475012009-04-25 08:35:12 +00006823 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006824 // Conversion functions don't have return types, but the parser will
6825 // happily parse something like:
6826 //
6827 // class X {
6828 // float operator bool();
6829 // };
6830 //
6831 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006832 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6833 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6834 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006835 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006836 }
6837
John McCalla3f81372010-04-13 00:04:31 +00006838 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6839
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006840 // Make sure we don't have any parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006841 if (Proto->getNumParams() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006842 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6843
6844 // Delete the parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -07006845 D.getFunctionTypeInfo().freeParams();
Chris Lattner6e475012009-04-25 08:35:12 +00006846 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006847 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006848 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006849 D.setInvalidType();
6850 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006851
John McCalla3f81372010-04-13 00:04:31 +00006852 // Diagnose "&operator bool()" and other such nonsense. This
6853 // is actually a gcc extension which we don't support.
Stephen Hines651f13c2014-04-23 16:59:28 -07006854 if (Proto->getReturnType() != ConvType) {
John McCalla3f81372010-04-13 00:04:31 +00006855 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
Stephen Hines651f13c2014-04-23 16:59:28 -07006856 << Proto->getReturnType();
John McCalla3f81372010-04-13 00:04:31 +00006857 D.setInvalidType();
Stephen Hines651f13c2014-04-23 16:59:28 -07006858 ConvType = Proto->getReturnType();
John McCalla3f81372010-04-13 00:04:31 +00006859 }
6860
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006861 // C++ [class.conv.fct]p4:
6862 // The conversion-type-id shall not represent a function type nor
6863 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006864 if (ConvType->isArrayType()) {
6865 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6866 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006867 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006868 } else if (ConvType->isFunctionType()) {
6869 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6870 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006871 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006872 }
6873
6874 // Rebuild the function type "R" without any parameters (in case any
6875 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006876 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006877 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006878 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006879
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006880 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006881 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006882 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006883 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006884 diag::warn_cxx98_compat_explicit_conversion_functions :
6885 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006886 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006887}
6888
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006889/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6890/// the declaration of the given C++ conversion function. This routine
6891/// is responsible for recording the conversion function in the C++
6892/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006893Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006894 assert(Conversion && "Expected to receive a conversion function declaration");
6895
Douglas Gregor9d350972008-12-12 08:25:50 +00006896 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006897
6898 // Make sure we aren't redeclaring the conversion function.
6899 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006900
6901 // C++ [class.conv.fct]p1:
6902 // [...] A conversion function is never used to convert a
6903 // (possibly cv-qualified) object to the (possibly cv-qualified)
6904 // same object type (or a reference to it), to a (possibly
6905 // cv-qualified) base class of that type (or a reference to it),
6906 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006907 // FIXME: Suppress this warning if the conversion function ends up being a
6908 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006909 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006910 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006911 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006912 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006913 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6914 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006915 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006916 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006917 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6918 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006919 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006920 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006921 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006922 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006923 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006924 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006925 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006926 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006927 }
6928
Douglas Gregore80622f2010-09-29 04:25:11 +00006929 if (FunctionTemplateDecl *ConversionTemplate
6930 = Conversion->getDescribedFunctionTemplate())
6931 return ConversionTemplate;
6932
John McCalld226f652010-08-21 09:40:31 +00006933 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006934}
6935
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006936//===----------------------------------------------------------------------===//
6937// Namespace Handling
6938//===----------------------------------------------------------------------===//
6939
Richard Smithd1a55a62012-10-04 22:13:39 +00006940/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6941/// reopened.
6942static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6943 SourceLocation Loc,
6944 IdentifierInfo *II, bool *IsInline,
6945 NamespaceDecl *PrevNS) {
6946 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006947
Richard Smithc969e6a2012-10-05 01:46:25 +00006948 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6949 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6950 // inline namespaces, with the intention of bringing names into namespace std.
6951 //
6952 // We support this just well enough to get that case working; this is not
6953 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006954 if (*IsInline && II && II->getName().startswith("__atomic") &&
6955 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006956 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006957 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6958 NS = NS->getPreviousDecl())
6959 NS->setInline(*IsInline);
6960 // Patch up the lookup table for the containing namespace. This isn't really
6961 // correct, but it's good enough for this particular case.
Stephen Hines651f13c2014-04-23 16:59:28 -07006962 for (auto *I : PrevNS->decls())
6963 if (auto *ND = dyn_cast<NamedDecl>(I))
Richard Smithd1a55a62012-10-04 22:13:39 +00006964 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6965 return;
6966 }
6967
6968 if (PrevNS->isInline())
6969 // The user probably just forgot the 'inline', so suggest that it
6970 // be added back.
6971 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6972 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6973 else
Stephen Hines651f13c2014-04-23 16:59:28 -07006974 S.Diag(Loc, diag::err_inline_namespace_mismatch) << *IsInline;
Richard Smithd1a55a62012-10-04 22:13:39 +00006975
6976 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6977 *IsInline = PrevNS->isInline();
6978}
John McCallea318642010-08-26 09:15:37 +00006979
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006980/// ActOnStartNamespaceDef - This is called at the start of a namespace
6981/// definition.
John McCalld226f652010-08-21 09:40:31 +00006982Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006983 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006984 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006985 SourceLocation IdentLoc,
6986 IdentifierInfo *II,
6987 SourceLocation LBrace,
6988 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006989 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6990 // For anonymous namespace, take the location of the left brace.
6991 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006992 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006993 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006994 bool IsStd = false;
6995 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006996 Scope *DeclRegionScope = NamespcScope->getParent();
6997
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006998 NamespaceDecl *PrevNS = nullptr;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006999 if (II) {
7000 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00007001 // The identifier in an original-namespace-definition shall not
7002 // have been previously defined in the declarative region in
7003 // which the original-namespace-definition appears. The
7004 // identifier in an original-namespace-definition is the name of
7005 // the namespace. Subsequently in that declarative region, it is
7006 // treated as an original-namespace-name.
7007 //
7008 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00007009 // look through using directives, just look for any ordinary names.
7010
7011 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007012 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
7013 Decl::IDNS_Namespace;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007014 NamedDecl *PrevDecl = nullptr;
David Blaikie3bc93e32012-12-19 00:45:41 +00007015 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
7016 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
7017 ++I) {
7018 if ((*I)->getIdentifierNamespace() & IDNS) {
7019 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00007020 break;
7021 }
7022 }
7023
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007024 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
7025
7026 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00007027 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00007028 if (IsInline != PrevNS->isInline())
7029 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
7030 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00007031 } else if (PrevDecl) {
7032 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007033 Diag(Loc, diag::err_redefinition_different_kind)
7034 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00007035 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00007036 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00007037 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007038 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00007039 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00007040 // This is the first "real" definition of the namespace "std", so update
7041 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007042 PrevNS = getStdNamespace();
7043 IsStd = true;
7044 AddToKnown = !IsInline;
7045 } else {
7046 // We've seen this namespace for the first time.
7047 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00007048 }
Douglas Gregor44b43212008-12-11 16:49:14 +00007049 } else {
John McCall9aeed322009-10-01 00:25:31 +00007050 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007051
7052 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00007053 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00007054 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007055 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00007056 } else {
7057 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007058 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00007059 }
7060
Richard Smithd1a55a62012-10-04 22:13:39 +00007061 if (PrevNS && IsInline != PrevNS->isInline())
7062 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
7063 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007064 }
7065
7066 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
7067 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00007068 if (IsInvalid)
7069 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007070
7071 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00007072
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007073 // FIXME: Should we be merging attributes?
7074 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00007075 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007076
7077 if (IsStd)
7078 StdNamespace = Namespc;
7079 if (AddToKnown)
7080 KnownNamespaces[Namespc] = false;
7081
7082 if (II) {
7083 PushOnScopeChains(Namespc, DeclRegionScope);
7084 } else {
7085 // Link the anonymous namespace into its parent.
7086 DeclContext *Parent = CurContext->getRedeclContext();
7087 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
7088 TU->setAnonymousNamespace(Namespc);
7089 } else {
7090 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00007091 }
John McCall9aeed322009-10-01 00:25:31 +00007092
Douglas Gregora4181472010-03-24 00:46:35 +00007093 CurContext->addDecl(Namespc);
7094
John McCall9aeed322009-10-01 00:25:31 +00007095 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
7096 // behaves as if it were replaced by
7097 // namespace unique { /* empty body */ }
7098 // using namespace unique;
7099 // namespace unique { namespace-body }
7100 // where all occurrences of 'unique' in a translation unit are
7101 // replaced by the same identifier and this identifier differs
7102 // from all other identifiers in the entire program.
7103
7104 // We just create the namespace with an empty name and then add an
7105 // implicit using declaration, just like the standard suggests.
7106 //
7107 // CodeGen enforces the "universally unique" aspect by giving all
7108 // declarations semantically contained within an anonymous
7109 // namespace internal linkage.
7110
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007111 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00007112 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00007113 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00007114 /* 'using' */ LBrace,
7115 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00007116 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00007117 /* identifier */ SourceLocation(),
7118 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00007119 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00007120 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00007121 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00007122 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007123 }
7124
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00007125 ActOnDocumentableDecl(Namespc);
7126
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007127 // Although we could have an invalid decl (i.e. the namespace name is a
7128 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00007129 // FIXME: We should be able to push Namespc here, so that the each DeclContext
7130 // for the namespace has the declarations that showed up in that particular
7131 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00007132 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00007133 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007134}
7135
Sebastian Redleb0d8c92009-11-23 15:34:23 +00007136/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
7137/// is a namespace alias, returns the namespace it points to.
7138static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
7139 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
7140 return AD->getNamespace();
7141 return dyn_cast_or_null<NamespaceDecl>(D);
7142}
7143
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007144/// ActOnFinishNamespaceDef - This callback is called after a namespace is
7145/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00007146void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007147 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
7148 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00007149 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007150 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00007151 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00007152 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00007153}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007154
John McCall384aff82010-08-25 07:42:41 +00007155CXXRecordDecl *Sema::getStdBadAlloc() const {
7156 return cast_or_null<CXXRecordDecl>(
7157 StdBadAlloc.get(Context.getExternalSource()));
7158}
7159
7160NamespaceDecl *Sema::getStdNamespace() const {
7161 return cast_or_null<NamespaceDecl>(
7162 StdNamespace.get(Context.getExternalSource()));
7163}
7164
Douglas Gregor66992202010-06-29 17:53:46 +00007165/// \brief Retrieve the special "std" namespace, which may require us to
7166/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00007167NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00007168 if (!StdNamespace) {
7169 // The "std" namespace has not yet been defined, so build one implicitly.
7170 StdNamespace = NamespaceDecl::Create(Context,
7171 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007172 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00007173 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00007174 &PP.getIdentifierTable().get("std"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007175 /*PrevDecl=*/nullptr);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00007176 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00007177 }
Stephen Hines176edba2014-12-01 14:53:08 -08007178
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00007179 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00007180}
7181
Sebastian Redl395e04d2012-01-17 22:49:33 +00007182bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00007183 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00007184 "Looking for std::initializer_list outside of C++.");
7185
7186 // We're looking for implicit instantiations of
7187 // template <typename E> class std::initializer_list.
7188
7189 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
7190 return false;
7191
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007192 ClassTemplateDecl *Template = nullptr;
7193 const TemplateArgument *Arguments = nullptr;
Sebastian Redl395e04d2012-01-17 22:49:33 +00007194
Sebastian Redl84760e32012-01-17 22:49:58 +00007195 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00007196
Sebastian Redl84760e32012-01-17 22:49:58 +00007197 ClassTemplateSpecializationDecl *Specialization =
7198 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
7199 if (!Specialization)
7200 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00007201
Sebastian Redl84760e32012-01-17 22:49:58 +00007202 Template = Specialization->getSpecializedTemplate();
7203 Arguments = Specialization->getTemplateArgs().data();
7204 } else if (const TemplateSpecializationType *TST =
7205 Ty->getAs<TemplateSpecializationType>()) {
7206 Template = dyn_cast_or_null<ClassTemplateDecl>(
7207 TST->getTemplateName().getAsTemplateDecl());
7208 Arguments = TST->getArgs();
7209 }
7210 if (!Template)
7211 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00007212
7213 if (!StdInitializerList) {
7214 // Haven't recognized std::initializer_list yet, maybe this is it.
7215 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
7216 if (TemplateClass->getIdentifier() !=
7217 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00007218 !getStdNamespace()->InEnclosingNamespaceSetOf(
7219 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00007220 return false;
7221 // This is a template called std::initializer_list, but is it the right
7222 // template?
7223 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00007224 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00007225 return false;
7226 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
7227 return false;
7228
7229 // It's the right template.
7230 StdInitializerList = Template;
7231 }
7232
7233 if (Template != StdInitializerList)
7234 return false;
7235
7236 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00007237 if (Element)
7238 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00007239 return true;
7240}
7241
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00007242static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
7243 NamespaceDecl *Std = S.getStdNamespace();
7244 if (!Std) {
7245 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007246 return nullptr;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00007247 }
7248
7249 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
7250 Loc, Sema::LookupOrdinaryName);
7251 if (!S.LookupQualifiedName(Result, Std)) {
7252 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007253 return nullptr;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00007254 }
7255 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
7256 if (!Template) {
7257 Result.suppressDiagnostics();
7258 // We found something weird. Complain about the first thing we found.
7259 NamedDecl *Found = *Result.begin();
7260 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007261 return nullptr;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00007262 }
7263
7264 // We found some template called std::initializer_list. Now verify that it's
7265 // correct.
7266 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00007267 if (Params->getMinRequiredArguments() != 1 ||
7268 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00007269 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007270 return nullptr;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00007271 }
7272
7273 return Template;
7274}
7275
7276QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
7277 if (!StdInitializerList) {
7278 StdInitializerList = LookupStdInitializerList(*this, Loc);
7279 if (!StdInitializerList)
7280 return QualType();
7281 }
7282
7283 TemplateArgumentListInfo Args(Loc, Loc);
7284 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
7285 Context.getTrivialTypeSourceInfo(Element,
7286 Loc)));
7287 return Context.getCanonicalType(
7288 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
7289}
7290
Sebastian Redl98d36062012-01-17 22:50:14 +00007291bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
7292 // C++ [dcl.init.list]p2:
7293 // A constructor is an initializer-list constructor if its first parameter
7294 // is of type std::initializer_list<E> or reference to possibly cv-qualified
7295 // std::initializer_list<E> for some type E, and either there are no other
7296 // parameters or else all other parameters have default arguments.
7297 if (Ctor->getNumParams() < 1 ||
7298 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
7299 return false;
7300
7301 QualType ArgType = Ctor->getParamDecl(0)->getType();
7302 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
7303 ArgType = RT->getPointeeType().getUnqualifiedType();
7304
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007305 return isStdInitializerList(ArgType, nullptr);
Sebastian Redl98d36062012-01-17 22:50:14 +00007306}
7307
Douglas Gregor9172aa62011-03-26 22:25:30 +00007308/// \brief Determine whether a using statement is in a context where it will be
7309/// apply in all contexts.
7310static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
7311 switch (CurContext->getDeclKind()) {
7312 case Decl::TranslationUnit:
7313 return true;
7314 case Decl::LinkageSpec:
7315 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
7316 default:
7317 return false;
7318 }
7319}
7320
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00007321namespace {
7322
7323// Callback to only accept typo corrections that are namespaces.
7324class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007325public:
Stephen Hines651f13c2014-04-23 16:59:28 -07007326 bool ValidateCandidate(const TypoCorrection &candidate) override {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007327 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00007328 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00007329 return false;
7330 }
7331};
7332
7333}
7334
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007335static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
7336 CXXScopeSpec &SS,
7337 SourceLocation IdentLoc,
7338 IdentifierInfo *Ident) {
7339 R.clear();
Stephen Hines176edba2014-12-01 14:53:08 -08007340 if (TypoCorrection Corrected =
7341 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
7342 llvm::make_unique<NamespaceValidatorCCC>(),
7343 Sema::CTK_ErrorRecovery)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00007344 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00007345 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
7346 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00007347 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00007348 S.diagnoseTypo(Corrected,
7349 S.PDiag(diag::err_using_directive_member_suggest)
7350 << Ident << DC << DroppedSpecifier << SS.getRange(),
7351 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00007352 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007353 S.diagnoseTypo(Corrected,
7354 S.PDiag(diag::err_using_directive_suggest) << Ident,
7355 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00007356 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00007357 R.addDecl(Corrected.getCorrectionDecl());
7358 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007359 }
7360 return false;
7361}
7362
John McCalld226f652010-08-21 09:40:31 +00007363Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007364 SourceLocation UsingLoc,
7365 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007366 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007367 SourceLocation IdentLoc,
7368 IdentifierInfo *NamespcName,
7369 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00007370 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7371 assert(NamespcName && "Invalid NamespcName.");
7372 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00007373
7374 // This can only happen along a recovery path.
7375 while (S->getFlags() & Scope::TemplateParamScope)
7376 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007377 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00007378
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007379 UsingDirectiveDecl *UDir = nullptr;
7380 NestedNameSpecifier *Qualifier = nullptr;
Douglas Gregor66992202010-06-29 17:53:46 +00007381 if (SS.isSet())
Stephen Hines651f13c2014-04-23 16:59:28 -07007382 Qualifier = SS.getScopeRep();
Douglas Gregor66992202010-06-29 17:53:46 +00007383
Douglas Gregoreb11cd02009-01-14 22:20:51 +00007384 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007385 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
7386 LookupParsedName(R, S, &SS);
7387 if (R.isAmbiguous())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007388 return nullptr;
John McCalla24dc2e2009-11-17 02:14:36 +00007389
Douglas Gregor66992202010-06-29 17:53:46 +00007390 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007391 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00007392 // Allow "using namespace std;" or "using namespace ::std;" even if
7393 // "std" hasn't been defined yet, for GCC compatibility.
7394 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
7395 NamespcName->isStr("std")) {
7396 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00007397 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00007398 R.resolveKind();
7399 }
7400 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007401 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00007402 }
7403
John McCallf36e02d2009-10-09 21:13:30 +00007404 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00007405 NamedDecl *Named = R.getFoundDecl();
7406 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
7407 && "expected namespace decl");
Stephen Hines176edba2014-12-01 14:53:08 -08007408
7409 // The use of a nested name specifier may trigger deprecation warnings.
7410 DiagnoseUseOfDecl(Named, IdentLoc);
7411
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007412 // C++ [namespace.udir]p1:
7413 // A using-directive specifies that the names in the nominated
7414 // namespace can be used in the scope in which the
7415 // using-directive appears after the using-directive. During
7416 // unqualified name lookup (3.4.1), the names appear as if they
7417 // were declared in the nearest enclosing namespace which
7418 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00007419 // namespace. [Note: in this context, "contains" means "contains
7420 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007421
7422 // Find enclosing context containing both using-directive and
7423 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00007424 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007425 DeclContext *CommonAncestor = cast<DeclContext>(NS);
7426 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
7427 CommonAncestor = CommonAncestor->getParent();
7428
Sebastian Redleb0d8c92009-11-23 15:34:23 +00007429 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00007430 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00007431 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00007432
Douglas Gregor9172aa62011-03-26 22:25:30 +00007433 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00007434 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00007435 Diag(IdentLoc, diag::warn_using_directive_in_header);
7436 }
7437
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007438 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00007439 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00007440 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00007441 }
7442
Richard Smith6b3d3e52013-02-20 19:22:51 +00007443 if (UDir)
7444 ProcessDeclAttributeList(S, UDir, AttrList);
7445
John McCalld226f652010-08-21 09:40:31 +00007446 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007447}
7448
7449void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00007450 // If the scope has an associated entity and the using directive is at
7451 // namespace or translation unit scope, add the UsingDirectiveDecl into
7452 // its lookup structure so qualified name lookup can find it.
Ted Kremenekf0d58612013-10-08 17:08:03 +00007453 DeclContext *Ctx = S->getEntity();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00007454 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00007455 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00007456 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007457 // Otherwise, it is at block scope. The using-directives will affect lookup
Richard Smith1b7f9cb2012-03-13 03:12:56 +00007458 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00007459 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00007460}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00007461
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007462
John McCalld226f652010-08-21 09:40:31 +00007463Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00007464 AccessSpecifier AS,
7465 bool HasUsingKeyword,
7466 SourceLocation UsingLoc,
7467 CXXScopeSpec &SS,
7468 UnqualifiedId &Name,
7469 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007470 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00007471 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007472 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00007473
Douglas Gregor12c118a2009-11-04 16:30:06 +00007474 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00007475 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00007476 case UnqualifiedId::IK_Identifier:
7477 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00007478 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00007479 case UnqualifiedId::IK_ConversionFunctionId:
7480 break;
7481
7482 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00007483 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00007484 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00007485 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00007486 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00007487 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00007488 diag::err_using_decl_constructor)
7489 << SS.getRange();
7490
Richard Smith80ad52f2013-01-02 11:42:31 +00007491 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00007492
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007493 return nullptr;
7494
Douglas Gregor12c118a2009-11-04 16:30:06 +00007495 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00007496 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00007497 << SS.getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007498 return nullptr;
7499
Douglas Gregor12c118a2009-11-04 16:30:06 +00007500 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00007501 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00007502 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007503 return nullptr;
Douglas Gregor12c118a2009-11-04 16:30:06 +00007504 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007505
7506 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7507 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00007508 if (!TargetName)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007509 return nullptr;
John McCall604e7f12009-12-08 07:46:18 +00007510
Richard Smith07b0fdc2013-03-18 21:12:30 +00007511 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00007512 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00007513 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00007514 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7515 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00007516 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00007517 }
7518
Douglas Gregor56c04582010-12-16 00:46:58 +00007519 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7520 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007521 return nullptr;
Douglas Gregor56c04582010-12-16 00:46:58 +00007522
John McCall9488ea12009-11-17 05:59:44 +00007523 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007524 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007525 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007526 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00007527 if (UD)
7528 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00007529
John McCalld226f652010-08-21 09:40:31 +00007530 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00007531}
7532
Douglas Gregor09acc982010-07-07 23:08:52 +00007533/// \brief Determine whether a using declaration considers the given
7534/// declarations as "equivalent", e.g., if they are redeclarations of
7535/// the same entity or are both typedefs of the same type.
Richard Smithf06a28932013-10-23 02:17:46 +00007536static bool
7537IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7538 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor09acc982010-07-07 23:08:52 +00007539 return true;
Douglas Gregor09acc982010-07-07 23:08:52 +00007540
Richard Smith162e1c12011-04-15 14:24:37 +00007541 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithf06a28932013-10-23 02:17:46 +00007542 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor09acc982010-07-07 23:08:52 +00007543 return Context.hasSameType(TD1->getUnderlyingType(),
7544 TD2->getUnderlyingType());
Douglas Gregor09acc982010-07-07 23:08:52 +00007545
7546 return false;
7547}
7548
7549
John McCall9f54ad42009-12-10 09:41:52 +00007550/// Determines whether to create a using shadow decl for a particular
7551/// decl, given the set of decls existing prior to this using lookup.
7552bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithf06a28932013-10-23 02:17:46 +00007553 const LookupResult &Previous,
7554 UsingShadowDecl *&PrevShadow) {
John McCall9f54ad42009-12-10 09:41:52 +00007555 // Diagnose finding a decl which is not from a base class of the
7556 // current class. We do this now because there are cases where this
7557 // function will silently decide not to build a shadow decl, which
7558 // will pre-empt further diagnostics.
7559 //
7560 // We don't need to do this in C++0x because we do the check once on
7561 // the qualifier.
7562 //
7563 // FIXME: diagnose the following if we care enough:
7564 // struct A { int foo; };
7565 // struct B : A { using A::foo; };
7566 // template <class T> struct C : A {};
7567 // template <class T> struct D : C<T> { using B::foo; } // <---
7568 // This is invalid (during instantiation) in C++03 because B::foo
7569 // resolves to the using decl in B, which is not a base class of D<T>.
7570 // We can't diagnose it immediately because C<T> is an unknown
7571 // specialization. The UsingShadowDecl in D<T> then points directly
7572 // to A::foo, which will look well-formed when we instantiate.
7573 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00007574 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00007575 DeclContext *OrigDC = Orig->getDeclContext();
7576
7577 // Handle enums and anonymous structs.
7578 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7579 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7580 while (OrigRec->isAnonymousStructOrUnion())
7581 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7582
7583 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7584 if (OrigDC == CurContext) {
7585 Diag(Using->getLocation(),
7586 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007587 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007588 Diag(Orig->getLocation(), diag::note_using_decl_target);
7589 return true;
7590 }
7591
Douglas Gregordc355712011-02-25 00:36:19 +00007592 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00007593 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007594 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00007595 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00007596 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007597 Diag(Orig->getLocation(), diag::note_using_decl_target);
7598 return true;
7599 }
7600 }
7601
7602 if (Previous.empty()) return false;
7603
7604 NamedDecl *Target = Orig;
7605 if (isa<UsingShadowDecl>(Target))
7606 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7607
John McCalld7533ec2009-12-11 02:33:26 +00007608 // If the target happens to be one of the previous declarations, we
7609 // don't have a conflict.
7610 //
7611 // FIXME: but we might be increasing its access, in which case we
7612 // should redeclare it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007613 NamedDecl *NonTag = nullptr, *Tag = nullptr;
Richard Smithf06a28932013-10-23 02:17:46 +00007614 bool FoundEquivalentDecl = false;
John McCalld7533ec2009-12-11 02:33:26 +00007615 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7616 I != E; ++I) {
7617 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithf06a28932013-10-23 02:17:46 +00007618 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7619 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7620 PrevShadow = Shadow;
7621 FoundEquivalentDecl = true;
7622 }
John McCalld7533ec2009-12-11 02:33:26 +00007623
7624 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7625 }
7626
Richard Smithf06a28932013-10-23 02:17:46 +00007627 if (FoundEquivalentDecl)
7628 return false;
7629
Stephen Hines651f13c2014-04-23 16:59:28 -07007630 if (FunctionDecl *FD = Target->getAsFunction()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007631 NamedDecl *OldDecl = nullptr;
7632 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
7633 /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00007634 case Ovl_Overload:
7635 return false;
7636
7637 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00007638 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007639 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07007640
John McCall9f54ad42009-12-10 09:41:52 +00007641 // We found a decl with the exact signature.
7642 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007643 // If we're in a record, we want to hide the target, so we
7644 // return true (without a diagnostic) to tell the caller not to
7645 // build a shadow decl.
7646 if (CurContext->isRecord())
7647 return true;
7648
7649 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00007650 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007651 break;
7652 }
7653
7654 Diag(Target->getLocation(), diag::note_using_decl_target);
7655 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7656 return true;
7657 }
7658
7659 // Target is not a function.
7660
John McCall9f54ad42009-12-10 09:41:52 +00007661 if (isa<TagDecl>(Target)) {
7662 // No conflict between a tag and a non-tag.
7663 if (!Tag) return false;
7664
John McCall41ce66f2009-12-10 19:51:03 +00007665 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007666 Diag(Target->getLocation(), diag::note_using_decl_target);
7667 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7668 return true;
7669 }
7670
7671 // No conflict between a tag and a non-tag.
7672 if (!NonTag) return false;
7673
John McCall41ce66f2009-12-10 19:51:03 +00007674 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007675 Diag(Target->getLocation(), diag::note_using_decl_target);
7676 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7677 return true;
7678}
7679
John McCall9488ea12009-11-17 05:59:44 +00007680/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00007681UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00007682 UsingDecl *UD,
Richard Smithf06a28932013-10-23 02:17:46 +00007683 NamedDecl *Orig,
7684 UsingShadowDecl *PrevDecl) {
John McCall9488ea12009-11-17 05:59:44 +00007685
7686 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00007687 NamedDecl *Target = Orig;
7688 if (isa<UsingShadowDecl>(Target)) {
7689 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7690 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00007691 }
Richard Smithf06a28932013-10-23 02:17:46 +00007692
John McCall9488ea12009-11-17 05:59:44 +00007693 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00007694 = UsingShadowDecl::Create(Context, CurContext,
7695 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00007696 UD->addShadowDecl(Shadow);
Richard Smithf06a28932013-10-23 02:17:46 +00007697
Douglas Gregore80622f2010-09-29 04:25:11 +00007698 Shadow->setAccess(UD->getAccess());
7699 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7700 Shadow->setInvalidDecl();
Richard Smithf06a28932013-10-23 02:17:46 +00007701
7702 Shadow->setPreviousDecl(PrevDecl);
7703
John McCall9488ea12009-11-17 05:59:44 +00007704 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007705 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007706 else
John McCall604e7f12009-12-08 07:46:18 +00007707 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007708
John McCall604e7f12009-12-08 07:46:18 +00007709
John McCall9f54ad42009-12-10 09:41:52 +00007710 return Shadow;
7711}
John McCall604e7f12009-12-08 07:46:18 +00007712
John McCall9f54ad42009-12-10 09:41:52 +00007713/// Hides a using shadow declaration. This is required by the current
7714/// using-decl implementation when a resolvable using declaration in a
7715/// class is followed by a declaration which would hide or override
7716/// one or more of the using decl's targets; for example:
7717///
7718/// struct Base { void foo(int); };
7719/// struct Derived : Base {
7720/// using Base::foo;
7721/// void foo(int);
7722/// };
7723///
7724/// The governing language is C++03 [namespace.udecl]p12:
7725///
7726/// When a using-declaration brings names from a base class into a
7727/// derived class scope, member functions in the derived class
7728/// override and/or hide member functions with the same name and
7729/// parameter types in a base class (rather than conflicting).
7730///
7731/// There are two ways to implement this:
7732/// (1) optimistically create shadow decls when they're not hidden
7733/// by existing declarations, or
7734/// (2) don't create any shadow decls (or at least don't make them
7735/// visible) until we've fully parsed/instantiated the class.
7736/// The problem with (1) is that we might have to retroactively remove
7737/// a shadow decl, which requires several O(n) operations because the
7738/// decl structures are (very reasonably) not designed for removal.
7739/// (2) avoids this but is very fiddly and phase-dependent.
7740void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007741 if (Shadow->getDeclName().getNameKind() ==
7742 DeclarationName::CXXConversionFunctionName)
7743 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7744
John McCall9f54ad42009-12-10 09:41:52 +00007745 // Remove it from the DeclContext...
7746 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007747
John McCall9f54ad42009-12-10 09:41:52 +00007748 // ...and the scope, if applicable...
7749 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007750 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007751 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007752 }
7753
John McCall9f54ad42009-12-10 09:41:52 +00007754 // ...and the using decl.
7755 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7756
7757 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007758 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007759}
7760
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007761/// Find the base specifier for a base class with the given type.
7762static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
7763 QualType DesiredBase,
7764 bool &AnyDependentBases) {
7765 // Check whether the named type is a direct base class.
7766 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
7767 for (auto &Base : Derived->bases()) {
7768 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
7769 if (CanonicalDesiredBase == BaseType)
7770 return &Base;
7771 if (BaseType->isDependentType())
7772 AnyDependentBases = true;
7773 }
7774 return nullptr;
7775}
7776
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007777namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007778class UsingValidatorCCC : public CorrectionCandidateCallback {
7779public:
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007780 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007781 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007782 : HasTypenameKeyword(HasTypenameKeyword),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007783 IsInstantiation(IsInstantiation), OldNNS(NNS),
7784 RequireMemberOf(RequireMemberOf) {}
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007785
Stephen Hines651f13c2014-04-23 16:59:28 -07007786 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007787 NamedDecl *ND = Candidate.getCorrectionDecl();
7788
7789 // Keywords are not valid here.
7790 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007791 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007792
7793 // Completely unqualified names are invalid for a 'using' declaration.
7794 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7795 return false;
7796
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007797 if (RequireMemberOf) {
7798 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
7799 if (FoundRecord && FoundRecord->isInjectedClassName()) {
7800 // No-one ever wants a using-declaration to name an injected-class-name
7801 // of a base class, unless they're declaring an inheriting constructor.
7802 ASTContext &Ctx = ND->getASTContext();
7803 if (!Ctx.getLangOpts().CPlusPlus11)
7804 return false;
7805 QualType FoundType = Ctx.getRecordType(FoundRecord);
7806
7807 // Check that the injected-class-name is named as a member of its own
7808 // type; we don't want to suggest 'using Derived::Base;', since that
7809 // means something else.
7810 NestedNameSpecifier *Specifier =
7811 Candidate.WillReplaceSpecifier()
7812 ? Candidate.getCorrectionSpecifier()
7813 : OldNNS;
7814 if (!Specifier->getAsType() ||
7815 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
7816 return false;
7817
7818 // Check that this inheriting constructor declaration actually names a
7819 // direct base class of the current class.
7820 bool AnyDependentBases = false;
7821 if (!findDirectBaseWithType(RequireMemberOf,
7822 Ctx.getRecordType(FoundRecord),
7823 AnyDependentBases) &&
7824 !AnyDependentBases)
7825 return false;
7826 } else {
7827 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
7828 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
7829 return false;
7830
7831 // FIXME: Check that the base class member is accessible?
7832 }
7833 }
7834
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007835 if (isa<TypeDecl>(ND))
7836 return HasTypenameKeyword || !IsInstantiation;
7837
7838 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007839 }
7840
7841private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007842 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007843 bool IsInstantiation;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007844 NestedNameSpecifier *OldNNS;
7845 CXXRecordDecl *RequireMemberOf;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007846};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007847} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007848
John McCall7ba107a2009-11-18 02:36:19 +00007849/// Builds a using declaration.
7850///
7851/// \param IsInstantiation - Whether this call arises from an
7852/// instantiation of an unresolved using declaration. We treat
7853/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007854NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7855 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007856 CXXScopeSpec &SS,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007857 DeclarationNameInfo NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007858 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007859 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007860 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007861 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007862 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007863 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007864 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007865
Anders Carlsson550b14b2009-08-28 05:49:21 +00007866 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007867
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007868 if (SS.isEmpty()) {
7869 Diag(IdentLoc, diag::err_using_requires_qualname);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007870 return nullptr;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007871 }
Mike Stump1eb44332009-09-09 15:08:12 +00007872
John McCall9f54ad42009-12-10 09:41:52 +00007873 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007874 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007875 ForRedeclaration);
7876 Previous.setHideTags(false);
7877 if (S) {
7878 LookupName(Previous, S);
7879
7880 // It is really dumb that we have to do this.
7881 LookupResult::Filter F = Previous.makeFilter();
7882 while (F.hasNext()) {
7883 NamedDecl *D = F.next();
7884 if (!isDeclInScope(D, CurContext, S))
7885 F.erase();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007886 // If we found a local extern declaration that's not ordinarily visible,
7887 // and this declaration is being added to a non-block scope, ignore it.
7888 // We're only checking for scope conflicts here, not also for violations
7889 // of the linkage rules.
7890 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
7891 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
7892 F.erase();
John McCall9f54ad42009-12-10 09:41:52 +00007893 }
7894 F.done();
7895 } else {
7896 assert(IsInstantiation && "no scope in non-instantiation");
7897 assert(CurContext->isRecord() && "scope not record in instantiation");
7898 LookupQualifiedName(Previous, CurContext);
7899 }
7900
John McCall9f54ad42009-12-10 09:41:52 +00007901 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007902 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7903 SS, IdentLoc, Previous))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007904 return nullptr;
John McCall9f54ad42009-12-10 09:41:52 +00007905
7906 // Check for bad qualifiers.
Stephen Hines651f13c2014-04-23 16:59:28 -07007907 if (CheckUsingDeclQualifier(UsingLoc, SS, NameInfo, IdentLoc))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007908 return nullptr;
John McCalled976492009-12-04 22:46:56 +00007909
John McCallaf8e6ed2009-11-12 03:15:40 +00007910 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007911 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007912 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007913 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007914 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007915 // FIXME: not all declaration name kinds are legal here
7916 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7917 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007918 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007919 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007920 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007921 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7922 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007923 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007924 D->setAccess(AS);
7925 CurContext->addDecl(D);
7926 return D;
Anders Carlsson550b14b2009-08-28 05:49:21 +00007927 }
John McCalled976492009-12-04 22:46:56 +00007928
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007929 auto Build = [&](bool Invalid) {
7930 UsingDecl *UD =
7931 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, NameInfo,
7932 HasTypenameKeyword);
7933 UD->setAccess(AS);
7934 CurContext->addDecl(UD);
7935 UD->setInvalidDecl(Invalid);
John McCall604e7f12009-12-08 07:46:18 +00007936 return UD;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007937 };
7938 auto BuildInvalid = [&]{ return Build(true); };
7939 auto BuildValid = [&]{ return Build(false); };
7940
7941 if (RequireCompleteDeclContext(SS, LookupContext))
7942 return BuildInvalid();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007943
Richard Smithc5a89a12012-04-02 01:30:27 +00007944 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007945 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007946 UsingDecl *UD = BuildValid();
7947 CheckInheritingConstructorUsingDecl(UD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007948 return UD;
7949 }
7950
7951 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007952
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007953 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007954
John McCall604e7f12009-12-08 07:46:18 +00007955 // Unlike most lookups, we don't always want to hide tag
7956 // declarations: tag names are visible through the using declaration
7957 // even if hidden by ordinary names, *except* in a dependent context
7958 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007959 if (!IsInstantiation)
7960 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007961
John McCallb9abd8722012-04-07 03:04:20 +00007962 // For the purposes of this lookup, we have a base object type
7963 // equal to that of the current context.
7964 if (CurContext->isRecord()) {
7965 R.setBaseObjectType(
7966 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7967 }
7968
John McCalla24dc2e2009-11-17 02:14:36 +00007969 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007970
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007971 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007972 if (R.empty()) {
Stephen Hines176edba2014-12-01 14:53:08 -08007973 if (TypoCorrection Corrected = CorrectTypo(
7974 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
7975 llvm::make_unique<UsingValidatorCCC>(
7976 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
7977 dyn_cast<CXXRecordDecl>(CurContext)),
7978 CTK_ErrorRecovery)) {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007979 // We reject any correction for which ND would be NULL.
7980 NamedDecl *ND = Corrected.getCorrectionDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007981
Richard Smith2d670972013-08-17 00:46:16 +00007982 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007983 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007984 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7985 << NameInfo.getName() << LookupContext << 0
7986 << SS.getRange());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007987
7988 // If we corrected to an inheriting constructor, handle it as one.
7989 auto *RD = dyn_cast<CXXRecordDecl>(ND);
7990 if (RD && RD->isInjectedClassName()) {
7991 // Fix up the information we'll use to build the using declaration.
7992 if (Corrected.WillReplaceSpecifier()) {
7993 NestedNameSpecifierLocBuilder Builder;
7994 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
7995 QualifierLoc.getSourceRange());
7996 QualifierLoc = Builder.getWithLocInContext(Context);
7997 }
7998
7999 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
8000 Context.getCanonicalType(Context.getRecordType(RD))));
8001 NameInfo.setNamedTypeInfo(nullptr);
8002
8003 // Build it and process it as an inheriting constructor.
8004 UsingDecl *UD = BuildValid();
8005 CheckInheritingConstructorUsingDecl(UD);
8006 return UD;
8007 }
8008
8009 // FIXME: Pick up all the declarations if we found an overloaded function.
8010 R.setLookupName(Corrected.getCorrection());
8011 R.addDecl(ND);
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00008012 } else {
Richard Smith2d670972013-08-17 00:46:16 +00008013 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00008014 << NameInfo.getName() << LookupContext << SS.getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008015 return BuildInvalid();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00008016 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00008017 }
8018
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008019 if (R.isAmbiguous())
8020 return BuildInvalid();
Mike Stump1eb44332009-09-09 15:08:12 +00008021
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008022 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00008023 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00008024 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00008025 Diag(IdentLoc, diag::err_using_typename_non_type);
8026 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8027 Diag((*I)->getUnderlyingDecl()->getLocation(),
8028 diag::note_using_decl_target);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008029 return BuildInvalid();
John McCall7ba107a2009-11-18 02:36:19 +00008030 }
8031 } else {
8032 // If we asked for a non-typename and we got a type, error out,
8033 // but only if this is an instantiation of an unresolved using
8034 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00008035 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00008036 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
8037 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008038 return BuildInvalid();
John McCall7ba107a2009-11-18 02:36:19 +00008039 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00008040 }
8041
Anders Carlsson73b39cf2009-08-28 03:35:18 +00008042 // C++0x N2914 [namespace.udecl]p6:
8043 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00008044 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00008045 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
8046 << SS.getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008047 return BuildInvalid();
Anders Carlsson73b39cf2009-08-28 03:35:18 +00008048 }
Mike Stump1eb44332009-09-09 15:08:12 +00008049
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008050 UsingDecl *UD = BuildValid();
John McCall9f54ad42009-12-10 09:41:52 +00008051 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008052 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithf06a28932013-10-23 02:17:46 +00008053 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
8054 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall9f54ad42009-12-10 09:41:52 +00008055 }
John McCall9488ea12009-11-17 05:59:44 +00008056
8057 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00008058}
8059
Sebastian Redlf677ea32011-02-05 19:23:19 +00008060/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00008061bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008062 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00008063
Douglas Gregordc355712011-02-25 00:36:19 +00008064 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008065 assert(SourceType &&
8066 "Using decl naming constructor doesn't have type in scope spec.");
8067 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
8068
8069 // Check whether the named type is a direct base class.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008070 bool AnyDependentBases = false;
8071 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
8072 AnyDependentBases);
8073 if (!Base && !AnyDependentBases) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008074 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00008075 diag::err_using_decl_constructor_not_in_direct_base)
8076 << UD->getNameInfo().getSourceRange()
8077 << QualType(SourceType, 0) << TargetClass;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008078 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008079 return true;
8080 }
8081
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008082 if (Base)
8083 Base->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008084
8085 return false;
8086}
8087
John McCall9f54ad42009-12-10 09:41:52 +00008088/// Checks that the given using declaration is not an invalid
8089/// redeclaration. Note that this is checking only for the using decl
8090/// itself, not for any ill-formedness among the UsingShadowDecls.
8091bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008092 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00008093 const CXXScopeSpec &SS,
8094 SourceLocation NameLoc,
8095 const LookupResult &Prev) {
8096 // C++03 [namespace.udecl]p8:
8097 // C++0x [namespace.udecl]p10:
8098 // A using-declaration is a declaration and can therefore be used
8099 // repeatedly where (and only where) multiple declarations are
8100 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00008101 //
John McCall8a726212010-11-29 18:01:58 +00008102 // That's in non-member contexts.
8103 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00008104 return false;
8105
Stephen Hines651f13c2014-04-23 16:59:28 -07008106 NestedNameSpecifier *Qual = SS.getScopeRep();
John McCall9f54ad42009-12-10 09:41:52 +00008107
8108 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
8109 NamedDecl *D = *I;
8110
8111 bool DTypename;
8112 NestedNameSpecifier *DQual;
8113 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008114 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00008115 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00008116 } else if (UnresolvedUsingValueDecl *UD
8117 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
8118 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00008119 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00008120 } else if (UnresolvedUsingTypenameDecl *UD
8121 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
8122 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00008123 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00008124 } else continue;
8125
8126 // using decls differ if one says 'typename' and the other doesn't.
8127 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00008128 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00008129
8130 // using decls differ if they name different scopes (but note that
8131 // template instantiation can cause this check to trigger when it
8132 // didn't before instantiation).
8133 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
8134 Context.getCanonicalNestedNameSpecifier(DQual))
8135 continue;
8136
8137 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00008138 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00008139 return true;
8140 }
8141
8142 return false;
8143}
8144
John McCall604e7f12009-12-08 07:46:18 +00008145
John McCalled976492009-12-04 22:46:56 +00008146/// Checks that the given nested-name qualifier used in a using decl
8147/// in the current context is appropriately related to the current
8148/// scope. If an error is found, diagnoses it and returns true.
8149bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
8150 const CXXScopeSpec &SS,
Stephen Hines651f13c2014-04-23 16:59:28 -07008151 const DeclarationNameInfo &NameInfo,
John McCalled976492009-12-04 22:46:56 +00008152 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00008153 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00008154
John McCall604e7f12009-12-08 07:46:18 +00008155 if (!CurContext->isRecord()) {
8156 // C++03 [namespace.udecl]p3:
8157 // C++0x [namespace.udecl]p8:
8158 // A using-declaration for a class member shall be a member-declaration.
8159
8160 // If we weren't able to compute a valid scope, it must be a
8161 // dependent class scope.
8162 if (!NamedContext || NamedContext->isRecord()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07008163 auto *RD = dyn_cast<CXXRecordDecl>(NamedContext);
8164 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008165 RD = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07008166
John McCall604e7f12009-12-08 07:46:18 +00008167 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
8168 << SS.getRange();
Stephen Hines651f13c2014-04-23 16:59:28 -07008169
8170 // If we have a complete, non-dependent source type, try to suggest a
8171 // way to get the same effect.
8172 if (!RD)
8173 return true;
8174
8175 // Find what this using-declaration was referring to.
8176 LookupResult R(*this, NameInfo, LookupOrdinaryName);
8177 R.setHideTags(false);
8178 R.suppressDiagnostics();
8179 LookupQualifiedName(R, RD);
8180
8181 if (R.getAsSingle<TypeDecl>()) {
8182 if (getLangOpts().CPlusPlus11) {
8183 // Convert 'using X::Y;' to 'using Y = X::Y;'.
8184 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
8185 << 0 // alias declaration
8186 << FixItHint::CreateInsertion(SS.getBeginLoc(),
8187 NameInfo.getName().getAsString() +
8188 " = ");
8189 } else {
8190 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
8191 SourceLocation InsertLoc =
8192 PP.getLocForEndOfToken(NameInfo.getLocEnd());
8193 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
8194 << 1 // typedef declaration
8195 << FixItHint::CreateReplacement(UsingLoc, "typedef")
8196 << FixItHint::CreateInsertion(
8197 InsertLoc, " " + NameInfo.getName().getAsString());
8198 }
8199 } else if (R.getAsSingle<VarDecl>()) {
8200 // Don't provide a fixit outside C++11 mode; we don't want to suggest
8201 // repeating the type of the static data member here.
8202 FixItHint FixIt;
8203 if (getLangOpts().CPlusPlus11) {
8204 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
8205 FixIt = FixItHint::CreateReplacement(
8206 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
8207 }
8208
8209 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
8210 << 2 // reference declaration
8211 << FixIt;
8212 }
John McCall604e7f12009-12-08 07:46:18 +00008213 return true;
8214 }
8215
8216 // Otherwise, everything is known to be fine.
8217 return false;
8218 }
8219
8220 // The current scope is a record.
8221
8222 // If the named context is dependent, we can't decide much.
8223 if (!NamedContext) {
8224 // FIXME: in C++0x, we can diagnose if we can prove that the
8225 // nested-name-specifier does not refer to a base class, which is
8226 // still possible in some cases.
8227
8228 // Otherwise we have to conservatively report that things might be
8229 // okay.
8230 return false;
8231 }
8232
8233 if (!NamedContext->isRecord()) {
8234 // Ideally this would point at the last name in the specifier,
8235 // but we don't have that level of source info.
8236 Diag(SS.getRange().getBegin(),
8237 diag::err_using_decl_nested_name_specifier_is_not_class)
Stephen Hines651f13c2014-04-23 16:59:28 -07008238 << SS.getScopeRep() << SS.getRange();
John McCall604e7f12009-12-08 07:46:18 +00008239 return true;
8240 }
8241
Douglas Gregor6fb07292010-12-21 07:41:49 +00008242 if (!NamedContext->isDependentContext() &&
8243 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
8244 return true;
8245
Richard Smith80ad52f2013-01-02 11:42:31 +00008246 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00008247 // C++0x [namespace.udecl]p3:
8248 // In a using-declaration used as a member-declaration, the
8249 // nested-name-specifier shall name a base class of the class
8250 // being defined.
8251
8252 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
8253 cast<CXXRecordDecl>(NamedContext))) {
8254 if (CurContext == NamedContext) {
8255 Diag(NameLoc,
8256 diag::err_using_decl_nested_name_specifier_is_current_class)
8257 << SS.getRange();
8258 return true;
8259 }
8260
8261 Diag(SS.getRange().getBegin(),
8262 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Stephen Hines651f13c2014-04-23 16:59:28 -07008263 << SS.getScopeRep()
John McCall604e7f12009-12-08 07:46:18 +00008264 << cast<CXXRecordDecl>(CurContext)
8265 << SS.getRange();
8266 return true;
8267 }
8268
8269 return false;
8270 }
8271
8272 // C++03 [namespace.udecl]p4:
8273 // A using-declaration used as a member-declaration shall refer
8274 // to a member of a base class of the class being defined [etc.].
8275
8276 // Salient point: SS doesn't have to name a base class as long as
8277 // lookup only finds members from base classes. Therefore we can
8278 // diagnose here only if we can prove that that can't happen,
8279 // i.e. if the class hierarchies provably don't intersect.
8280
8281 // TODO: it would be nice if "definitely valid" results were cached
8282 // in the UsingDecl and UsingShadowDecl so that these checks didn't
8283 // need to be repeated.
8284
8285 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00008286 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00008287
8288 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
8289 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8290 Data->Bases.insert(Base);
8291 return true;
8292 }
8293
8294 bool hasDependentBases(const CXXRecordDecl *Class) {
8295 return !Class->forallBases(collect, this);
8296 }
8297
8298 /// Returns true if the base is dependent or is one of the
8299 /// accumulated base classes.
8300 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
8301 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
8302 return !Data->Bases.count(Base);
8303 }
8304
8305 bool mightShareBases(const CXXRecordDecl *Class) {
8306 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
8307 }
8308 };
8309
8310 UserData Data;
8311
8312 // Returns false if we find a dependent base.
8313 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
8314 return false;
8315
8316 // Returns false if the class has a dependent base or if it or one
8317 // of its bases is present in the base set of the current context.
8318 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
8319 return false;
8320
8321 Diag(SS.getRange().getBegin(),
8322 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Stephen Hines651f13c2014-04-23 16:59:28 -07008323 << SS.getScopeRep()
John McCall604e7f12009-12-08 07:46:18 +00008324 << cast<CXXRecordDecl>(CurContext)
8325 << SS.getRange();
8326
8327 return true;
John McCalled976492009-12-04 22:46:56 +00008328}
8329
Richard Smith162e1c12011-04-15 14:24:37 +00008330Decl *Sema::ActOnAliasDeclaration(Scope *S,
8331 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00008332 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00008333 SourceLocation UsingLoc,
8334 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00008335 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00008336 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00008337 // Skip up to the relevant declaration scope.
8338 while (S->getFlags() & Scope::TemplateParamScope)
8339 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00008340 assert((S->getFlags() & Scope::DeclScope) &&
8341 "got alias-declaration outside of declaration scope");
8342
8343 if (Type.isInvalid())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008344 return nullptr;
Richard Smith162e1c12011-04-15 14:24:37 +00008345
8346 bool Invalid = false;
8347 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008348 TypeSourceInfo *TInfo = nullptr;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00008349 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00008350
8351 if (DiagnoseClassNameShadow(CurContext, NameInfo))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008352 return nullptr;
Richard Smith162e1c12011-04-15 14:24:37 +00008353
8354 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00008355 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00008356 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00008357 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8358 TInfo->getTypeLoc().getBeginLoc());
8359 }
Richard Smith162e1c12011-04-15 14:24:37 +00008360
8361 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
8362 LookupName(Previous, S);
8363
8364 // Warn about shadowing the name of a template parameter.
8365 if (Previous.isSingleResult() &&
8366 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00008367 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00008368 Previous.clear();
8369 }
8370
8371 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
8372 "name in alias declaration must be an identifier");
8373 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
8374 Name.StartLocation,
8375 Name.Identifier, TInfo);
8376
8377 NewTD->setAccess(AS);
8378
8379 if (Invalid)
8380 NewTD->setInvalidDecl();
8381
Richard Smith6b3d3e52013-02-20 19:22:51 +00008382 ProcessDeclAttributeList(S, NewTD, AttrList);
8383
Richard Smith3e4c6c42011-05-05 21:57:07 +00008384 CheckTypedefForVariablyModifiedType(S, NewTD);
8385 Invalid |= NewTD->isInvalidDecl();
8386
Richard Smith162e1c12011-04-15 14:24:37 +00008387 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00008388
8389 NamedDecl *NewND;
8390 if (TemplateParamLists.size()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008391 TypeAliasTemplateDecl *OldDecl = nullptr;
8392 TemplateParameterList *OldTemplateParams = nullptr;
Richard Smith3e4c6c42011-05-05 21:57:07 +00008393
8394 if (TemplateParamLists.size() != 1) {
8395 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008396 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
8397 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00008398 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008399 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00008400
8401 // Only consider previous declarations in the same scope.
8402 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
8403 /*ExplicitInstantiationOrSpecialization*/false);
8404 if (!Previous.empty()) {
8405 Redeclaration = true;
8406
8407 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
8408 if (!OldDecl && !Invalid) {
8409 Diag(UsingLoc, diag::err_redefinition_different_kind)
8410 << Name.Identifier;
8411
8412 NamedDecl *OldD = Previous.getRepresentativeDecl();
8413 if (OldD->getLocation().isValid())
8414 Diag(OldD->getLocation(), diag::note_previous_definition);
8415
8416 Invalid = true;
8417 }
8418
8419 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
8420 if (TemplateParameterListsAreEqual(TemplateParams,
8421 OldDecl->getTemplateParameters(),
8422 /*Complain=*/true,
8423 TPL_TemplateMatch))
8424 OldTemplateParams = OldDecl->getTemplateParameters();
8425 else
8426 Invalid = true;
8427
8428 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
8429 if (!Invalid &&
8430 !Context.hasSameType(OldTD->getUnderlyingType(),
8431 NewTD->getUnderlyingType())) {
8432 // FIXME: The C++0x standard does not clearly say this is ill-formed,
8433 // but we can't reasonably accept it.
8434 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
8435 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
8436 if (OldTD->getLocation().isValid())
8437 Diag(OldTD->getLocation(), diag::note_previous_definition);
8438 Invalid = true;
8439 }
8440 }
8441 }
8442
8443 // Merge any previous default template arguments into our parameters,
8444 // and check the parameter list.
8445 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
8446 TPC_TypeAliasTemplate))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008447 return nullptr;
Richard Smith3e4c6c42011-05-05 21:57:07 +00008448
8449 TypeAliasTemplateDecl *NewDecl =
8450 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
8451 Name.Identifier, TemplateParams,
8452 NewTD);
Stephen Hines176edba2014-12-01 14:53:08 -08008453 NewTD->setDescribedAliasTemplate(NewDecl);
Richard Smith3e4c6c42011-05-05 21:57:07 +00008454
8455 NewDecl->setAccess(AS);
8456
8457 if (Invalid)
8458 NewDecl->setInvalidDecl();
8459 else if (OldDecl)
Rafael Espindolabc650912013-10-17 15:37:26 +00008460 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3e4c6c42011-05-05 21:57:07 +00008461
8462 NewND = NewDecl;
8463 } else {
8464 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
8465 NewND = NewTD;
8466 }
Richard Smith162e1c12011-04-15 14:24:37 +00008467
8468 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00008469 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00008470
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00008471 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00008472 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00008473}
8474
Stephen Hines176edba2014-12-01 14:53:08 -08008475Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
8476 SourceLocation AliasLoc,
8477 IdentifierInfo *Alias, CXXScopeSpec &SS,
8478 SourceLocation IdentLoc,
8479 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00008480
Anders Carlsson81c85c42009-03-28 23:53:49 +00008481 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00008482 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
8483 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00008484
John McCalla24dc2e2009-11-17 02:14:36 +00008485 if (R.isAmbiguous())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008486 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00008487
John McCallf36e02d2009-10-09 21:13:30 +00008488 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00008489 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00008490 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008491 return nullptr;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00008492 }
Anders Carlsson5721c682009-03-28 06:42:02 +00008493 }
Stephen Hines176edba2014-12-01 14:53:08 -08008494 assert(!R.isAmbiguous() && !R.empty());
8495
8496 // Check if we have a previous declaration with the same name.
8497 NamedDecl *PrevDecl = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
8498 ForRedeclaration);
8499 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
8500 PrevDecl = nullptr;
8501
8502 NamedDecl *ND = R.getFoundDecl();
8503
8504 if (PrevDecl) {
8505 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
8506 // We already have an alias with the same name that points to the same
8507 // namespace; check that it matches.
8508 if (!AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
8509 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
8510 << Alias;
8511 Diag(PrevDecl->getLocation(), diag::note_previous_namespace_alias)
8512 << AD->getNamespace();
8513 return nullptr;
8514 }
8515 } else {
8516 unsigned DiagID = isa<NamespaceDecl>(PrevDecl)
8517 ? diag::err_redefinition
8518 : diag::err_redefinition_different_kind;
8519 Diag(AliasLoc, DiagID) << Alias;
8520 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8521 return nullptr;
8522 }
8523 }
8524
8525 // The use of a nested name specifier may trigger deprecation warnings.
8526 DiagnoseUseOfDecl(ND, IdentLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00008527
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008528 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00008529 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00008530 Alias, SS.getWithLocInContext(Context),
Stephen Hines176edba2014-12-01 14:53:08 -08008531 IdentLoc, ND);
8532 if (PrevDecl)
8533 AliasDecl->setPreviousDecl(cast<NamespaceAliasDecl>(PrevDecl));
Mike Stump1eb44332009-09-09 15:08:12 +00008534
John McCall3dbd3d52010-02-16 06:53:13 +00008535 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00008536 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00008537}
8538
Sean Hunt001cad92011-05-10 00:49:42 +00008539Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008540Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
8541 CXXMethodDecl *MD) {
8542 CXXRecordDecl *ClassDecl = MD->getParent();
8543
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008544 // C++ [except.spec]p14:
8545 // An implicitly declared special member function (Clause 12) shall have an
8546 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008547 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008548 if (ClassDecl->isInvalidDecl())
8549 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008550
Sebastian Redl60618fa2011-03-12 11:50:43 +00008551 // Direct base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008552 for (const auto &B : ClassDecl->bases()) {
8553 if (B.isVirtual()) // Handled below.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008554 continue;
8555
Stephen Hines651f13c2014-04-23 16:59:28 -07008556 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor18274032010-07-03 00:47:00 +00008557 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00008558 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8559 // If this is a deleted function, add it anyway. This might be conformant
8560 // with the standard. This might not. I'm not sure. It might not matter.
8561 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008562 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008563 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008564 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008565
8566 // Virtual base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008567 for (const auto &B : ClassDecl->vbases()) {
8568 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Douglas Gregor18274032010-07-03 00:47:00 +00008569 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00008570 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8571 // If this is a deleted function, add it anyway. This might be conformant
8572 // with the standard. This might not. I'm not sure. It might not matter.
8573 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008574 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008575 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008576 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008577
8578 // Field constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008579 for (const auto *F : ClassDecl->fields()) {
Richard Smith7a614d82011-06-11 17:19:42 +00008580 if (F->hasInClassInitializer()) {
8581 if (Expr *E = F->getInClassInitializer())
8582 ExceptSpec.CalledExpr(E);
Richard Smith7a614d82011-06-11 17:19:42 +00008583 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00008584 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00008585 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8586 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8587 // If this is a deleted function, add it anyway. This might be conformant
8588 // with the standard. This might not. I'm not sure. It might not matter.
8589 // In particular, the problem is that this function never gets called. It
8590 // might just be ill-formed because this function attempts to refer to
8591 // a deleted function here.
8592 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008593 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00008594 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008595 }
John McCalle23cf432010-12-14 08:05:40 +00008596
Sean Hunt001cad92011-05-10 00:49:42 +00008597 return ExceptSpec;
8598}
8599
Richard Smith07b0fdc2013-03-18 21:12:30 +00008600Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00008601Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
8602 CXXRecordDecl *ClassDecl = CD->getParent();
8603
8604 // C++ [except.spec]p14:
8605 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00008606 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00008607 if (ClassDecl->isInvalidDecl())
8608 return ExceptSpec;
8609
8610 // Inherited constructor.
8611 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8612 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8613 // FIXME: Copying or moving the parameters could add extra exceptions to the
8614 // set, as could the default arguments for the inherited constructor. This
8615 // will be addressed when we implement the resolution of core issue 1351.
8616 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8617
8618 // Direct base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008619 for (const auto &B : ClassDecl->bases()) {
8620 if (B.isVirtual()) // Handled below.
Richard Smith0b0ca472013-04-10 06:11:48 +00008621 continue;
8622
Stephen Hines651f13c2014-04-23 16:59:28 -07008623 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smith0b0ca472013-04-10 06:11:48 +00008624 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8625 if (BaseClassDecl == InheritedDecl)
8626 continue;
8627 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8628 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008629 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smith0b0ca472013-04-10 06:11:48 +00008630 }
8631 }
8632
8633 // Virtual base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008634 for (const auto &B : ClassDecl->vbases()) {
8635 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Richard Smith0b0ca472013-04-10 06:11:48 +00008636 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8637 if (BaseClassDecl == InheritedDecl)
8638 continue;
8639 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8640 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -07008641 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Richard Smith0b0ca472013-04-10 06:11:48 +00008642 }
8643 }
8644
8645 // Field constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07008646 for (const auto *F : ClassDecl->fields()) {
Richard Smith0b0ca472013-04-10 06:11:48 +00008647 if (F->hasInClassInitializer()) {
8648 if (Expr *E = F->getInClassInitializer())
8649 ExceptSpec.CalledExpr(E);
Richard Smith0b0ca472013-04-10 06:11:48 +00008650 } else if (const RecordType *RecordTy
8651 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8652 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8653 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8654 if (Constructor)
8655 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8656 }
8657 }
8658
Richard Smith07b0fdc2013-03-18 21:12:30 +00008659 return ExceptSpec;
8660}
8661
Richard Smithafb49182012-11-29 01:34:07 +00008662namespace {
8663/// RAII object to register a special member as being currently declared.
8664struct DeclaringSpecialMember {
8665 Sema &S;
8666 Sema::SpecialMemberDecl D;
8667 bool WasAlreadyBeingDeclared;
8668
8669 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8670 : S(S), D(RD, CSM) {
Stephen Hines176edba2014-12-01 14:53:08 -08008671 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
Richard Smithafb49182012-11-29 01:34:07 +00008672 if (WasAlreadyBeingDeclared)
8673 // This almost never happens, but if it does, ensure that our cache
8674 // doesn't contain a stale result.
8675 S.SpecialMemberCache.clear();
8676
8677 // FIXME: Register a note to be produced if we encounter an error while
8678 // declaring the special member.
8679 }
8680 ~DeclaringSpecialMember() {
8681 if (!WasAlreadyBeingDeclared)
8682 S.SpecialMembersBeingDeclared.erase(D);
8683 }
8684
8685 /// \brief Are we already trying to declare this special member?
8686 bool isAlreadyBeingDeclared() const {
8687 return WasAlreadyBeingDeclared;
8688 }
8689};
8690}
8691
Sean Hunt001cad92011-05-10 00:49:42 +00008692CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8693 CXXRecordDecl *ClassDecl) {
8694 // C++ [class.ctor]p5:
8695 // A default constructor for a class X is a constructor of class X
8696 // that can be called without an argument. If there is no
8697 // user-declared constructor for class X, a default constructor is
8698 // implicitly declared. An implicitly-declared default constructor
8699 // is an inline public member of its class.
Stephen Hines176edba2014-12-01 14:53:08 -08008700 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00008701 "Should not build implicit default constructor!");
8702
Richard Smithafb49182012-11-29 01:34:07 +00008703 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8704 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008705 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +00008706
Richard Smith7756afa2012-06-10 05:43:50 +00008707 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8708 CXXDefaultConstructor,
8709 false);
8710
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008711 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00008712 CanQualType ClassType
8713 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008714 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008715 DeclarationName Name
8716 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008717 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00008718 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008719 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
8720 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
8721 /*isImplicitlyDeclared=*/true, Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00008722 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00008723 DefaultCon->setDefaulted();
Stephen Hines176edba2014-12-01 14:53:08 -08008724
8725 if (getLangOpts().CUDA) {
8726 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
8727 DefaultCon,
8728 /* ConstRHS */ false,
8729 /* Diagnose */ false);
8730 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008731
8732 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008733 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008734 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008735
Richard Smithbc2a35d2012-12-08 08:32:28 +00008736 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8737 // constructors is easy to compute.
8738 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8739
8740 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008741 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008742
Douglas Gregor18274032010-07-03 00:47:00 +00008743 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00008744 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00008745
Douglas Gregor23c94db2010-07-02 17:43:08 +00008746 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00008747 PushOnScopeChains(DefaultCon, S, false);
8748 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00008749
Douglas Gregor32df23e2010-07-01 22:02:46 +00008750 return DefaultCon;
8751}
8752
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008753void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8754 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00008755 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008756 !Constructor->doesThisDeclarationHaveABody() &&
8757 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00008758 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008759
Anders Carlssonf6513ed2010-04-23 16:04:08 +00008760 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00008761 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00008762
Eli Friedman9a14db32012-10-18 20:14:08 +00008763 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008764 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00008765 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008766 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008767 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00008768 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00008769 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008770 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00008771 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008772
Stephen Hines176edba2014-12-01 14:53:08 -08008773 // The exception specification is needed because we are defining the
8774 // function.
8775 ResolveExceptionSpec(CurrentLocation,
8776 Constructor->getType()->castAs<FunctionProtoType>());
8777
Stephen Hinesc568f1e2014-07-21 00:47:37 -07008778 SourceLocation Loc = Constructor->getLocEnd().isValid()
8779 ? Constructor->getLocEnd()
8780 : Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008781 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008782
Eli Friedman86164e82013-09-05 00:02:25 +00008783 Constructor->markUsed(Context);
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008784 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008785
8786 if (ASTMutationListener *L = getASTMutationListener()) {
8787 L->CompletedImplicitDefinition(Constructor);
8788 }
Richard Trieu858d2ba2013-10-25 00:56:00 +00008789
8790 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008791}
8792
Richard Smith7a614d82011-06-11 17:19:42 +00008793void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Toker08235662013-10-18 05:54:19 +00008794 // Perform any delayed checks on exception specifications.
8795 CheckDelayedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00008796}
8797
Richard Smith4841ca52013-04-10 05:48:59 +00008798namespace {
8799/// Information on inheriting constructors to declare.
8800class InheritingConstructorInfo {
8801public:
8802 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8803 : SemaRef(SemaRef), Derived(Derived) {
8804 // Mark the constructors that we already have in the derived class.
8805 //
8806 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8807 // unless there is a user-declared constructor with the same signature in
8808 // the class where the using-declaration appears.
8809 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8810 }
8811
8812 void inheritAll(CXXRecordDecl *RD) {
8813 visitAll(RD, &InheritingConstructorInfo::inherit);
8814 }
8815
8816private:
8817 /// Information about an inheriting constructor.
8818 struct InheritingConstructor {
8819 InheritingConstructor()
Stephen Hines6bcf27b2014-05-29 04:14:42 -07008820 : DeclaredInDerived(false), BaseCtor(nullptr), DerivedCtor(nullptr) {}
Richard Smith4841ca52013-04-10 05:48:59 +00008821
8822 /// If \c true, a constructor with this signature is already declared
8823 /// in the derived class.
8824 bool DeclaredInDerived;
8825
8826 /// The constructor which is inherited.
8827 const CXXConstructorDecl *BaseCtor;
8828
8829 /// The derived constructor we declared.
8830 CXXConstructorDecl *DerivedCtor;
8831 };
8832
8833 /// Inheriting constructors with a given canonical type. There can be at
8834 /// most one such non-template constructor, and any number of templated
8835 /// constructors.
8836 struct InheritingConstructorsForType {
8837 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008838 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8839 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008840
8841 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8842 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8843 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8844 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8845 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8846 false, S.TPL_TemplateMatch))
8847 return Templates[I].second;
8848 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8849 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008850 }
Richard Smith4841ca52013-04-10 05:48:59 +00008851
8852 return NonTemplate;
8853 }
8854 };
8855
8856 /// Get or create the inheriting constructor record for a constructor.
8857 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8858 QualType CtorType) {
8859 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8860 .getEntry(SemaRef, Ctor);
8861 }
8862
8863 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8864
8865 /// Process all constructors for a class.
8866 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
Stephen Hines651f13c2014-04-23 16:59:28 -07008867 for (const auto *Ctor : RD->ctors())
8868 (this->*Callback)(Ctor);
Richard Smith4841ca52013-04-10 05:48:59 +00008869 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8870 I(RD->decls_begin()), E(RD->decls_end());
8871 I != E; ++I) {
8872 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8873 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8874 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008875 }
8876 }
Richard Smith4841ca52013-04-10 05:48:59 +00008877
8878 /// Note that a constructor (or constructor template) was declared in Derived.
8879 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8880 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8881 }
8882
8883 /// Inherit a single constructor.
8884 void inherit(const CXXConstructorDecl *Ctor) {
8885 const FunctionProtoType *CtorType =
8886 Ctor->getType()->castAs<FunctionProtoType>();
Stephen Hines176edba2014-12-01 14:53:08 -08008887 ArrayRef<QualType> ArgTypes = CtorType->getParamTypes();
Richard Smith4841ca52013-04-10 05:48:59 +00008888 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8889
8890 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8891
8892 // Core issue (no number yet): the ellipsis is always discarded.
8893 if (EPI.Variadic) {
8894 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8895 SemaRef.Diag(Ctor->getLocation(),
8896 diag::note_using_decl_constructor_ellipsis);
8897 EPI.Variadic = false;
8898 }
8899
8900 // Declare a constructor for each number of parameters.
8901 //
8902 // C++11 [class.inhctor]p1:
8903 // The candidate set of inherited constructors from the class X named in
8904 // the using-declaration consists of [... modulo defects ...] for each
8905 // constructor or constructor template of X, the set of constructors or
8906 // constructor templates that results from omitting any ellipsis parameter
8907 // specification and successively omitting parameters with a default
8908 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008909 unsigned MinParams = minParamsToInherit(Ctor);
8910 unsigned Params = Ctor->getNumParams();
8911 if (Params >= MinParams) {
8912 do
8913 declareCtor(UsingLoc, Ctor,
8914 SemaRef.Context.getFunctionType(
Stephen Hines651f13c2014-04-23 16:59:28 -07008915 Ctor->getReturnType(), ArgTypes.slice(0, Params), EPI));
Richard Smith987c0302013-04-17 19:00:52 +00008916 while (Params > MinParams &&
8917 Ctor->getParamDecl(--Params)->hasDefaultArg());
8918 }
Richard Smith4841ca52013-04-10 05:48:59 +00008919 }
8920
8921 /// Find the using-declaration which specified that we should inherit the
8922 /// constructors of \p Base.
8923 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8924 // No fancy lookup required; just look for the base constructor name
8925 // directly within the derived class.
8926 ASTContext &Context = SemaRef.Context;
8927 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8928 Context.getCanonicalType(Context.getRecordType(Base)));
8929 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8930 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8931 }
8932
8933 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8934 // C++11 [class.inhctor]p3:
8935 // [F]or each constructor template in the candidate set of inherited
8936 // constructors, a constructor template is implicitly declared
8937 if (Ctor->getDescribedFunctionTemplate())
8938 return 0;
8939
8940 // For each non-template constructor in the candidate set of inherited
8941 // constructors other than a constructor having no parameters or a
8942 // copy/move constructor having a single parameter, a constructor is
8943 // implicitly declared [...]
8944 if (Ctor->getNumParams() == 0)
8945 return 1;
8946 if (Ctor->isCopyOrMoveConstructor())
8947 return 2;
8948
8949 // Per discussion on core reflector, never inherit a constructor which
8950 // would become a default, copy, or move constructor of Derived either.
8951 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8952 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8953 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8954 }
8955
8956 /// Declare a single inheriting constructor, inheriting the specified
8957 /// constructor, with the given type.
8958 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8959 QualType DerivedType) {
8960 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8961
8962 // C++11 [class.inhctor]p3:
8963 // ... a constructor is implicitly declared with the same constructor
8964 // characteristics unless there is a user-declared constructor with
8965 // the same signature in the class where the using-declaration appears
8966 if (Entry.DeclaredInDerived)
8967 return;
8968
8969 // C++11 [class.inhctor]p7:
8970 // If two using-declarations declare inheriting constructors with the
8971 // same signature, the program is ill-formed
8972 if (Entry.DerivedCtor) {
8973 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8974 // Only diagnose this once per constructor.
8975 if (Entry.DerivedCtor->isInvalidDecl())
8976 return;
8977 Entry.DerivedCtor->setInvalidDecl();
8978
8979 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8980 SemaRef.Diag(BaseCtor->getLocation(),
8981 diag::note_using_decl_constructor_conflict_current_ctor);
8982 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8983 diag::note_using_decl_constructor_conflict_previous_ctor);
8984 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8985 diag::note_using_decl_constructor_conflict_previous_using);
8986 } else {
8987 // Core issue (no number): if the same inheriting constructor is
8988 // produced by multiple base class constructors from the same base
8989 // class, the inheriting constructor is defined as deleted.
8990 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8991 }
8992
8993 return;
8994 }
8995
8996 ASTContext &Context = SemaRef.Context;
8997 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8998 Context.getCanonicalType(Context.getRecordType(Derived)));
8999 DeclarationNameInfo NameInfo(Name, UsingLoc);
9000
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009001 TemplateParameterList *TemplateParams = nullptr;
Richard Smith4841ca52013-04-10 05:48:59 +00009002 if (const FunctionTemplateDecl *FTD =
9003 BaseCtor->getDescribedFunctionTemplate()) {
9004 TemplateParams = FTD->getTemplateParameters();
9005 // We're reusing template parameters from a different DeclContext. This
9006 // is questionable at best, but works out because the template depth in
9007 // both places is guaranteed to be 0.
9008 // FIXME: Rebuild the template parameters in the new context, and
9009 // transform the function type to refer to them.
9010 }
9011
9012 // Build type source info pointing at the using-declaration. This is
9013 // required by template instantiation.
9014 TypeSourceInfo *TInfo =
9015 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
9016 FunctionProtoTypeLoc ProtoLoc =
9017 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
9018
9019 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
9020 Context, Derived, UsingLoc, NameInfo, DerivedType,
9021 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
9022 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
9023
9024 // Build an unevaluated exception specification for this constructor.
9025 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
9026 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Stephen Hines176edba2014-12-01 14:53:08 -08009027 EPI.ExceptionSpec.Type = EST_Unevaluated;
9028 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
Stephen Hines651f13c2014-04-23 16:59:28 -07009029 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
9030 FPT->getParamTypes(), EPI));
Richard Smith4841ca52013-04-10 05:48:59 +00009031
9032 // Build the parameter declarations.
9033 SmallVector<ParmVarDecl *, 16> ParamDecls;
Stephen Hines651f13c2014-04-23 16:59:28 -07009034 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
Richard Smith4841ca52013-04-10 05:48:59 +00009035 TypeSourceInfo *TInfo =
Stephen Hines651f13c2014-04-23 16:59:28 -07009036 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
Richard Smith4841ca52013-04-10 05:48:59 +00009037 ParmVarDecl *PD = ParmVarDecl::Create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009038 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
9039 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
Richard Smith4841ca52013-04-10 05:48:59 +00009040 PD->setScopeInfo(0, I);
9041 PD->setImplicit();
9042 ParamDecls.push_back(PD);
Stephen Hines651f13c2014-04-23 16:59:28 -07009043 ProtoLoc.setParam(I, PD);
Richard Smith4841ca52013-04-10 05:48:59 +00009044 }
9045
9046 // Set up the new constructor.
9047 DerivedCtor->setAccess(BaseCtor->getAccess());
9048 DerivedCtor->setParams(ParamDecls);
9049 DerivedCtor->setInheritedConstructor(BaseCtor);
9050 if (BaseCtor->isDeleted())
9051 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
9052
9053 // If this is a constructor template, build the template declaration.
9054 if (TemplateParams) {
9055 FunctionTemplateDecl *DerivedTemplate =
9056 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
9057 TemplateParams, DerivedCtor);
9058 DerivedTemplate->setAccess(BaseCtor->getAccess());
9059 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
9060 Derived->addDecl(DerivedTemplate);
9061 } else {
9062 Derived->addDecl(DerivedCtor);
9063 }
9064
9065 Entry.BaseCtor = BaseCtor;
9066 Entry.DerivedCtor = DerivedCtor;
9067 }
9068
9069 Sema &SemaRef;
9070 CXXRecordDecl *Derived;
9071 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
9072 MapType Map;
9073};
9074}
9075
9076void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
9077 // Defer declaring the inheriting constructors until the class is
9078 // instantiated.
9079 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00009080 return;
9081
Richard Smith4841ca52013-04-10 05:48:59 +00009082 // Find base classes from which we might inherit constructors.
9083 SmallVector<CXXRecordDecl*, 4> InheritedBases;
Stephen Hines651f13c2014-04-23 16:59:28 -07009084 for (const auto &BaseIt : ClassDecl->bases())
9085 if (BaseIt.getInheritConstructors())
9086 InheritedBases.push_back(BaseIt.getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00009087
Richard Smith4841ca52013-04-10 05:48:59 +00009088 // Go no further if we're not inheriting any constructors.
9089 if (InheritedBases.empty())
9090 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00009091
Richard Smith4841ca52013-04-10 05:48:59 +00009092 // Declare the inherited constructors.
9093 InheritingConstructorInfo ICI(*this, ClassDecl);
9094 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
9095 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00009096}
9097
Richard Smith07b0fdc2013-03-18 21:12:30 +00009098void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
9099 CXXConstructorDecl *Constructor) {
9100 CXXRecordDecl *ClassDecl = Constructor->getParent();
9101 assert(Constructor->getInheritedConstructor() &&
9102 !Constructor->doesThisDeclarationHaveABody() &&
9103 !Constructor->isDeleted());
9104
9105 SynthesizedFunctionScope Scope(*this, Constructor);
9106 DiagnosticErrorTrap Trap(Diags);
9107 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
9108 Trap.hasErrorOccurred()) {
9109 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
9110 << Context.getTagDeclType(ClassDecl);
9111 Constructor->setInvalidDecl();
9112 return;
9113 }
9114
9115 SourceLocation Loc = Constructor->getLocation();
9116 Constructor->setBody(new (Context) CompoundStmt(Loc));
9117
Eli Friedman86164e82013-09-05 00:02:25 +00009118 Constructor->markUsed(Context);
Richard Smith07b0fdc2013-03-18 21:12:30 +00009119 MarkVTableUsed(CurrentLocation, ClassDecl);
9120
9121 if (ASTMutationListener *L = getASTMutationListener()) {
9122 L->CompletedImplicitDefinition(Constructor);
9123 }
9124}
9125
9126
Sean Huntcb45a0f2011-05-12 22:46:25 +00009127Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009128Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
9129 CXXRecordDecl *ClassDecl = MD->getParent();
9130
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009131 // C++ [except.spec]p14:
9132 // An implicitly declared special member function (Clause 12) shall have
9133 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00009134 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009135 if (ClassDecl->isInvalidDecl())
9136 return ExceptSpec;
9137
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009138 // Direct base-class destructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07009139 for (const auto &B : ClassDecl->bases()) {
9140 if (B.isVirtual()) // Handled below.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009141 continue;
9142
Stephen Hines651f13c2014-04-23 16:59:28 -07009143 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9144 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00009145 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009146 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00009147
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009148 // Virtual base-class destructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07009149 for (const auto &B : ClassDecl->vbases()) {
9150 if (const RecordType *BaseType = B.getType()->getAs<RecordType>())
9151 ExceptSpec.CalledDecl(B.getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00009152 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009153 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00009154
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009155 // Field destructors.
Stephen Hines651f13c2014-04-23 16:59:28 -07009156 for (const auto *F : ClassDecl->fields()) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009157 if (const RecordType *RecordTy
9158 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00009159 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00009160 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009161 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009162
Sean Huntcb45a0f2011-05-12 22:46:25 +00009163 return ExceptSpec;
9164}
9165
9166CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
9167 // C++ [class.dtor]p2:
9168 // If a class has no user-declared destructor, a destructor is
9169 // declared implicitly. An implicitly-declared destructor is an
9170 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00009171 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00009172
Richard Smithafb49182012-11-29 01:34:07 +00009173 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
9174 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009175 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +00009176
Douglas Gregor4923aa22010-07-02 20:37:36 +00009177 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009178 CanQualType ClassType
9179 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009180 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009181 DeclarationName Name
9182 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009183 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009184 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00009185 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009186 QualType(), nullptr, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00009187 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009188 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00009189 Destructor->setDefaulted();
Stephen Hines176edba2014-12-01 14:53:08 -08009190
9191 if (getLangOpts().CUDA) {
9192 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
9193 Destructor,
9194 /* ConstRHS */ false,
9195 /* Diagnose */ false);
9196 }
Richard Smithb9d0b762012-07-27 04:22:15 +00009197
9198 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00009199 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00009200 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009201
Richard Smithbc2a35d2012-12-08 08:32:28 +00009202 AddOverriddenMethods(ClassDecl, Destructor);
9203
9204 // We don't need to use SpecialMemberIsTrivial here; triviality for
9205 // destructors is easy to compute.
9206 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
9207
9208 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009209 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00009210
Douglas Gregor4923aa22010-07-02 20:37:36 +00009211 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00009212 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00009213
Douglas Gregor4923aa22010-07-02 20:37:36 +00009214 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00009215 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00009216 PushOnScopeChains(Destructor, S, false);
9217 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00009218
Douglas Gregorfabd43a2010-07-01 19:09:28 +00009219 return Destructor;
9220}
9221
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009222void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00009223 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00009224 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00009225 !Destructor->doesThisDeclarationHaveABody() &&
9226 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009227 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00009228 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009229 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009230
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009231 if (Destructor->isInvalidDecl())
9232 return;
9233
Eli Friedman9a14db32012-10-18 20:14:08 +00009234 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009235
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009236 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00009237 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9238 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00009239
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009240 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00009241 Diag(CurrentLocation, diag::note_member_synthesized_at)
9242 << CXXDestructor << Context.getTagDeclType(ClassDecl);
9243
9244 Destructor->setInvalidDecl();
9245 return;
9246 }
9247
Stephen Hines176edba2014-12-01 14:53:08 -08009248 // The exception specification is needed because we are defining the
9249 // function.
9250 ResolveExceptionSpec(CurrentLocation,
9251 Destructor->getType()->castAs<FunctionProtoType>());
9252
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009253 SourceLocation Loc = Destructor->getLocEnd().isValid()
9254 ? Destructor->getLocEnd()
9255 : Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00009256 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman86164e82013-09-05 00:02:25 +00009257 Destructor->markUsed(Context);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00009258 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009259
9260 if (ASTMutationListener *L = getASTMutationListener()) {
9261 L->CompletedImplicitDefinition(Destructor);
9262 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009263}
9264
Richard Smitha4156b82012-04-21 18:42:51 +00009265/// \brief Perform any semantic analysis which needs to be delayed until all
9266/// pending class member declarations have been parsed.
9267void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00009268 // If the context is an invalid C++ class, just suppress these checks.
9269 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
9270 if (Record->isInvalidDecl()) {
Alp Toker08235662013-10-18 05:54:19 +00009271 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregor10318842013-02-01 04:49:10 +00009272 DelayedDestructorExceptionSpecChecks.clear();
9273 return;
9274 }
9275 }
Richard Smitha4156b82012-04-21 18:42:51 +00009276}
9277
Richard Smithb9d0b762012-07-27 04:22:15 +00009278void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
9279 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00009280 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00009281 "adjusting dtor exception specs was introduced in c++11");
9282
Sebastian Redl0ee33912011-05-19 05:13:44 +00009283 // C++11 [class.dtor]p3:
9284 // A declaration of a destructor that does not have an exception-
9285 // specification is implicitly considered to have the same exception-
9286 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00009287 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00009288 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00009289 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00009290 return;
9291
Chandler Carruth3f224b22011-09-20 04:55:26 +00009292 // Replace the destructor's type, building off the existing one. Fortunately,
9293 // the only thing of interest in the destructor type is its extended info.
9294 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00009295 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
Stephen Hines176edba2014-12-01 14:53:08 -08009296 EPI.ExceptionSpec.Type = EST_Unevaluated;
9297 EPI.ExceptionSpec.SourceDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00009298 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00009299
Sebastian Redl0ee33912011-05-19 05:13:44 +00009300 // FIXME: If the destructor has a body that could throw, and the newly created
9301 // spec doesn't allow exceptions, we should emit a warning, because this
9302 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00009303 // However, we don't have a body or an exception specification yet, so it
9304 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00009305}
9306
Pavel Labath66ea35d2013-08-30 08:52:28 +00009307namespace {
9308/// \brief An abstract base class for all helper classes used in building the
9309// copy/move operators. These classes serve as factory functions and help us
9310// avoid using the same Expr* in the AST twice.
9311class ExprBuilder {
9312 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9313 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
9314
9315protected:
9316 static Expr *assertNotNull(Expr *E) {
9317 assert(E && "Expression construction must not fail.");
9318 return E;
9319 }
9320
9321public:
9322 ExprBuilder() {}
9323 virtual ~ExprBuilder() {}
9324
9325 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
9326};
9327
9328class RefBuilder: public ExprBuilder {
9329 VarDecl *Var;
9330 QualType VarType;
9331
9332public:
Stephen Hines176edba2014-12-01 14:53:08 -08009333 Expr *build(Sema &S, SourceLocation Loc) const override {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009334 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009335 }
9336
9337 RefBuilder(VarDecl *Var, QualType VarType)
9338 : Var(Var), VarType(VarType) {}
9339};
9340
9341class ThisBuilder: public ExprBuilder {
9342public:
Stephen Hines176edba2014-12-01 14:53:08 -08009343 Expr *build(Sema &S, SourceLocation Loc) const override {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009344 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009345 }
9346};
9347
9348class CastBuilder: public ExprBuilder {
9349 const ExprBuilder &Builder;
9350 QualType Type;
9351 ExprValueKind Kind;
9352 const CXXCastPath &Path;
9353
9354public:
Stephen Hines176edba2014-12-01 14:53:08 -08009355 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009356 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
9357 CK_UncheckedDerivedToBase, Kind,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009358 &Path).get());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009359 }
9360
9361 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
9362 const CXXCastPath &Path)
9363 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
9364};
9365
9366class DerefBuilder: public ExprBuilder {
9367 const ExprBuilder &Builder;
9368
9369public:
Stephen Hines176edba2014-12-01 14:53:08 -08009370 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009371 return assertNotNull(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009372 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009373 }
9374
9375 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9376};
9377
9378class MemberBuilder: public ExprBuilder {
9379 const ExprBuilder &Builder;
9380 QualType Type;
9381 CXXScopeSpec SS;
9382 bool IsArrow;
9383 LookupResult &MemberLookup;
9384
9385public:
Stephen Hines176edba2014-12-01 14:53:08 -08009386 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009387 return assertNotNull(S.BuildMemberReferenceExpr(
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009388 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009389 nullptr, MemberLookup, nullptr).get());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009390 }
9391
9392 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
9393 LookupResult &MemberLookup)
9394 : Builder(Builder), Type(Type), IsArrow(IsArrow),
9395 MemberLookup(MemberLookup) {}
9396};
9397
9398class MoveCastBuilder: public ExprBuilder {
9399 const ExprBuilder &Builder;
9400
9401public:
Stephen Hines176edba2014-12-01 14:53:08 -08009402 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009403 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
9404 }
9405
9406 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9407};
9408
9409class LvalueConvBuilder: public ExprBuilder {
9410 const ExprBuilder &Builder;
9411
9412public:
Stephen Hines176edba2014-12-01 14:53:08 -08009413 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009414 return assertNotNull(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009415 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009416 }
9417
9418 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
9419};
9420
9421class SubscriptBuilder: public ExprBuilder {
9422 const ExprBuilder &Base;
9423 const ExprBuilder &Index;
9424
9425public:
Stephen Hines176edba2014-12-01 14:53:08 -08009426 Expr *build(Sema &S, SourceLocation Loc) const override {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009427 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009428 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
Pavel Labath66ea35d2013-08-30 08:52:28 +00009429 }
9430
9431 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
9432 : Base(Base), Index(Index) {}
9433};
9434
9435} // end anonymous namespace
9436
Richard Smith8c889532012-11-14 00:50:40 +00009437/// When generating a defaulted copy or move assignment operator, if a field
9438/// should be copied with __builtin_memcpy rather than via explicit assignments,
9439/// do so. This optimization only applies for arrays of scalars, and for arrays
9440/// of class type where the selected copy/move-assignment operator is trivial.
9441static StmtResult
9442buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009443 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00009444 // Compute the size of the memory buffer to be copied.
9445 QualType SizeType = S.Context.getSizeType();
9446 llvm::APInt Size(S.Context.getTypeSize(SizeType),
9447 S.Context.getTypeSizeInChars(T).getQuantity());
9448
9449 // Take the address of the field references for "from" and "to". We
9450 // directly construct UnaryOperators here because semantic analysis
9451 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009452 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009453 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
9454 S.Context.getPointerType(From->getType()),
9455 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00009456 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009457 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
9458 S.Context.getPointerType(To->getType()),
9459 VK_RValue, OK_Ordinary, Loc);
9460
9461 const Type *E = T->getBaseElementTypeUnsafe();
9462 bool NeedsCollectableMemCpy =
9463 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
9464
9465 // Create a reference to the __builtin_objc_memmove_collectable function
9466 StringRef MemCpyName = NeedsCollectableMemCpy ?
9467 "__builtin_objc_memmove_collectable" :
9468 "__builtin_memcpy";
9469 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
9470 Sema::LookupOrdinaryName);
9471 S.LookupName(R, S.TUScope, true);
9472
9473 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
9474 if (!MemCpy)
9475 // Something went horribly wrong earlier, and we will have complained
9476 // about it.
9477 return StmtError();
9478
9479 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009480 VK_RValue, Loc, nullptr);
Richard Smith8c889532012-11-14 00:50:40 +00009481 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
9482
9483 Expr *CallArgs[] = {
9484 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
9485 };
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009486 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
Richard Smith8c889532012-11-14 00:50:40 +00009487 Loc, CallArgs, Loc);
9488
9489 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009490 return Call.getAs<Stmt>();
Richard Smith8c889532012-11-14 00:50:40 +00009491}
9492
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009493/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00009494/// \c To.
9495///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009496/// This routine is used to copy/move the members of a class with an
9497/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00009498/// copied are arrays, this routine builds for loops to copy them.
9499///
9500/// \param S The Sema object used for type-checking.
9501///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009502/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00009503///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009504/// \param T The type of the expressions being copied/moved. Both expressions
9505/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00009506///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009507/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00009508///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009509/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00009510///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009511/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009512/// Otherwise, it's a non-static member subobject.
9513///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009514/// \param Copying Whether we're copying or moving.
9515///
Douglas Gregor06a9f362010-05-01 20:49:11 +00009516/// \param Depth Internal parameter recording the depth of the recursion.
9517///
Richard Smith8c889532012-11-14 00:50:40 +00009518/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
9519/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00009520static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00009521buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009522 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00009523 bool CopyingBaseSubobject, bool Copying,
9524 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00009525 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00009526 // Each subobject is assigned in the manner appropriate to its type:
9527 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009528 // - if the subobject is of class type, as if by a call to operator= with
9529 // the subobject as the object expression and the corresponding
9530 // subobject of x as a single function argument (as if by explicit
9531 // qualification; that is, ignoring any possible virtual overriding
9532 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00009533 //
9534 // C++03 [class.copy]p13:
9535 // - if the subobject is of class type, the copy assignment operator for
9536 // the class is used (as if by explicit qualification; that is,
9537 // ignoring any possible virtual overriding functions in more derived
9538 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009539 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
9540 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00009541
Douglas Gregor06a9f362010-05-01 20:49:11 +00009542 // Look for operator=.
9543 DeclarationName Name
9544 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9545 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
9546 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009547
Richard Smith044c8aa2012-11-13 00:54:12 +00009548 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9549 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00009550 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00009551 LookupResult::Filter F = OpLookup.makeFilter();
9552 while (F.hasNext()) {
9553 NamedDecl *D = F.next();
9554 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9555 if (Method->isCopyAssignmentOperator() ||
9556 (!Copying && Method->isMoveAssignmentOperator()))
9557 continue;
9558
9559 F.erase();
9560 }
9561 F.done();
John McCallb0207482010-03-16 06:11:48 +00009562 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009563
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009564 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00009565 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009566 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00009567 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009568 // ambiguities), we need to cast "this" to that subobject type; to
9569 // ensure that we don't go through the virtual call mechanism, we need
9570 // to qualify the operator= name with the base class (see below). However,
9571 // this means that if the base class has a protected copy assignment
9572 // operator, the protected member access check will fail. So, we
9573 // rewrite "protected" access to "public" access in this case, since we
9574 // know by construction that we're calling from a derived class.
9575 if (CopyingBaseSubobject) {
9576 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9577 L != LEnd; ++L) {
9578 if (L.getAccess() == AS_protected)
9579 L.setAccess(AS_public);
9580 }
9581 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009582
Douglas Gregor06a9f362010-05-01 20:49:11 +00009583 // Create the nested-name-specifier that will be used to qualify the
9584 // reference to operator=; this is required to suppress the virtual
9585 // call mechanism.
9586 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009587 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00009588 SS.MakeTrivial(S.Context,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009589 NestedNameSpecifier::Create(S.Context, nullptr, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009590 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00009591 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00009592
Douglas Gregor06a9f362010-05-01 20:49:11 +00009593 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00009594 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00009595 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9596 SS, /*TemplateKWLoc=*/SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009597 /*FirstQualifierInScope=*/nullptr,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009598 OpLookup,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009599 /*TemplateArgs=*/nullptr,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009600 /*SuppressQualifierCheck=*/true);
9601 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009602 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009603
Douglas Gregor06a9f362010-05-01 20:49:11 +00009604 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00009605
Pavel Labath66ea35d2013-08-30 08:52:28 +00009606 Expr *FromInst = From.build(S, Loc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009607 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009608 OpEqualRef.getAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009609 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009610 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009611 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009612
Richard Smith8c889532012-11-14 00:50:40 +00009613 // If we built a call to a trivial 'operator=' while copying an array,
9614 // bail out. We'll replace the whole shebang with a memcpy.
9615 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9616 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009617 return StmtResult((Stmt*)nullptr);
Richard Smith8c889532012-11-14 00:50:40 +00009618
Richard Smith044c8aa2012-11-13 00:54:12 +00009619 // Convert to an expression-statement, and clean up any produced
9620 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00009621 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009622 }
John McCallb0207482010-03-16 06:11:48 +00009623
Richard Smith044c8aa2012-11-13 00:54:12 +00009624 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00009625 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00009626 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009627 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009628 ExprResult Assignment = S.CreateBuiltinBinOp(
9629 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009630 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009631 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00009632 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009633 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009634
9635 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00009636 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00009637
Douglas Gregor06a9f362010-05-01 20:49:11 +00009638 // Construct a loop over the array bounds, e.g.,
9639 //
9640 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9641 //
9642 // that will copy each of the array elements.
9643 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00009644
Douglas Gregor06a9f362010-05-01 20:49:11 +00009645 // Create the iteration variable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009646 IdentifierInfo *IterationVarName = nullptr;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009647 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009648 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009649 llvm::raw_svector_ostream OS(Str);
9650 OS << "__i" << Depth;
9651 IterationVarName = &S.Context.Idents.get(OS.str());
9652 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009653 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009654 IterationVarName, SizeType,
9655 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009656 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00009657
Douglas Gregor06a9f362010-05-01 20:49:11 +00009658 // Initialize the iteration variable to zero.
9659 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009660 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009661
Pavel Labath66ea35d2013-08-30 08:52:28 +00009662 // Creates a reference to the iteration variable.
9663 RefBuilder IterationVarRef(IterationVar, SizeType);
9664 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00009665
Douglas Gregor06a9f362010-05-01 20:49:11 +00009666 // Create the DeclStmt that holds the iteration variable.
9667 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009668
Douglas Gregor06a9f362010-05-01 20:49:11 +00009669 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009670 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9671 MoveCastBuilder FromIndexMove(FromIndexCopy);
9672 const ExprBuilder *FromIndex;
9673 if (Copying)
9674 FromIndex = &FromIndexCopy;
9675 else
9676 FromIndex = &FromIndexMove;
9677
9678 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009679
9680 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00009681 StmtResult Copy =
9682 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009683 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00009684 Copying, Depth + 1);
9685 // Bail out if copying fails or if we determined that we should use memcpy.
9686 if (Copy.isInvalid() || !Copy.get())
9687 return Copy;
9688
9689 // Create the comparison against the array bound.
9690 llvm::APInt Upper
9691 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9692 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00009693 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00009694 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9695 BO_NE, S.Context.BoolTy,
9696 VK_RValue, OK_Ordinary, Loc, false);
9697
9698 // Create the pre-increment of the iteration variable.
9699 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00009700 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9701 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009702
Douglas Gregor06a9f362010-05-01 20:49:11 +00009703 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00009704 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009705 S.MakeFullExpr(Comparison),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009706 nullptr, S.MakeFullDiscardedValueExpr(Increment),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009707 Loc, Copy.get());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009708}
9709
Richard Smith8c889532012-11-14 00:50:40 +00009710static StmtResult
9711buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009712 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00009713 bool CopyingBaseSubobject, bool Copying) {
9714 // Maybe we should use a memcpy?
9715 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9716 T.isTriviallyCopyableType(S.Context))
9717 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9718
9719 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9720 CopyingBaseSubobject,
9721 Copying, 0));
9722
9723 // If we ended up picking a trivial assignment operator for an array of a
9724 // non-trivially-copyable class type, just emit a memcpy.
9725 if (!Result.isInvalid() && !Result.get())
9726 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9727
9728 return Result;
9729}
9730
Richard Smithb9d0b762012-07-27 04:22:15 +00009731Sema::ImplicitExceptionSpecification
9732Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9733 CXXRecordDecl *ClassDecl = MD->getParent();
9734
9735 ImplicitExceptionSpecification ExceptSpec(*this);
9736 if (ClassDecl->isInvalidDecl())
9737 return ExceptSpec;
9738
9739 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07009740 assert(T->getNumParams() == 1 && "not a copy assignment op");
9741 unsigned ArgQuals =
9742 T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithb9d0b762012-07-27 04:22:15 +00009743
Douglas Gregorb87786f2010-07-01 17:48:08 +00009744 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00009745 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00009746 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00009747
9748 // It is unspecified whether or not an implicit copy assignment operator
9749 // attempts to deduplicate calls to assignment operators of virtual bases are
9750 // made. As such, this exception specification is effectively unspecified.
9751 // Based on a similar decision made for constness in C++0x, we're erring on
9752 // the side of assuming such calls to be made regardless of whether they
9753 // actually happen.
Stephen Hines651f13c2014-04-23 16:59:28 -07009754 for (const auto &Base : ClassDecl->bases()) {
9755 if (Base.isVirtual())
Sean Hunt661c67a2011-06-21 23:42:56 +00009756 continue;
9757
Douglas Gregora376d102010-07-02 21:50:04 +00009758 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07009759 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009760 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9761 ArgQuals, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -07009762 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00009763 }
Sean Hunt661c67a2011-06-21 23:42:56 +00009764
Stephen Hines651f13c2014-04-23 16:59:28 -07009765 for (const auto &Base : ClassDecl->vbases()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00009766 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -07009767 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009768 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9769 ArgQuals, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -07009770 ExceptSpec.CalledDecl(Base.getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00009771 }
9772
Stephen Hines651f13c2014-04-23 16:59:28 -07009773 for (const auto *Field : ClassDecl->fields()) {
David Blaikie262bc182012-04-30 02:36:29 +00009774 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00009775 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9776 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009777 LookupCopyingAssignment(FieldClassDecl,
9778 ArgQuals | FieldType.getCVRQualifiers(),
9779 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009780 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009781 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00009782 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009783
Richard Smithb9d0b762012-07-27 04:22:15 +00009784 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00009785}
9786
9787CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9788 // Note: The following rules are largely analoguous to the copy
9789 // constructor rules. Note that virtual bases are not taken into account
9790 // for determining the argument type of the operator. Note also that
9791 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00009792 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00009793
Richard Smithafb49182012-11-29 01:34:07 +00009794 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9795 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009796 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +00009797
Sean Hunt30de05c2011-05-14 05:23:20 +00009798 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9799 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00009800 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9801 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00009802 ArgType = ArgType.withConst();
9803 ArgType = Context.getLValueReferenceType(ArgType);
9804
Richard Smitha8942d72013-05-07 03:19:20 +00009805 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9806 CXXCopyAssignment,
9807 Const);
9808
Douglas Gregord3c35902010-07-01 16:36:15 +00009809 // An implicitly-declared copy assignment operator is an inline public
9810 // member of its class.
9811 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009812 SourceLocation ClassLoc = ClassDecl->getLocation();
9813 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009814 CXXMethodDecl *CopyAssignment =
9815 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009816 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
9817 /*isInline=*/true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00009818 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00009819 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00009820 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00009821
Stephen Hines176edba2014-12-01 14:53:08 -08009822 if (getLangOpts().CUDA) {
9823 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
9824 CopyAssignment,
9825 /* ConstRHS */ Const,
9826 /* Diagnose */ false);
9827 }
9828
Richard Smithb9d0b762012-07-27 04:22:15 +00009829 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009830 FunctionProtoType::ExtProtoInfo EPI =
9831 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009832 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009833
Douglas Gregord3c35902010-07-01 16:36:15 +00009834 // Add the parameter to the operator.
9835 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009836 ClassLoc, ClassLoc,
9837 /*Id=*/nullptr, ArgType,
9838 /*TInfo=*/nullptr, SC_None,
9839 nullptr);
David Blaikie4278c652011-09-21 18:16:56 +00009840 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00009841
Richard Smithbc2a35d2012-12-08 08:32:28 +00009842 AddOverriddenMethods(ClassDecl, CopyAssignment);
9843
9844 CopyAssignment->setTrivial(
9845 ClassDecl->needsOverloadResolutionForCopyAssignment()
9846 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9847 : ClassDecl->hasTrivialCopyAssignment());
9848
Richard Smith6c4c36c2012-03-30 20:53:28 +00009849 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009850 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009851
Richard Smithbc2a35d2012-12-08 08:32:28 +00009852 // Note that we have added this copy-assignment operator.
9853 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9854
9855 if (Scope *S = getScopeForContext(ClassDecl))
9856 PushOnScopeChains(CopyAssignment, S, false);
9857 ClassDecl->addDecl(CopyAssignment);
9858
Douglas Gregord3c35902010-07-01 16:36:15 +00009859 return CopyAssignment;
9860}
9861
Richard Smith36155c12013-06-13 03:23:42 +00009862/// Diagnose an implicit copy operation for a class which is odr-used, but
9863/// which is deprecated because the class has a user-declared copy constructor,
9864/// copy assignment operator, or destructor.
9865static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9866 SourceLocation UseLoc) {
9867 assert(CopyOp->isImplicit());
9868
9869 CXXRecordDecl *RD = CopyOp->getParent();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07009870 CXXMethodDecl *UserDeclaredOperation = nullptr;
Richard Smith36155c12013-06-13 03:23:42 +00009871
9872 // In Microsoft mode, assignment operations don't affect constructors and
9873 // vice versa.
9874 if (RD->hasUserDeclaredDestructor()) {
9875 UserDeclaredOperation = RD->getDestructor();
9876 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9877 RD->hasUserDeclaredCopyConstructor() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07009878 !S.getLangOpts().MSVCCompat) {
Richard Smith36155c12013-06-13 03:23:42 +00009879 // Find any user-declared copy constructor.
Stephen Hines651f13c2014-04-23 16:59:28 -07009880 for (auto *I : RD->ctors()) {
Richard Smith36155c12013-06-13 03:23:42 +00009881 if (I->isCopyConstructor()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07009882 UserDeclaredOperation = I;
Richard Smith36155c12013-06-13 03:23:42 +00009883 break;
9884 }
9885 }
9886 assert(UserDeclaredOperation);
9887 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9888 RD->hasUserDeclaredCopyAssignment() &&
Stephen Hines651f13c2014-04-23 16:59:28 -07009889 !S.getLangOpts().MSVCCompat) {
Richard Smith36155c12013-06-13 03:23:42 +00009890 // Find any user-declared move assignment operator.
Stephen Hines651f13c2014-04-23 16:59:28 -07009891 for (auto *I : RD->methods()) {
Richard Smith36155c12013-06-13 03:23:42 +00009892 if (I->isCopyAssignmentOperator()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07009893 UserDeclaredOperation = I;
Richard Smith36155c12013-06-13 03:23:42 +00009894 break;
9895 }
9896 }
9897 assert(UserDeclaredOperation);
9898 }
9899
9900 if (UserDeclaredOperation) {
9901 S.Diag(UserDeclaredOperation->getLocation(),
9902 diag::warn_deprecated_copy_operation)
9903 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9904 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9905 S.Diag(UseLoc, diag::note_member_synthesized_at)
9906 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9907 : Sema::CXXCopyAssignment)
9908 << RD;
9909 }
9910}
9911
Douglas Gregor06a9f362010-05-01 20:49:11 +00009912void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9913 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00009914 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009915 CopyAssignOperator->isOverloadedOperator() &&
9916 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009917 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9918 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009919 "DefineImplicitCopyAssignment called for wrong function");
9920
9921 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9922
9923 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9924 CopyAssignOperator->setInvalidDecl();
9925 return;
9926 }
Richard Smith36155c12013-06-13 03:23:42 +00009927
9928 // C++11 [class.copy]p18:
9929 // The [definition of an implicitly declared copy assignment operator] is
9930 // deprecated if the class has a user-declared copy constructor or a
9931 // user-declared destructor.
9932 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9933 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9934
Eli Friedman86164e82013-09-05 00:02:25 +00009935 CopyAssignOperator->markUsed(Context);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009936
Eli Friedman9a14db32012-10-18 20:14:08 +00009937 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009938 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009939
9940 // C++0x [class.copy]p30:
9941 // The implicitly-defined or explicitly-defaulted copy assignment operator
9942 // for a non-union class X performs memberwise copy assignment of its
9943 // subobjects. The direct base classes of X are assigned first, in the
9944 // order of their declaration in the base-specifier-list, and then the
9945 // immediate non-static data members of X are assigned, in the order in
9946 // which they were declared in the class definition.
9947
9948 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009949 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009950
9951 // The parameter for the "other" object, which we are copying from.
9952 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9953 Qualifiers OtherQuals = Other->getType().getQualifiers();
9954 QualType OtherRefType = Other->getType();
9955 if (const LValueReferenceType *OtherRef
9956 = OtherRefType->getAs<LValueReferenceType>()) {
9957 OtherRefType = OtherRef->getPointeeType();
9958 OtherQuals = OtherRefType.getQualifiers();
9959 }
9960
9961 // Our location for everything implicitly-generated.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07009962 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
9963 ? CopyAssignOperator->getLocEnd()
9964 : CopyAssignOperator->getLocation();
9965
Pavel Labath66ea35d2013-08-30 08:52:28 +00009966 // Builds a DeclRefExpr for the "other" object.
9967 RefBuilder OtherRef(Other, OtherRefType);
9968
9969 // Builds the "this" pointer.
9970 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009971
9972 // Assign base classes.
9973 bool Invalid = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07009974 for (auto &Base : ClassDecl->bases()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009975 // Form the assignment:
9976 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
Stephen Hines651f13c2014-04-23 16:59:28 -07009977 QualType BaseType = Base.getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009978 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009979 Invalid = true;
9980 continue;
9981 }
9982
John McCallf871d0c2010-08-07 06:22:56 +00009983 CXXCastPath BasePath;
Stephen Hines651f13c2014-04-23 16:59:28 -07009984 BasePath.push_back(&Base);
John McCallf871d0c2010-08-07 06:22:56 +00009985
Douglas Gregor06a9f362010-05-01 20:49:11 +00009986 // Construct the "from" expression, which is an implicit cast to the
9987 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009988 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9989 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009990
9991 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009992 DerefBuilder DerefThis(This);
9993 CastBuilder To(DerefThis,
9994 Context.getCVRQualifiedType(
9995 BaseType, CopyAssignOperator->getTypeQualifiers()),
9996 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009997
9998 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009999 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +000010000 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010001 /*CopyingBaseSubobject=*/true,
10002 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010003 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +000010004 Diag(CurrentLocation, diag::note_member_synthesized_at)
10005 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10006 CopyAssignOperator->setInvalidDecl();
10007 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +000010008 }
10009
10010 // Success! Record the copy.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010011 Statements.push_back(Copy.getAs<Expr>());
Douglas Gregor06a9f362010-05-01 20:49:11 +000010012 }
10013
Douglas Gregor06a9f362010-05-01 20:49:11 +000010014 // Assign non-static members.
Stephen Hines651f13c2014-04-23 16:59:28 -070010015 for (auto *Field : ClassDecl->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +000010016 if (Field->isUnnamedBitfield())
10017 continue;
Eli Friedman8150da32013-06-07 01:48:56 +000010018
10019 if (Field->isInvalidDecl()) {
10020 Invalid = true;
10021 continue;
10022 }
10023
Douglas Gregor06a9f362010-05-01 20:49:11 +000010024 // Check for members of reference type; we can't copy those.
10025 if (Field->getType()->isReferenceType()) {
10026 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10027 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10028 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +000010029 Diag(CurrentLocation, diag::note_member_synthesized_at)
10030 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010031 Invalid = true;
10032 continue;
10033 }
10034
10035 // Check for members of const-qualified, non-class type.
10036 QualType BaseType = Context.getBaseElementType(Field->getType());
10037 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10038 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10039 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10040 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +000010041 Diag(CurrentLocation, diag::note_member_synthesized_at)
10042 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010043 Invalid = true;
10044 continue;
10045 }
John McCallb77115d2011-06-17 00:18:42 +000010046
10047 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +000010048 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10049 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +000010050
10051 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +000010052 if (FieldType->isIncompleteArrayType()) {
10053 assert(ClassDecl->hasFlexibleArrayMember() &&
10054 "Incomplete array type is not valid");
10055 continue;
10056 }
Douglas Gregor06a9f362010-05-01 20:49:11 +000010057
10058 // Build references to the field in the object we're copying from and to.
10059 CXXScopeSpec SS; // Intentionally empty
10060 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10061 LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -070010062 MemberLookup.addDecl(Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010063 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +000010064
10065 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
10066
10067 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010068
Douglas Gregor06a9f362010-05-01 20:49:11 +000010069 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +000010070 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +000010071 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010072 /*CopyingBaseSubobject=*/false,
10073 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +000010074 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +000010075 Diag(CurrentLocation, diag::note_member_synthesized_at)
10076 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10077 CopyAssignOperator->setInvalidDecl();
10078 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +000010079 }
10080
10081 // Success! Record the copy.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010082 Statements.push_back(Copy.getAs<Stmt>());
Douglas Gregor06a9f362010-05-01 20:49:11 +000010083 }
10084
10085 if (!Invalid) {
10086 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +000010087 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +000010088
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010089 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +000010090 if (Return.isInvalid())
10091 Invalid = true;
10092 else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010093 Statements.push_back(Return.getAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +000010094
10095 if (Trap.hasErrorOccurred()) {
10096 Diag(CurrentLocation, diag::note_member_synthesized_at)
10097 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
10098 Invalid = true;
10099 }
Douglas Gregor06a9f362010-05-01 20:49:11 +000010100 }
10101 }
10102
Stephen Hines176edba2014-12-01 14:53:08 -080010103 // The exception specification is needed because we are defining the
10104 // function.
10105 ResolveExceptionSpec(CurrentLocation,
10106 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
10107
Douglas Gregor06a9f362010-05-01 20:49:11 +000010108 if (Invalid) {
10109 CopyAssignOperator->setInvalidDecl();
10110 return;
10111 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010112
10113 StmtResult Body;
10114 {
10115 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010116 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010117 /*isStmtExpr=*/false);
10118 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10119 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010120 CopyAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010121
10122 if (ASTMutationListener *L = getASTMutationListener()) {
10123 L->CompletedImplicitDefinition(CopyAssignOperator);
10124 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +000010125}
10126
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010127Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010128Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
10129 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010130
Richard Smithb9d0b762012-07-27 04:22:15 +000010131 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010132 if (ClassDecl->isInvalidDecl())
10133 return ExceptSpec;
10134
10135 // C++0x [except.spec]p14:
10136 // An implicitly declared special member function (Clause 12) shall have an
10137 // exception-specification. [...]
10138
10139 // It is unspecified whether or not an implicit move assignment operator
10140 // attempts to deduplicate calls to assignment operators of virtual bases are
10141 // made. As such, this exception specification is effectively unspecified.
10142 // Based on a similar decision made for constness in C++0x, we're erring on
10143 // the side of assuming such calls to be made regardless of whether they
10144 // actually happen.
10145 // Note that a move constructor is not implicitly declared when there are
10146 // virtual bases, but it can still be user-declared and explicitly defaulted.
Stephen Hines651f13c2014-04-23 16:59:28 -070010147 for (const auto &Base : ClassDecl->bases()) {
10148 if (Base.isVirtual())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010149 continue;
10150
10151 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -070010152 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010153 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +000010154 0, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -070010155 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010156 }
10157
Stephen Hines651f13c2014-04-23 16:59:28 -070010158 for (const auto &Base : ClassDecl->vbases()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010159 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -070010160 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010161 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +000010162 0, false, 0))
Stephen Hines651f13c2014-04-23 16:59:28 -070010163 ExceptSpec.CalledDecl(Base.getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010164 }
10165
Stephen Hines651f13c2014-04-23 16:59:28 -070010166 for (const auto *Field : ClassDecl->fields()) {
David Blaikie262bc182012-04-30 02:36:29 +000010167 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010168 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010169 if (CXXMethodDecl *MoveAssign =
10170 LookupMovingAssignment(FieldClassDecl,
10171 FieldType.getCVRQualifiers(),
10172 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +000010173 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010174 }
10175 }
10176
10177 return ExceptSpec;
10178}
10179
10180CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010181 assert(ClassDecl->needsImplicitMoveAssignment());
10182
Richard Smithafb49182012-11-29 01:34:07 +000010183 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
10184 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010185 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +000010186
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010187 // Note: The following rules are largely analoguous to the move
10188 // constructor rules.
10189
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010190 QualType ArgType = Context.getTypeDeclType(ClassDecl);
10191 QualType RetType = Context.getLValueReferenceType(ArgType);
10192 ArgType = Context.getRValueReferenceType(ArgType);
10193
Richard Smitha8942d72013-05-07 03:19:20 +000010194 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10195 CXXMoveAssignment,
10196 false);
10197
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010198 // An implicitly-declared move assignment operator is an inline public
10199 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010200 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10201 SourceLocation ClassLoc = ClassDecl->getLocation();
10202 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +000010203 CXXMethodDecl *MoveAssignment =
10204 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010205 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
Richard Smitha8942d72013-05-07 03:19:20 +000010206 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010207 MoveAssignment->setAccess(AS_public);
10208 MoveAssignment->setDefaulted();
10209 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010210
Stephen Hines176edba2014-12-01 14:53:08 -080010211 if (getLangOpts().CUDA) {
10212 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
10213 MoveAssignment,
10214 /* ConstRHS */ false,
10215 /* Diagnose */ false);
10216 }
10217
Richard Smithb9d0b762012-07-27 04:22:15 +000010218 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010219 FunctionProtoType::ExtProtoInfo EPI =
10220 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +000010221 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010222
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010223 // Add the parameter to the operator.
10224 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010225 ClassLoc, ClassLoc,
10226 /*Id=*/nullptr, ArgType,
10227 /*TInfo=*/nullptr, SC_None,
10228 nullptr);
David Blaikie4278c652011-09-21 18:16:56 +000010229 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010230
Richard Smithbc2a35d2012-12-08 08:32:28 +000010231 AddOverriddenMethods(ClassDecl, MoveAssignment);
10232
10233 MoveAssignment->setTrivial(
10234 ClassDecl->needsOverloadResolutionForMoveAssignment()
10235 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
10236 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010237
Richard Smith7d5088a2012-02-18 02:02:13 +000010238 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith743cbb92013-11-04 01:48:18 +000010239 ClassDecl->setImplicitMoveAssignmentIsDeleted();
10240 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010241 }
10242
Richard Smithbc2a35d2012-12-08 08:32:28 +000010243 // Note that we have added this copy-assignment operator.
10244 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
10245
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010246 if (Scope *S = getScopeForContext(ClassDecl))
10247 PushOnScopeChains(MoveAssignment, S, false);
10248 ClassDecl->addDecl(MoveAssignment);
10249
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010250 return MoveAssignment;
10251}
10252
Richard Smith33b1f632013-11-04 04:26:14 +000010253/// Check if we're implicitly defining a move assignment operator for a class
10254/// with virtual bases. Such a move assignment might move-assign the virtual
10255/// base multiple times.
10256static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
10257 SourceLocation CurrentLocation) {
10258 assert(!Class->isDependentContext() && "should not define dependent move");
10259
10260 // Only a virtual base could get implicitly move-assigned multiple times.
10261 // Only a non-trivial move assignment can observe this. We only want to
10262 // diagnose if we implicitly define an assignment operator that assigns
10263 // two base classes, both of which move-assign the same virtual base.
10264 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
10265 Class->getNumBases() < 2)
10266 return;
10267
10268 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
10269 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
10270 VBaseMap VBases;
10271
Stephen Hines651f13c2014-04-23 16:59:28 -070010272 for (auto &BI : Class->bases()) {
10273 Worklist.push_back(&BI);
Richard Smith33b1f632013-11-04 04:26:14 +000010274 while (!Worklist.empty()) {
10275 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
10276 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
10277
10278 // If the base has no non-trivial move assignment operators,
10279 // we don't care about moves from it.
10280 if (!Base->hasNonTrivialMoveAssignment())
10281 continue;
10282
10283 // If there's nothing virtual here, skip it.
10284 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
10285 continue;
10286
10287 // If we're not actually going to call a move assignment for this base,
10288 // or the selected move assignment is trivial, skip it.
10289 Sema::SpecialMemberOverloadResult *SMOR =
10290 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
10291 /*ConstArg*/false, /*VolatileArg*/false,
10292 /*RValueThis*/true, /*ConstThis*/false,
10293 /*VolatileThis*/false);
10294 if (!SMOR->getMethod() || SMOR->getMethod()->isTrivial() ||
10295 !SMOR->getMethod()->isMoveAssignmentOperator())
10296 continue;
10297
10298 if (BaseSpec->isVirtual()) {
10299 // We're going to move-assign this virtual base, and its move
10300 // assignment operator is not trivial. If this can happen for
10301 // multiple distinct direct bases of Class, diagnose it. (If it
10302 // only happens in one base, we'll diagnose it when synthesizing
10303 // that base class's move assignment operator.)
10304 CXXBaseSpecifier *&Existing =
Stephen Hines651f13c2014-04-23 16:59:28 -070010305 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
Richard Smith33b1f632013-11-04 04:26:14 +000010306 .first->second;
Stephen Hines651f13c2014-04-23 16:59:28 -070010307 if (Existing && Existing != &BI) {
Richard Smith33b1f632013-11-04 04:26:14 +000010308 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
10309 << Class << Base;
10310 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
10311 << (Base->getCanonicalDecl() ==
10312 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10313 << Base << Existing->getType() << Existing->getSourceRange();
Stephen Hines651f13c2014-04-23 16:59:28 -070010314 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
Richard Smith33b1f632013-11-04 04:26:14 +000010315 << (Base->getCanonicalDecl() ==
Stephen Hines651f13c2014-04-23 16:59:28 -070010316 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
10317 << Base << BI.getType() << BaseSpec->getSourceRange();
Richard Smith33b1f632013-11-04 04:26:14 +000010318
10319 // Only diagnose each vbase once.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010320 Existing = nullptr;
Richard Smith33b1f632013-11-04 04:26:14 +000010321 }
10322 } else {
10323 // Only walk over bases that have defaulted move assignment operators.
10324 // We assume that any user-provided move assignment operator handles
10325 // the multiple-moves-of-vbase case itself somehow.
10326 if (!SMOR->getMethod()->isDefaulted())
10327 continue;
10328
10329 // We're going to move the base classes of Base. Add them to the list.
Stephen Hines651f13c2014-04-23 16:59:28 -070010330 for (auto &BI : Base->bases())
10331 Worklist.push_back(&BI);
Richard Smith33b1f632013-11-04 04:26:14 +000010332 }
10333 }
10334 }
10335}
10336
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010337void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
10338 CXXMethodDecl *MoveAssignOperator) {
10339 assert((MoveAssignOperator->isDefaulted() &&
10340 MoveAssignOperator->isOverloadedOperator() &&
10341 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +000010342 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
10343 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010344 "DefineImplicitMoveAssignment called for wrong function");
10345
10346 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
10347
10348 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
10349 MoveAssignOperator->setInvalidDecl();
10350 return;
10351 }
10352
Eli Friedman86164e82013-09-05 00:02:25 +000010353 MoveAssignOperator->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010354
Eli Friedman9a14db32012-10-18 20:14:08 +000010355 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010356 DiagnosticErrorTrap Trap(Diags);
10357
10358 // C++0x [class.copy]p28:
10359 // The implicitly-defined or move assignment operator for a non-union class
10360 // X performs memberwise move assignment of its subobjects. The direct base
10361 // classes of X are assigned first, in the order of their declaration in the
10362 // base-specifier-list, and then the immediate non-static data members of X
10363 // are assigned, in the order in which they were declared in the class
10364 // definition.
10365
Richard Smith33b1f632013-11-04 04:26:14 +000010366 // Issue a warning if our implicit move assignment operator will move
10367 // from a virtual base more than once.
10368 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
Richard Smith743cbb92013-11-04 01:48:18 +000010369
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010370 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010371 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010372
10373 // The parameter for the "other" object, which we are move from.
10374 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
10375 QualType OtherRefType = Other->getType()->
10376 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +000010377 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010378 "Bad argument type of defaulted move assignment");
10379
10380 // Our location for everything implicitly-generated.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010381 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
10382 ? MoveAssignOperator->getLocEnd()
10383 : MoveAssignOperator->getLocation();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010384
Pavel Labath66ea35d2013-08-30 08:52:28 +000010385 // Builds a reference to the "other" object.
10386 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010387 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +000010388 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010389
Pavel Labath66ea35d2013-08-30 08:52:28 +000010390 // Builds the "this" pointer.
10391 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +000010392
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010393 // Assign base classes.
10394 bool Invalid = false;
Stephen Hines651f13c2014-04-23 16:59:28 -070010395 for (auto &Base : ClassDecl->bases()) {
Richard Smith33b1f632013-11-04 04:26:14 +000010396 // C++11 [class.copy]p28:
10397 // It is unspecified whether subobjects representing virtual base classes
10398 // are assigned more than once by the implicitly-defined copy assignment
10399 // operator.
10400 // FIXME: Do not assign to a vbase that will be assigned by some other base
10401 // class. For a move-assignment, this can result in the vbase being moved
10402 // multiple times.
10403
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010404 // Form the assignment:
10405 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
Stephen Hines651f13c2014-04-23 16:59:28 -070010406 QualType BaseType = Base.getType().getUnqualifiedType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010407 if (!BaseType->isRecordType()) {
10408 Invalid = true;
10409 continue;
10410 }
10411
10412 CXXCastPath BasePath;
Stephen Hines651f13c2014-04-23 16:59:28 -070010413 BasePath.push_back(&Base);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010414
10415 // Construct the "from" expression, which is an implicit cast to the
10416 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +000010417 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010418
10419 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +000010420 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010421
10422 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +000010423 CastBuilder To(DerefThis,
10424 Context.getCVRQualifiedType(
10425 BaseType, MoveAssignOperator->getTypeQualifiers()),
10426 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010427
10428 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +000010429 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +000010430 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010431 /*CopyingBaseSubobject=*/true,
10432 /*Copying=*/false);
10433 if (Move.isInvalid()) {
10434 Diag(CurrentLocation, diag::note_member_synthesized_at)
10435 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10436 MoveAssignOperator->setInvalidDecl();
10437 return;
10438 }
10439
10440 // Success! Record the move.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010441 Statements.push_back(Move.getAs<Expr>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010442 }
10443
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010444 // Assign non-static members.
Stephen Hines651f13c2014-04-23 16:59:28 -070010445 for (auto *Field : ClassDecl->fields()) {
Douglas Gregord61db332011-10-10 17:22:13 +000010446 if (Field->isUnnamedBitfield())
10447 continue;
10448
Eli Friedman8150da32013-06-07 01:48:56 +000010449 if (Field->isInvalidDecl()) {
10450 Invalid = true;
10451 continue;
10452 }
10453
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010454 // Check for members of reference type; we can't move those.
10455 if (Field->getType()->isReferenceType()) {
10456 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10457 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
10458 Diag(Field->getLocation(), diag::note_declared_at);
10459 Diag(CurrentLocation, diag::note_member_synthesized_at)
10460 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10461 Invalid = true;
10462 continue;
10463 }
10464
10465 // Check for members of const-qualified, non-class type.
10466 QualType BaseType = Context.getBaseElementType(Field->getType());
10467 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
10468 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
10469 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
10470 Diag(Field->getLocation(), diag::note_declared_at);
10471 Diag(CurrentLocation, diag::note_member_synthesized_at)
10472 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10473 Invalid = true;
10474 continue;
10475 }
10476
10477 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +000010478 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
10479 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010480
10481 QualType FieldType = Field->getType().getNonReferenceType();
10482 if (FieldType->isIncompleteArrayType()) {
10483 assert(ClassDecl->hasFlexibleArrayMember() &&
10484 "Incomplete array type is not valid");
10485 continue;
10486 }
10487
10488 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010489 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
10490 LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -070010491 MemberLookup.addDecl(Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010492 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +000010493 MemberBuilder From(MoveOther, OtherRefType,
10494 /*IsArrow=*/false, MemberLookup);
10495 MemberBuilder To(This, getCurrentThisType(),
10496 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010497
Pavel Labath66ea35d2013-08-30 08:52:28 +000010498 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010499 "Member reference with rvalue base must be rvalue except for reference "
10500 "members, which aren't allowed for move assignment.");
10501
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010502 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +000010503 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +000010504 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010505 /*CopyingBaseSubobject=*/false,
10506 /*Copying=*/false);
10507 if (Move.isInvalid()) {
10508 Diag(CurrentLocation, diag::note_member_synthesized_at)
10509 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10510 MoveAssignOperator->setInvalidDecl();
10511 return;
10512 }
Richard Smithe7ce7092012-11-12 23:33:00 +000010513
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010514 // Success! Record the copy.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010515 Statements.push_back(Move.getAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010516 }
10517
10518 if (!Invalid) {
10519 // Add a "return *this;"
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010520 ExprResult ThisObj =
10521 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
10522
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010523 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010524 if (Return.isInvalid())
10525 Invalid = true;
10526 else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010527 Statements.push_back(Return.getAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010528
10529 if (Trap.hasErrorOccurred()) {
10530 Diag(CurrentLocation, diag::note_member_synthesized_at)
10531 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10532 Invalid = true;
10533 }
10534 }
10535 }
10536
Stephen Hines176edba2014-12-01 14:53:08 -080010537 // The exception specification is needed because we are defining the
10538 // function.
10539 ResolveExceptionSpec(CurrentLocation,
10540 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
10541
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010542 if (Invalid) {
10543 MoveAssignOperator->setInvalidDecl();
10544 return;
10545 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010546
10547 StmtResult Body;
10548 {
10549 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010550 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010551 /*isStmtExpr=*/false);
10552 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10553 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010554 MoveAssignOperator->setBody(Body.getAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010555
10556 if (ASTMutationListener *L = getASTMutationListener()) {
10557 L->CompletedImplicitDefinition(MoveAssignOperator);
10558 }
10559}
10560
Richard Smithb9d0b762012-07-27 04:22:15 +000010561Sema::ImplicitExceptionSpecification
10562Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10563 CXXRecordDecl *ClassDecl = MD->getParent();
10564
10565 ImplicitExceptionSpecification ExceptSpec(*this);
10566 if (ClassDecl->isInvalidDecl())
10567 return ExceptSpec;
10568
10569 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
Stephen Hines651f13c2014-04-23 16:59:28 -070010570 assert(T->getNumParams() >= 1 && "not a copy ctor");
10571 unsigned Quals = T->getParamType(0).getNonReferenceType().getCVRQualifiers();
Richard Smithb9d0b762012-07-27 04:22:15 +000010572
Douglas Gregor0d405db2010-07-01 20:59:04 +000010573 // C++ [except.spec]p14:
10574 // An implicitly declared special member function (Clause 12) shall have an
10575 // exception-specification. [...]
Stephen Hines651f13c2014-04-23 16:59:28 -070010576 for (const auto &Base : ClassDecl->bases()) {
Douglas Gregor0d405db2010-07-01 20:59:04 +000010577 // Virtual bases are handled below.
Stephen Hines651f13c2014-04-23 16:59:28 -070010578 if (Base.isVirtual())
Douglas Gregor0d405db2010-07-01 20:59:04 +000010579 continue;
10580
Douglas Gregor22584312010-07-02 23:41:54 +000010581 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -070010582 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010583 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010584 LookupCopyingConstructor(BaseClassDecl, Quals))
Stephen Hines651f13c2014-04-23 16:59:28 -070010585 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010586 }
Stephen Hines651f13c2014-04-23 16:59:28 -070010587 for (const auto &Base : ClassDecl->vbases()) {
Douglas Gregor22584312010-07-02 23:41:54 +000010588 CXXRecordDecl *BaseClassDecl
Stephen Hines651f13c2014-04-23 16:59:28 -070010589 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010590 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010591 LookupCopyingConstructor(BaseClassDecl, Quals))
Stephen Hines651f13c2014-04-23 16:59:28 -070010592 ExceptSpec.CalledDecl(Base.getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010593 }
Stephen Hines651f13c2014-04-23 16:59:28 -070010594 for (const auto *Field : ClassDecl->fields()) {
David Blaikie262bc182012-04-30 02:36:29 +000010595 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +000010596 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10597 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +000010598 LookupCopyingConstructor(FieldClassDecl,
10599 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +000010600 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010601 }
10602 }
Sebastian Redl60618fa2011-03-12 11:50:43 +000010603
Richard Smithb9d0b762012-07-27 04:22:15 +000010604 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +000010605}
10606
10607CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10608 CXXRecordDecl *ClassDecl) {
10609 // C++ [class.copy]p4:
10610 // If the class definition does not explicitly declare a copy
10611 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +000010612 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +000010613
Richard Smithafb49182012-11-29 01:34:07 +000010614 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10615 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010616 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +000010617
Sean Hunt49634cf2011-05-13 06:10:58 +000010618 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10619 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +000010620 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +000010621 if (Const)
10622 ArgType = ArgType.withConst();
10623 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +000010624
Richard Smith7756afa2012-06-10 05:43:50 +000010625 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10626 CXXCopyConstructor,
10627 Const);
10628
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010629 DeclarationName Name
10630 = Context.DeclarationNames.getCXXConstructorName(
10631 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010632 SourceLocation ClassLoc = ClassDecl->getLocation();
10633 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +000010634
10635 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010636 // member of its class.
10637 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010638 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smith61802452011-12-22 02:22:31 +000010639 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010640 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010641 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +000010642 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010643
Stephen Hines176edba2014-12-01 14:53:08 -080010644 if (getLangOpts().CUDA) {
10645 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
10646 CopyConstructor,
10647 /* ConstRHS */ Const,
10648 /* Diagnose */ false);
10649 }
10650
Richard Smithb9d0b762012-07-27 04:22:15 +000010651 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010652 FunctionProtoType::ExtProtoInfo EPI =
10653 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010654 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010655 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010656
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010657 // Add the parameter to the constructor.
10658 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010659 ClassLoc, ClassLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010660 /*IdentifierInfo=*/nullptr,
10661 ArgType, /*TInfo=*/nullptr,
10662 SC_None, nullptr);
David Blaikie4278c652011-09-21 18:16:56 +000010663 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +000010664
Richard Smithbc2a35d2012-12-08 08:32:28 +000010665 CopyConstructor->setTrivial(
10666 ClassDecl->needsOverloadResolutionForCopyConstructor()
10667 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10668 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +000010669
Richard Smith6c4c36c2012-03-30 20:53:28 +000010670 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +000010671 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +000010672
Richard Smithbc2a35d2012-12-08 08:32:28 +000010673 // Note that we have declared this constructor.
10674 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10675
10676 if (Scope *S = getScopeForContext(ClassDecl))
10677 PushOnScopeChains(CopyConstructor, S, false);
10678 ClassDecl->addDecl(CopyConstructor);
10679
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010680 return CopyConstructor;
10681}
10682
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010683void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +000010684 CXXConstructorDecl *CopyConstructor) {
10685 assert((CopyConstructor->isDefaulted() &&
10686 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010687 !CopyConstructor->doesThisDeclarationHaveABody() &&
10688 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010689 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +000010690
Anders Carlsson63010a72010-04-23 16:24:12 +000010691 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010692 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010693
Richard Smith36155c12013-06-13 03:23:42 +000010694 // C++11 [class.copy]p7:
Benjamin Kramere5753592013-09-09 14:48:42 +000010695 // The [definition of an implicitly declared copy constructor] is
Richard Smith36155c12013-06-13 03:23:42 +000010696 // deprecated if the class has a user-declared copy assignment operator
10697 // or a user-declared destructor.
10698 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10699 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10700
Eli Friedman9a14db32012-10-18 20:14:08 +000010701 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +000010702 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010703
David Blaikie93c86172013-01-17 05:26:25 +000010704 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +000010705 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +000010706 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010707 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +000010708 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010709 } else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010710 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
10711 ? CopyConstructor->getLocEnd()
10712 : CopyConstructor->getLocation();
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010713 Sema::CompoundScopeRAII CompoundScope(*this);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010714 CopyConstructor->setBody(
10715 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +000010716 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010717
Stephen Hines176edba2014-12-01 14:53:08 -080010718 // The exception specification is needed because we are defining the
10719 // function.
10720 ResolveExceptionSpec(CurrentLocation,
10721 CopyConstructor->getType()->castAs<FunctionProtoType>());
10722
Eli Friedman86164e82013-09-05 00:02:25 +000010723 CopyConstructor->markUsed(Context);
Stephen Hines176edba2014-12-01 14:53:08 -080010724 MarkVTableUsed(CurrentLocation, ClassDecl);
10725
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010726 if (ASTMutationListener *L = getASTMutationListener()) {
10727 L->CompletedImplicitDefinition(CopyConstructor);
10728 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010729}
10730
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010731Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010732Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10733 CXXRecordDecl *ClassDecl = MD->getParent();
10734
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010735 // C++ [except.spec]p14:
10736 // An implicitly declared special member function (Clause 12) shall have an
10737 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +000010738 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010739 if (ClassDecl->isInvalidDecl())
10740 return ExceptSpec;
10741
10742 // Direct base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -070010743 for (const auto &B : ClassDecl->bases()) {
10744 if (B.isVirtual()) // Handled below.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010745 continue;
10746
Stephen Hines651f13c2014-04-23 16:59:28 -070010747 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010748 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010749 CXXConstructorDecl *Constructor =
10750 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010751 // If this is a deleted function, add it anyway. This might be conformant
10752 // with the standard. This might not. I'm not sure. It might not matter.
10753 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -070010754 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010755 }
10756 }
10757
10758 // Virtual base-class constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -070010759 for (const auto &B : ClassDecl->vbases()) {
10760 if (const RecordType *BaseType = B.getType()->getAs<RecordType>()) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010761 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010762 CXXConstructorDecl *Constructor =
10763 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010764 // If this is a deleted function, add it anyway. This might be conformant
10765 // with the standard. This might not. I'm not sure. It might not matter.
10766 if (Constructor)
Stephen Hines651f13c2014-04-23 16:59:28 -070010767 ExceptSpec.CalledDecl(B.getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010768 }
10769 }
10770
10771 // Field constructors.
Stephen Hines651f13c2014-04-23 16:59:28 -070010772 for (const auto *F : ClassDecl->fields()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010773 QualType FieldType = Context.getBaseElementType(F->getType());
10774 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10775 CXXConstructorDecl *Constructor =
10776 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010777 // If this is a deleted function, add it anyway. This might be conformant
10778 // with the standard. This might not. I'm not sure. It might not matter.
10779 // In particular, the problem is that this function never gets called. It
10780 // might just be ill-formed because this function attempts to refer to
10781 // a deleted function here.
10782 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010783 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010784 }
10785 }
10786
10787 return ExceptSpec;
10788}
10789
10790CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10791 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010792 assert(ClassDecl->needsImplicitMoveConstructor());
10793
Richard Smithafb49182012-11-29 01:34:07 +000010794 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10795 if (DSM.isAlreadyBeingDeclared())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010796 return nullptr;
Richard Smithafb49182012-11-29 01:34:07 +000010797
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010798 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10799 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010800
Richard Smith7756afa2012-06-10 05:43:50 +000010801 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10802 CXXMoveConstructor,
10803 false);
10804
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010805 DeclarationName Name
10806 = Context.DeclarationNames.getCXXConstructorName(
10807 Context.getCanonicalType(ClassType));
10808 SourceLocation ClassLoc = ClassDecl->getLocation();
10809 DeclarationNameInfo NameInfo(Name, ClassLoc);
10810
Richard Smitha8942d72013-05-07 03:19:20 +000010811 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010812 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010813 // member of its class.
10814 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010815 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
Richard Smith61802452011-12-22 02:22:31 +000010816 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010817 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010818 MoveConstructor->setAccess(AS_public);
10819 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010820
Stephen Hines176edba2014-12-01 14:53:08 -080010821 if (getLangOpts().CUDA) {
10822 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
10823 MoveConstructor,
10824 /* ConstRHS */ false,
10825 /* Diagnose */ false);
10826 }
10827
Richard Smithb9d0b762012-07-27 04:22:15 +000010828 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010829 FunctionProtoType::ExtProtoInfo EPI =
10830 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010831 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010832 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010833
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010834 // Add the parameter to the constructor.
10835 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10836 ClassLoc, ClassLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010837 /*IdentifierInfo=*/nullptr,
10838 ArgType, /*TInfo=*/nullptr,
10839 SC_None, nullptr);
David Blaikie4278c652011-09-21 18:16:56 +000010840 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010841
Richard Smithbc2a35d2012-12-08 08:32:28 +000010842 MoveConstructor->setTrivial(
10843 ClassDecl->needsOverloadResolutionForMoveConstructor()
10844 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10845 : ClassDecl->hasTrivialMoveConstructor());
10846
Sean Hunt769bb2d2011-10-11 06:43:29 +000010847 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith743cbb92013-11-04 01:48:18 +000010848 ClassDecl->setImplicitMoveConstructorIsDeleted();
10849 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010850 }
10851
10852 // Note that we have declared this constructor.
10853 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10854
10855 if (Scope *S = getScopeForContext(ClassDecl))
10856 PushOnScopeChains(MoveConstructor, S, false);
10857 ClassDecl->addDecl(MoveConstructor);
10858
10859 return MoveConstructor;
10860}
10861
10862void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10863 CXXConstructorDecl *MoveConstructor) {
10864 assert((MoveConstructor->isDefaulted() &&
10865 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010866 !MoveConstructor->doesThisDeclarationHaveABody() &&
10867 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010868 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10869
10870 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10871 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10872
Eli Friedman9a14db32012-10-18 20:14:08 +000010873 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010874 DiagnosticErrorTrap Trap(Diags);
10875
David Blaikie93c86172013-01-17 05:26:25 +000010876 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010877 Trap.hasErrorOccurred()) {
10878 Diag(CurrentLocation, diag::note_member_synthesized_at)
10879 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10880 MoveConstructor->setInvalidDecl();
10881 } else {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010882 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
10883 ? MoveConstructor->getLocEnd()
10884 : MoveConstructor->getLocation();
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010885 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010886 MoveConstructor->setBody(ActOnCompoundStmt(
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010887 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010888 }
10889
Stephen Hines176edba2014-12-01 14:53:08 -080010890 // The exception specification is needed because we are defining the
10891 // function.
10892 ResolveExceptionSpec(CurrentLocation,
10893 MoveConstructor->getType()->castAs<FunctionProtoType>());
10894
Eli Friedman86164e82013-09-05 00:02:25 +000010895 MoveConstructor->markUsed(Context);
Stephen Hines176edba2014-12-01 14:53:08 -080010896 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010897
10898 if (ASTMutationListener *L = getASTMutationListener()) {
10899 L->CompletedImplicitDefinition(MoveConstructor);
10900 }
10901}
10902
Douglas Gregore4e68d42012-02-15 19:33:52 +000010903bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010904 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010905}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010906
10907void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Valid6992ab2013-09-29 08:45:24 +000010908 SourceLocation CurrentLocation,
10909 CXXConversionDecl *Conv) {
10910 CXXRecordDecl *Lambda = Conv->getParent();
10911 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10912 // If we are defining a specialization of a conversion to function-ptr
10913 // cache the deduced template arguments for this specialization
10914 // so that we can use them to retrieve the corresponding call-operator
10915 // and static-invoker.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010916 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
10917
Faisal Valid6992ab2013-09-29 08:45:24 +000010918 // Retrieve the corresponding call-operator specialization.
10919 if (Lambda->isGenericLambda()) {
10920 assert(Conv->isFunctionTemplateSpecialization());
10921 FunctionTemplateDecl *CallOpTemplate =
10922 CallOp->getDescribedFunctionTemplate();
10923 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010924 void *InsertPos = nullptr;
Faisal Valid6992ab2013-09-29 08:45:24 +000010925 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010926 DeducedTemplateArgs->asArray(),
Faisal Valid6992ab2013-09-29 08:45:24 +000010927 InsertPos);
10928 assert(CallOpSpec &&
10929 "Conversion operator must have a corresponding call operator");
10930 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10931 }
10932 // Mark the call operator referenced (and add to pending instantiations
10933 // if necessary).
10934 // For both the conversion and static-invoker template specializations
10935 // we construct their body's in this function, so no need to add them
10936 // to the PendingInstantiations.
10937 MarkFunctionReferenced(CurrentLocation, CallOp);
10938
Eli Friedman9a14db32012-10-18 20:14:08 +000010939 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010940 DiagnosticErrorTrap Trap(Diags);
Faisal Valid6992ab2013-09-29 08:45:24 +000010941
Stephen Hines651f13c2014-04-23 16:59:28 -070010942 // Retrieve the static invoker...
Faisal Valid6992ab2013-09-29 08:45:24 +000010943 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10944 // ... and get the corresponding specialization for a generic lambda.
10945 if (Lambda->isGenericLambda()) {
10946 assert(DeducedTemplateArgs &&
10947 "Must have deduced template arguments from Conversion Operator");
10948 FunctionTemplateDecl *InvokeTemplate =
10949 Invoker->getDescribedFunctionTemplate();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070010950 void *InsertPos = nullptr;
Faisal Valid6992ab2013-09-29 08:45:24 +000010951 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010952 DeducedTemplateArgs->asArray(),
Faisal Valid6992ab2013-09-29 08:45:24 +000010953 InsertPos);
10954 assert(InvokeSpec &&
10955 "Must have a corresponding static invoker specialization");
10956 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10957 }
10958 // Construct the body of the conversion function { return __invoke; }.
10959 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010960 VK_LValue, Conv->getLocation()).get();
Faisal Valid6992ab2013-09-29 08:45:24 +000010961 assert(FunctionRef && "Can't refer to __invoke function?");
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010962 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
Faisal Valid6992ab2013-09-29 08:45:24 +000010963 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10964 Conv->getLocation(),
10965 Conv->getLocation()));
10966
10967 Conv->markUsed(Context);
10968 Conv->setReferenced();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010969
Faisal Valid6992ab2013-09-29 08:45:24 +000010970 // Fill in the __invoke function with a dummy implementation. IR generation
10971 // will fill in the actual details.
10972 Invoker->markUsed(Context);
10973 Invoker->setReferenced();
10974 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10975
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010976 if (ASTMutationListener *L = getASTMutationListener()) {
10977 L->CompletedImplicitDefinition(Conv);
Faisal Valid6992ab2013-09-29 08:45:24 +000010978 L->CompletedImplicitDefinition(Invoker);
10979 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010980}
10981
Faisal Valid6992ab2013-09-29 08:45:24 +000010982
10983
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010984void Sema::DefineImplicitLambdaToBlockPointerConversion(
10985 SourceLocation CurrentLocation,
10986 CXXConversionDecl *Conv)
10987{
Faisal Vali56fe35b2013-09-29 17:08:32 +000010988 assert(!Conv->getParent()->isGenericLambda());
Faisal Valid6992ab2013-09-29 08:45:24 +000010989
Eli Friedman86164e82013-09-05 00:02:25 +000010990 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010991
Eli Friedman9a14db32012-10-18 20:14:08 +000010992 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010993 DiagnosticErrorTrap Trap(Diags);
10994
Douglas Gregorac1303e2012-02-22 05:02:47 +000010995 // Copy-initialize the lambda object as needed to capture it.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070010996 Expr *This = ActOnCXXThis(CurrentLocation).get();
10997 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010998
Eli Friedman23f02672012-03-01 04:01:32 +000010999 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
11000 Conv->getLocation(),
11001 Conv, DerefThis);
11002
11003 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
11004 // behavior. Note that only the general conversion function does this
11005 // (since it's unusable otherwise); in the case where we inline the
11006 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000011007 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000011008 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
11009 CK_CopyAndAutoreleaseBlockObject,
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011010 BuildBlock.get(), nullptr, VK_RValue);
Eli Friedman23f02672012-03-01 04:01:32 +000011011
11012 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011013 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000011014 Conv->setInvalidDecl();
11015 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011016 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000011017
Douglas Gregorac1303e2012-02-22 05:02:47 +000011018 // Create the return statement that returns the block from the conversion
11019 // function.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011020 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000011021 if (Return.isInvalid()) {
11022 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
11023 Conv->setInvalidDecl();
11024 return;
11025 }
11026
11027 // Set the body of the conversion function.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011028 Stmt *ReturnS = Return.get();
Nico Weberd36aa352012-12-29 20:03:39 +000011029 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000011030 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011031 Conv->getLocation()));
11032
Douglas Gregorac1303e2012-02-22 05:02:47 +000011033 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000011034 if (ASTMutationListener *L = getASTMutationListener()) {
11035 L->CompletedImplicitDefinition(Conv);
11036 }
11037}
11038
Douglas Gregorf52757d2012-03-10 06:53:13 +000011039/// \brief Determine whether the given list arguments contains exactly one
11040/// "real" (non-default) argument.
11041static bool hasOneRealArgument(MultiExprArg Args) {
11042 switch (Args.size()) {
11043 case 0:
11044 return false;
11045
11046 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011047 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000011048 return false;
11049
11050 // fall through
11051 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011052 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000011053 }
11054
11055 return false;
11056}
11057
John McCall60d7b3a2010-08-24 06:29:42 +000011058ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000011059Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000011060 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000011061 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011062 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000011063 bool IsListInitialization,
Stephen Hines176edba2014-12-01 14:53:08 -080011064 bool IsStdInitListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000011065 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000011066 unsigned ConstructKind,
11067 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000011068 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000011069
Douglas Gregor2f599792010-04-02 18:24:57 +000011070 // C++0x [class.copy]p34:
11071 // When certain criteria are met, an implementation is allowed to
11072 // omit the copy/move construction of a class object, even if the
11073 // copy/move constructor and/or destructor for the object have
11074 // side effects. [...]
11075 // - when a temporary class object that has not been bound to a
11076 // reference (12.2) would be copied/moved to a class object
11077 // with the same cv-unqualified type, the copy/move operation
11078 // can be omitted by constructing the temporary object
11079 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000011080 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000011081 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000011082 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000011083 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000011084 }
Mike Stump1eb44332009-09-09 15:08:12 +000011085
11086 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011087 Elidable, ExprArgs, HadMultipleCandidates,
Stephen Hines176edba2014-12-01 14:53:08 -080011088 IsListInitialization,
11089 IsStdInitListInitialization, RequiresZeroInit,
Richard Smithc83c2302012-12-19 01:39:02 +000011090 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000011091}
11092
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000011093/// BuildCXXConstructExpr - Creates a complete call to a constructor,
11094/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000011095ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000011096Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
11097 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000011098 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011099 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000011100 bool IsListInitialization,
Stephen Hines176edba2014-12-01 14:53:08 -080011101 bool IsStdInitListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000011102 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000011103 unsigned ConstructKind,
11104 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000011105 MarkFunctionReferenced(ConstructLoc, Constructor);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011106 return CXXConstructExpr::Create(
11107 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
Stephen Hines176edba2014-12-01 14:53:08 -080011108 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
11109 RequiresZeroInit,
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011110 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
11111 ParenRange);
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000011112}
11113
Stephen Hines176edba2014-12-01 14:53:08 -080011114ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
11115 assert(Field->hasInClassInitializer());
11116
11117 // If we already have the in-class initializer nothing needs to be done.
11118 if (Field->getInClassInitializer())
11119 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11120
11121 // Maybe we haven't instantiated the in-class initializer. Go check the
11122 // pattern FieldDecl to see if it has one.
11123 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
11124
11125 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
11126 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
11127 DeclContext::lookup_result Lookup =
11128 ClassPattern->lookup(Field->getDeclName());
11129 assert(Lookup.size() == 1);
11130 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
11131 if (InstantiateInClassInitializer(Loc, Field, Pattern,
11132 getTemplateInstantiationArgs(Field)))
11133 return ExprError();
11134 return CXXDefaultInitExpr::Create(Context, Loc, Field);
11135 }
11136
11137 // DR1351:
11138 // If the brace-or-equal-initializer of a non-static data member
11139 // invokes a defaulted default constructor of its class or of an
11140 // enclosing class in a potentially evaluated subexpression, the
11141 // program is ill-formed.
11142 //
11143 // This resolution is unworkable: the exception specification of the
11144 // default constructor can be needed in an unevaluated context, in
11145 // particular, in the operand of a noexcept-expression, and we can be
11146 // unable to compute an exception specification for an enclosed class.
11147 //
11148 // Any attempt to resolve the exception specification of a defaulted default
11149 // constructor before the initializer is lexically complete will ultimately
11150 // come here at which point we can diagnose it.
11151 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
11152 if (OutermostClass == ParentRD) {
11153 Diag(Field->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
11154 << ParentRD << Field;
11155 } else {
11156 Diag(Field->getLocEnd(),
11157 diag::err_in_class_initializer_not_yet_parsed_outer_class)
11158 << ParentRD << OutermostClass << Field;
11159 }
11160
11161 return ExprError();
11162}
11163
John McCall68c6c9a2010-02-02 09:10:11 +000011164void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000011165 if (VD->isInvalidDecl()) return;
11166
John McCall68c6c9a2010-02-02 09:10:11 +000011167 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000011168 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000011169 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000011170 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000011171
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000011172 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000011173 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000011174 CheckDestructorAccess(VD->getLocation(), Destructor,
11175 PDiag(diag::err_access_dtor_var)
11176 << VD->getDeclName()
11177 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000011178 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000011179
Stephen Hines651f13c2014-04-23 16:59:28 -070011180 if (Destructor->isTrivial()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000011181 if (!VD->hasGlobalStorage()) return;
11182
11183 // Emit warning for non-trivial dtor in global scope (a real global,
11184 // class-static, function-static).
11185 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
11186
11187 // TODO: this should be re-enabled for static locals by !CXAAtExit
11188 if (!VD->isStaticLocal())
11189 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000011190}
11191
Douglas Gregor39da0b82009-09-09 23:08:42 +000011192/// \brief Given a constructor and the set of arguments provided for the
11193/// constructor, convert the arguments and add any required default arguments
11194/// to form a proper call to this constructor.
11195///
11196/// \returns true if an error occurred, false otherwise.
11197bool
11198Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
11199 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000011200 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000011201 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000011202 bool AllowExplicit,
11203 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000011204 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
11205 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000011206 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000011207
11208 const FunctionProtoType *Proto
11209 = Constructor->getType()->getAs<FunctionProtoType>();
11210 assert(Proto && "Constructor without a prototype?");
Stephen Hines651f13c2014-04-23 16:59:28 -070011211 unsigned NumParams = Proto->getNumParams();
11212
Douglas Gregor39da0b82009-09-09 23:08:42 +000011213 // If too few arguments are available, we'll fill in the rest with defaults.
Stephen Hines651f13c2014-04-23 16:59:28 -070011214 if (NumArgs < NumParams)
11215 ConvertedArgs.reserve(NumParams);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000011216 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000011217 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000011218
11219 VariadicCallType CallType =
11220 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000011221 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000011222 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011223 Proto, 0,
11224 llvm::makeArrayRef(Args, NumArgs),
11225 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000011226 CallType, AllowExplicit,
11227 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000011228 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000011229
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011230 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000011231
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000011232 CheckConstructorCall(Constructor,
Stephen Hines176edba2014-12-01 14:53:08 -080011233 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000011234 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000011235
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000011236 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000011237}
11238
Anders Carlsson20d45d22009-12-12 00:32:00 +000011239static inline bool
11240CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
11241 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011242 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000011243 if (isa<NamespaceDecl>(DC)) {
11244 return SemaRef.Diag(FnDecl->getLocation(),
11245 diag::err_operator_new_delete_declared_in_namespace)
11246 << FnDecl->getDeclName();
11247 }
11248
11249 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000011250 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000011251 return SemaRef.Diag(FnDecl->getLocation(),
11252 diag::err_operator_new_delete_declared_static)
11253 << FnDecl->getDeclName();
11254 }
11255
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000011256 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000011257}
11258
Anders Carlsson156c78e2009-12-13 17:53:43 +000011259static inline bool
11260CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
11261 CanQualType ExpectedResultType,
11262 CanQualType ExpectedFirstParamType,
11263 unsigned DependentParamTypeDiag,
11264 unsigned InvalidParamTypeDiag) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011265 QualType ResultType =
11266 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlsson156c78e2009-12-13 17:53:43 +000011267
11268 // Check that the result type is not dependent.
11269 if (ResultType->isDependentType())
11270 return SemaRef.Diag(FnDecl->getLocation(),
11271 diag::err_operator_new_delete_dependent_result_type)
11272 << FnDecl->getDeclName() << ExpectedResultType;
11273
11274 // Check that the result type is what we expect.
11275 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
11276 return SemaRef.Diag(FnDecl->getLocation(),
11277 diag::err_operator_new_delete_invalid_result_type)
11278 << FnDecl->getDeclName() << ExpectedResultType;
11279
11280 // A function template must have at least 2 parameters.
11281 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
11282 return SemaRef.Diag(FnDecl->getLocation(),
11283 diag::err_operator_new_delete_template_too_few_parameters)
11284 << FnDecl->getDeclName();
11285
11286 // The function decl must have at least 1 parameter.
11287 if (FnDecl->getNumParams() == 0)
11288 return SemaRef.Diag(FnDecl->getLocation(),
11289 diag::err_operator_new_delete_too_few_parameters)
11290 << FnDecl->getDeclName();
11291
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000011292 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000011293 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
11294 if (FirstParamType->isDependentType())
11295 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
11296 << FnDecl->getDeclName() << ExpectedFirstParamType;
11297
11298 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000011299 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000011300 ExpectedFirstParamType)
11301 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
11302 << FnDecl->getDeclName() << ExpectedFirstParamType;
11303
11304 return false;
11305}
11306
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000011307static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000011308CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000011309 // C++ [basic.stc.dynamic.allocation]p1:
11310 // A program is ill-formed if an allocation function is declared in a
11311 // namespace scope other than global scope or declared static in global
11312 // scope.
11313 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11314 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000011315
11316 CanQualType SizeTy =
11317 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
11318
11319 // C++ [basic.stc.dynamic.allocation]p1:
11320 // The return type shall be void*. The first parameter shall have type
11321 // std::size_t.
11322 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
11323 SizeTy,
11324 diag::err_operator_new_dependent_param_type,
11325 diag::err_operator_new_param_type))
11326 return true;
11327
11328 // C++ [basic.stc.dynamic.allocation]p1:
11329 // The first parameter shall not have an associated default argument.
11330 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000011331 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000011332 diag::err_operator_new_default_arg)
11333 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
11334
11335 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000011336}
11337
11338static bool
Richard Smith444d3842012-10-20 08:26:51 +000011339CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000011340 // C++ [basic.stc.dynamic.deallocation]p1:
11341 // A program is ill-formed if deallocation functions are declared in a
11342 // namespace scope other than global scope or declared static in global
11343 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000011344 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
11345 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000011346
11347 // C++ [basic.stc.dynamic.deallocation]p2:
11348 // Each deallocation function shall return void and its first parameter
11349 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000011350 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
11351 SemaRef.Context.VoidPtrTy,
11352 diag::err_operator_delete_dependent_param_type,
11353 diag::err_operator_delete_param_type))
11354 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000011355
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000011356 return false;
11357}
11358
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011359/// CheckOverloadedOperatorDeclaration - Check whether the declaration
11360/// of this overloaded operator is well-formed. If so, returns false;
11361/// otherwise, emits appropriate diagnostics and returns true.
11362bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011363 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011364 "Expected an overloaded operator declaration");
11365
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011366 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
11367
Mike Stump1eb44332009-09-09 15:08:12 +000011368 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011369 // The allocation and deallocation functions, operator new,
11370 // operator new[], operator delete and operator delete[], are
11371 // described completely in 3.7.3. The attributes and restrictions
11372 // found in the rest of this subclause do not apply to them unless
11373 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000011374 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000011375 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000011376
Anders Carlssona3ccda52009-12-12 00:26:23 +000011377 if (Op == OO_New || Op == OO_Array_New)
11378 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011379
11380 // C++ [over.oper]p6:
11381 // An operator function shall either be a non-static member
11382 // function or be a non-member function and have at least one
11383 // parameter whose type is a class, a reference to a class, an
11384 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011385 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
11386 if (MethodDecl->isStatic())
11387 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011388 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011389 } else {
11390 bool ClassOrEnumParam = false;
Stephen Hines651f13c2014-04-23 16:59:28 -070011391 for (auto Param : FnDecl->params()) {
11392 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000011393 if (ParamType->isDependentType() || ParamType->isRecordType() ||
11394 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011395 ClassOrEnumParam = true;
11396 break;
11397 }
11398 }
11399
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011400 if (!ClassOrEnumParam)
11401 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011402 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011403 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011404 }
11405
11406 // C++ [over.oper]p8:
11407 // An operator function cannot have default arguments (8.3.6),
11408 // except where explicitly stated below.
11409 //
Mike Stump1eb44332009-09-09 15:08:12 +000011410 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011411 // (C++ [over.call]p1).
11412 if (Op != OO_Call) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011413 for (auto Param : FnDecl->params()) {
11414 if (Param->hasDefaultArg())
11415 return Diag(Param->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000011416 diag::err_operator_overload_default_arg)
Stephen Hines651f13c2014-04-23 16:59:28 -070011417 << FnDecl->getDeclName() << Param->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011418 }
11419 }
11420
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000011421 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
11422 { false, false, false }
11423#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
11424 , { Unary, Binary, MemberOnly }
11425#include "clang/Basic/OperatorKinds.def"
11426 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011427
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000011428 bool CanBeUnaryOperator = OperatorUses[Op][0];
11429 bool CanBeBinaryOperator = OperatorUses[Op][1];
11430 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011431
11432 // C++ [over.oper]p8:
11433 // [...] Operator functions cannot have more or fewer parameters
11434 // than the number required for the corresponding operator, as
11435 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000011436 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011437 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011438 if (Op != OO_Call &&
11439 ((NumParams == 1 && !CanBeUnaryOperator) ||
11440 (NumParams == 2 && !CanBeBinaryOperator) ||
11441 (NumParams < 1) || (NumParams > 2))) {
11442 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000011443 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000011444 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000011445 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000011446 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000011447 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000011448 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000011449 assert(CanBeBinaryOperator &&
11450 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000011451 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000011452 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011453
Chris Lattner416e46f2008-11-21 07:57:12 +000011454 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011455 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011456 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000011457
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011458 // Overloaded operators other than operator() cannot be variadic.
11459 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000011460 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011461 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011462 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011463 }
11464
11465 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011466 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
11467 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000011468 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000011469 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011470 }
11471
11472 // C++ [over.inc]p1:
11473 // The user-defined function called operator++ implements the
11474 // prefix and postfix ++ operator. If this function is a member
11475 // function with no parameters, or a non-member function with one
11476 // parameter of class or enumeration type, it defines the prefix
11477 // increment operator ++ for objects of that type. If the function
11478 // is a member function with one parameter (which shall be of type
11479 // int) or a non-member function with two parameters (the second
11480 // of which shall be of type int), it defines the postfix
11481 // increment operator ++ for objects of that type.
11482 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
11483 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
Stephen Hines651f13c2014-04-23 16:59:28 -070011484 QualType ParamType = LastParam->getType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011485
Stephen Hines651f13c2014-04-23 16:59:28 -070011486 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
11487 !ParamType->isDependentType())
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000011488 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000011489 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000011490 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011491 }
11492
Douglas Gregor43c7bad2008-11-17 16:14:12 +000011493 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000011494}
Chris Lattner5a003a42008-12-17 07:09:26 +000011495
Sean Hunta6c058d2010-01-13 09:01:02 +000011496/// CheckLiteralOperatorDeclaration - Check whether the declaration
11497/// of this literal operator function is well-formed. If so, returns
11498/// false; otherwise, emits appropriate diagnostics and returns true.
11499bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000011500 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000011501 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
11502 << FnDecl->getDeclName();
11503 return true;
11504 }
11505
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011506 if (FnDecl->isExternC()) {
11507 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
11508 return true;
11509 }
11510
Sean Hunta6c058d2010-01-13 09:01:02 +000011511 bool Valid = false;
11512
Richard Smith36f5cfe2012-03-09 08:00:36 +000011513 // This might be the definition of a literal operator template.
11514 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
11515 // This might be a specialization of a literal operator template.
11516 if (!TpDecl)
11517 TpDecl = FnDecl->getPrimaryTemplate();
11518
Richard Smithb328e292013-10-07 19:57:58 +000011519 // template <char...> type operator "" name() and
11520 // template <class T, T...> type operator "" name() are the only valid
11521 // template signatures, and the only valid signatures with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000011522 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011523 if (FnDecl->param_size() == 0) {
Richard Smithb328e292013-10-07 19:57:58 +000011524 // Must have one or two template parameters
Sean Hunt216c2782010-04-07 23:11:06 +000011525 TemplateParameterList *Params = TpDecl->getTemplateParameters();
11526 if (Params->size() == 1) {
11527 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000011528 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000011529
Sean Hunt216c2782010-04-07 23:11:06 +000011530 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000011531 if (PmDecl && PmDecl->isTemplateParameterPack() &&
11532 Context.hasSameType(PmDecl->getType(), Context.CharTy))
11533 Valid = true;
Richard Smithb328e292013-10-07 19:57:58 +000011534 } else if (Params->size() == 2) {
11535 TemplateTypeParmDecl *PmType =
11536 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
11537 NonTypeTemplateParmDecl *PmArgs =
11538 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
11539
11540 // The second template parameter must be a parameter pack with the
11541 // first template parameter as its type.
11542 if (PmType && PmArgs &&
11543 !PmType->isTemplateParameterPack() &&
11544 PmArgs->isTemplateParameterPack()) {
11545 const TemplateTypeParmType *TArgs =
11546 PmArgs->getType()->getAs<TemplateTypeParmType>();
11547 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
11548 TArgs->getIndex() == PmType->getIndex()) {
11549 Valid = true;
11550 if (ActiveTemplateInstantiations.empty())
11551 Diag(FnDecl->getLocation(),
11552 diag::ext_string_literal_operator_template);
11553 }
11554 }
Sean Hunt216c2782010-04-07 23:11:06 +000011555 }
11556 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011557 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000011558 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000011559 FunctionDecl::param_iterator Param = FnDecl->param_begin();
11560
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011561 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000011562
Sean Hunt30019c02010-04-07 22:57:35 +000011563 // unsigned long long int, long double, and any character type are allowed
11564 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000011565 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11566 Context.hasSameType(T, Context.LongDoubleTy) ||
11567 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000011568 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000011569 Context.hasSameType(T, Context.Char16Ty) ||
11570 Context.hasSameType(T, Context.Char32Ty)) {
11571 if (++Param == FnDecl->param_end())
11572 Valid = true;
11573 goto FinishedParams;
11574 }
11575
Sean Hunt30019c02010-04-07 22:57:35 +000011576 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000011577 const PointerType *PT = T->getAs<PointerType>();
11578 if (!PT)
11579 goto FinishedParams;
11580 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011581 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000011582 goto FinishedParams;
11583 T = T.getUnqualifiedType();
11584
11585 // Move on to the second parameter;
11586 ++Param;
11587
11588 // If there is no second parameter, the first must be a const char *
11589 if (Param == FnDecl->param_end()) {
11590 if (Context.hasSameType(T, Context.CharTy))
11591 Valid = true;
11592 goto FinishedParams;
11593 }
11594
11595 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11596 // are allowed as the first parameter to a two-parameter function
11597 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000011598 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000011599 Context.hasSameType(T, Context.Char16Ty) ||
11600 Context.hasSameType(T, Context.Char32Ty)))
11601 goto FinishedParams;
11602
11603 // The second and final parameter must be an std::size_t
11604 T = (*Param)->getType().getUnqualifiedType();
11605 if (Context.hasSameType(T, Context.getSizeType()) &&
11606 ++Param == FnDecl->param_end())
11607 Valid = true;
11608 }
11609
11610 // FIXME: This diagnostic is absolutely terrible.
11611FinishedParams:
11612 if (!Valid) {
11613 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11614 << FnDecl->getDeclName();
11615 return true;
11616 }
11617
Richard Smitha9e88b22012-03-09 08:16:22 +000011618 // A parameter-declaration-clause containing a default argument is not
11619 // equivalent to any of the permitted forms.
Stephen Hines651f13c2014-04-23 16:59:28 -070011620 for (auto Param : FnDecl->params()) {
11621 if (Param->hasDefaultArg()) {
11622 Diag(Param->getDefaultArgRange().getBegin(),
Richard Smitha9e88b22012-03-09 08:16:22 +000011623 diag::err_literal_operator_default_argument)
Stephen Hines651f13c2014-04-23 16:59:28 -070011624 << Param->getDefaultArgRange();
Richard Smitha9e88b22012-03-09 08:16:22 +000011625 break;
11626 }
11627 }
11628
Richard Smith2fb4ae32012-03-08 02:39:21 +000011629 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000011630 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11631 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000011632 // C++11 [usrlit.suffix]p1:
11633 // Literal suffix identifiers that do not start with an underscore
11634 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000011635 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11636 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000011637 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000011638
Sean Hunta6c058d2010-01-13 09:01:02 +000011639 return false;
11640}
11641
Douglas Gregor074149e2009-01-05 19:45:36 +000011642/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11643/// linkage specification, including the language and (if present)
Stephen Hines651f13c2014-04-23 16:59:28 -070011644/// the '{'. ExternLoc is the location of the 'extern', Lang is the
11645/// language string literal. LBraceLoc, if valid, provides the location of
Douglas Gregor074149e2009-01-05 19:45:36 +000011646/// the '{' brace. Otherwise, this linkage specification does not
11647/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000011648Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -070011649 Expr *LangStr,
Chris Lattner7d642712010-11-09 20:15:55 +000011650 SourceLocation LBraceLoc) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011651 StringLiteral *Lit = cast<StringLiteral>(LangStr);
11652 if (!Lit->isAscii()) {
11653 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
11654 << LangStr->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011655 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -070011656 }
11657
11658 StringRef Lang = Lit->getString();
Chris Lattnercc98eac2008-12-17 07:13:27 +000011659 LinkageSpecDecl::LanguageIDs Language;
Stephen Hines651f13c2014-04-23 16:59:28 -070011660 if (Lang == "C")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011661 Language = LinkageSpecDecl::lang_c;
Stephen Hines651f13c2014-04-23 16:59:28 -070011662 else if (Lang == "C++")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011663 Language = LinkageSpecDecl::lang_cxx;
11664 else {
Stephen Hines651f13c2014-04-23 16:59:28 -070011665 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
11666 << LangStr->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011667 return nullptr;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011668 }
Mike Stump1eb44332009-09-09 15:08:12 +000011669
Chris Lattnercc98eac2008-12-17 07:13:27 +000011670 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000011671
Stephen Hines651f13c2014-04-23 16:59:28 -070011672 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
11673 LangStr->getExprLoc(), Language,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000011674 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011675 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000011676 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000011677 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011678}
11679
Abramo Bagnara35f9a192010-07-30 16:47:02 +000011680/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000011681/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11682/// valid, it's the position of the closing '}' brace in a linkage
11683/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000011684Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011685 Decl *LinkageSpec,
11686 SourceLocation RBraceLoc) {
Stephen Hines651f13c2014-04-23 16:59:28 -070011687 if (RBraceLoc.isValid()) {
11688 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11689 LSDecl->setRBraceLoc(RBraceLoc);
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011690 }
Stephen Hines651f13c2014-04-23 16:59:28 -070011691 PopDeclContext();
Douglas Gregor074149e2009-01-05 19:45:36 +000011692 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000011693}
11694
Michael Han684aa732013-02-22 17:15:32 +000011695Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11696 AttributeList *AttrList,
11697 SourceLocation SemiLoc) {
11698 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11699 // Attribute declarations appertain to empty declaration so we handle
11700 // them here.
11701 if (AttrList)
11702 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000011703
Michael Han684aa732013-02-22 17:15:32 +000011704 CurContext->addDecl(ED);
11705 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000011706}
11707
Douglas Gregord308e622009-05-18 20:51:54 +000011708/// \brief Perform semantic analysis for the variable declaration that
11709/// occurs within a C++ catch clause, returning the newly-created
11710/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011711VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000011712 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011713 SourceLocation StartLoc,
11714 SourceLocation Loc,
11715 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000011716 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000011717 QualType ExDeclType = TInfo->getType();
11718
Sebastian Redl4b07b292008-12-22 19:15:10 +000011719 // Arrays and functions decay.
11720 if (ExDeclType->isArrayType())
11721 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11722 else if (ExDeclType->isFunctionType())
11723 ExDeclType = Context.getPointerType(ExDeclType);
11724
11725 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11726 // The exception-declaration shall not denote a pointer or reference to an
11727 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011728 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000011729 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000011730 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011731 Invalid = true;
11732 }
Douglas Gregord308e622009-05-18 20:51:54 +000011733
Sebastian Redl4b07b292008-12-22 19:15:10 +000011734 QualType BaseType = ExDeclType;
11735 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000011736 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000011737 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011738 BaseType = Ptr->getPointeeType();
11739 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011740 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000011741 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011742 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011743 BaseType = Ref->getPointeeType();
11744 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011745 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011746 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011747 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000011748 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000011749 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011750
Mike Stump1eb44332009-09-09 15:08:12 +000011751 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000011752 RequireNonAbstractType(Loc, ExDeclType,
11753 diag::err_abstract_type_in_decl,
11754 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000011755 Invalid = true;
11756
John McCall5a180392010-07-24 00:37:23 +000011757 // Only the non-fragile NeXT runtime currently supports C++ catches
11758 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000011759 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000011760 QualType T = ExDeclType;
11761 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11762 T = RT->getPointeeType();
11763
11764 if (T->isObjCObjectType()) {
11765 Diag(Loc, diag::err_objc_object_catch);
11766 Invalid = true;
11767 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000011768 // FIXME: should this be a test for macosx-fragile specifically?
11769 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000011770 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000011771 }
11772 }
11773
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011774 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000011775 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000011776 ExDecl->setExceptionVariable(true);
11777
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011778 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011779 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011780 Invalid = true;
11781
Douglas Gregorc41b8782011-07-06 18:14:43 +000011782 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000011783 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000011784 // Insulate this from anything else we might currently be parsing.
11785 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11786
Douglas Gregor6d182892010-03-05 23:38:39 +000011787 // C++ [except.handle]p16:
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011788 // The object declared in an exception-declaration or, if the
11789 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6d182892010-03-05 23:38:39 +000011790 // copy-initialized (8.5) from the exception object. [...]
11791 // The object is destroyed when the handler exits, after the destruction
11792 // of any automatic objects initialized within the handler.
11793 //
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011794 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6d182892010-03-05 23:38:39 +000011795 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000011796 QualType initType = ExDeclType;
11797
11798 InitializedEntity entity =
11799 InitializedEntity::InitializeVariable(ExDecl);
11800 InitializationKind initKind =
11801 InitializationKind::CreateCopy(Loc, SourceLocation());
11802
11803 Expr *opaqueValue =
11804 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011805 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11806 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000011807 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000011808 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000011809 else {
11810 // If the constructor used was non-trivial, set this as the
11811 // "initializer".
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011812 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
John McCalle996ffd2011-02-16 08:02:54 +000011813 if (!construct->getConstructor()->isTrivial()) {
11814 Expr *init = MaybeCreateExprWithCleanups(construct);
11815 ExDecl->setInit(init);
11816 }
11817
11818 // And make sure it's destructable.
11819 FinalizeVarWithDestructor(ExDecl, recordType);
11820 }
Douglas Gregor6d182892010-03-05 23:38:39 +000011821 }
11822 }
11823
Douglas Gregord308e622009-05-18 20:51:54 +000011824 if (Invalid)
11825 ExDecl->setInvalidDecl();
11826
11827 return ExDecl;
11828}
11829
11830/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11831/// handler.
John McCalld226f652010-08-21 09:40:31 +000011832Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000011833 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000011834 bool Invalid = D.isInvalidType();
11835
11836 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000011837 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11838 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000011839 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11840 D.getIdentifierLoc());
11841 Invalid = true;
11842 }
11843
Sebastian Redl4b07b292008-12-22 19:15:10 +000011844 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000011845 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000011846 LookupOrdinaryName,
11847 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011848 // The scope should be freshly made just for us. There is just no way
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011849 // it contains any previous declaration, except for function parameters in
11850 // a function-try-block's catch statement.
John McCalld226f652010-08-21 09:40:31 +000011851 assert(!S->isDeclScope(PrevDecl));
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011852 if (isDeclInScope(PrevDecl, CurContext, S)) {
11853 Diag(D.getIdentifierLoc(), diag::err_redefinition)
11854 << D.getIdentifier();
11855 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
11856 Invalid = true;
11857 } else if (PrevDecl->isTemplateParameter())
Sebastian Redl4b07b292008-12-22 19:15:10 +000011858 // Maybe we will complain about the shadowed template parameter.
11859 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000011860 }
11861
Chris Lattnereaaebc72009-04-25 08:06:05 +000011862 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011863 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11864 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000011865 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011866 }
11867
Douglas Gregor83cb9422010-09-09 17:09:21 +000011868 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000011869 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011870 D.getIdentifierLoc(),
11871 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000011872 if (Invalid)
11873 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000011874
Sebastian Redl4b07b292008-12-22 19:15:10 +000011875 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011876 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000011877 PushOnScopeChains(ExDecl, S);
11878 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011879 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000011880
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011881 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000011882 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011883}
Anders Carlssonfb311762009-03-14 00:25:26 +000011884
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011885Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000011886 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000011887 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011888 SourceLocation RParenLoc) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011889 StringLiteral *AssertMessage =
11890 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
Anders Carlssonfb311762009-03-14 00:25:26 +000011891
Richard Smithe3f470a2012-07-11 22:37:56 +000011892 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011893 return nullptr;
Richard Smithe3f470a2012-07-11 22:37:56 +000011894
11895 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11896 AssertMessage, RParenLoc, false);
11897}
11898
11899Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11900 Expr *AssertExpr,
11901 StringLiteral *AssertMessage,
11902 SourceLocation RParenLoc,
11903 bool Failed) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011904 assert(AssertExpr != nullptr && "Expected non-null condition");
Richard Smithe3f470a2012-07-11 22:37:56 +000011905 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11906 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000011907 // In a static_assert-declaration, the constant-expression shall be a
11908 // constant expression that can be contextually converted to bool.
11909 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11910 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011911 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000011912
Richard Smithdaaefc52011-12-14 23:32:26 +000011913 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000011914 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011915 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000011916 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011917 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000011918
Richard Smithe3f470a2012-07-11 22:37:56 +000011919 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011920 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000011921 llvm::raw_svector_ostream Msg(MsgBuffer);
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011922 if (AssertMessage)
11923 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011924 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Stephen Hinesc568f1e2014-07-21 00:47:37 -070011925 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000011926 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000011927 }
Anders Carlssonc3082412009-03-14 00:33:21 +000011928 }
Mike Stump1eb44332009-09-09 15:08:12 +000011929
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011930 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000011931 AssertExpr, AssertMessage, RParenLoc,
11932 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000011933
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011934 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000011935 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000011936}
Sebastian Redl50de12f2009-03-24 22:27:57 +000011937
Douglas Gregor1d869352010-04-07 16:53:43 +000011938/// \brief Perform semantic analysis of the given friend type declaration.
11939///
11940/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000011941FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000011942 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011943 TypeSourceInfo *TSInfo) {
11944 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11945
11946 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000011947 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000011948
Richard Smith6b130222011-10-18 21:39:00 +000011949 // C++03 [class.friend]p2:
11950 // An elaborated-type-specifier shall be used in a friend declaration
11951 // for a class.*
11952 //
11953 // * The class-key of the elaborated-type-specifier is required.
11954 if (!ActiveTemplateInstantiations.empty()) {
11955 // Do not complain about the form of friend template types during
11956 // template instantiation; we will already have complained when the
11957 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011958 } else {
11959 if (!T->isElaboratedTypeSpecifier()) {
11960 // If we evaluated the type to a record type, suggest putting
11961 // a tag in front.
11962 if (const RecordType *RT = T->getAs<RecordType>()) {
11963 RecordDecl *RD = RT->getDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070011964
11965 SmallString<16> InsertionText(" ");
11966 InsertionText += RD->getKindName();
11967
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011968 Diag(TypeRange.getBegin(),
11969 getLangOpts().CPlusPlus11 ?
11970 diag::warn_cxx98_compat_unelaborated_friend_type :
11971 diag::ext_unelaborated_friend_type)
11972 << (unsigned) RD->getTagKind()
11973 << T
11974 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11975 InsertionText);
11976 } else {
11977 Diag(FriendLoc,
11978 getLangOpts().CPlusPlus11 ?
11979 diag::warn_cxx98_compat_nonclass_type_friend :
11980 diag::ext_nonclass_type_friend)
11981 << T
11982 << TypeRange;
11983 }
11984 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000011985 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000011986 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011987 diag::warn_cxx98_compat_enum_friend :
11988 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000011989 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000011990 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000011991 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011992
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011993 // C++11 [class.friend]p3:
11994 // A friend declaration that does not declare a function shall have one
11995 // of the following forms:
11996 // friend elaborated-type-specifier ;
11997 // friend simple-type-specifier ;
11998 // friend typename-specifier ;
11999 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
12000 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
12001 }
Richard Smithd6f80da2012-09-20 01:31:00 +000012002
Douglas Gregor06245bf2010-04-07 17:57:12 +000012003 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000012004 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000012005 // the friend declaration is ignored.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012006 return FriendDecl::Create(Context, CurContext,
12007 TSInfo->getTypeLoc().getLocStart(), TSInfo,
12008 FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000012009}
12010
John McCall9a34edb2010-10-19 01:40:49 +000012011/// Handle a friend tag declaration where the scope specifier was
12012/// templated.
12013Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
12014 unsigned TagSpec, SourceLocation TagLoc,
12015 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000012016 IdentifierInfo *Name,
12017 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000012018 AttributeList *Attr,
12019 MultiTemplateParamsArg TempParamLists) {
12020 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12021
12022 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000012023 bool Invalid = false;
12024
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000012025 if (TemplateParameterList *TemplateParams =
12026 MatchTemplateParametersToScopeSpecifier(
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012027 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000012028 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000012029 if (TemplateParams->size() > 0) {
12030 // This is a declaration of a class template.
12031 if (Invalid)
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012032 return nullptr;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000012033
Stephen Hines176edba2014-12-01 14:53:08 -080012034 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
12035 NameLoc, Attr, TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000012036 /*ModulePrivateLoc=*/SourceLocation(),
Stephen Hines176edba2014-12-01 14:53:08 -080012037 FriendLoc, TempParamLists.size() - 1,
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012038 TempParamLists.data()).get();
John McCall9a34edb2010-10-19 01:40:49 +000012039 } else {
12040 // The "template<>" header is extraneous.
12041 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12042 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12043 isExplicitSpecialization = true;
12044 }
12045 }
12046
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012047 if (Invalid) return nullptr;
John McCall9a34edb2010-10-19 01:40:49 +000012048
John McCall9a34edb2010-10-19 01:40:49 +000012049 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000012050 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000012051 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000012052 isAllExplicitSpecializations = false;
12053 break;
12054 }
12055 }
12056
12057 // FIXME: don't ignore attributes.
12058
12059 // If it's explicit specializations all the way down, just forget
12060 // about the template header and build an appropriate non-templated
12061 // friend. TODO: for source fidelity, remember the headers.
12062 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000012063 if (SS.isEmpty()) {
12064 bool Owned = false;
12065 bool IsDependent = false;
12066 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
Stephen Hines651f13c2014-04-23 16:59:28 -070012067 Attr, AS_public,
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000012068 /*ModulePrivateLoc=*/SourceLocation(),
Stephen Hines651f13c2014-04-23 16:59:28 -070012069 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000012070 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000012071 /*ScopedEnumUsesClassTag=*/false,
Stephen Hines651f13c2014-04-23 16:59:28 -070012072 /*UnderlyingType=*/TypeResult(),
12073 /*IsTypeSpecifier=*/false);
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000012074 }
Stephen Hines651f13c2014-04-23 16:59:28 -070012075
Douglas Gregor2494dd02011-03-01 01:34:45 +000012076 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000012077 ElaboratedTypeKeyword Keyword
12078 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000012079 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000012080 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000012081 if (T.isNull())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012082 return nullptr;
John McCall9a34edb2010-10-19 01:40:49 +000012083
12084 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
12085 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000012086 DependentNameTypeLoc TL =
12087 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000012088 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000012089 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000012090 TL.setNameLoc(NameLoc);
12091 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000012092 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000012093 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000012094 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000012095 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000012096 }
12097
12098 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000012099 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000012100 Friend->setAccess(AS_public);
12101 CurContext->addDecl(Friend);
12102 return Friend;
12103 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000012104
12105 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
12106
12107
John McCall9a34edb2010-10-19 01:40:49 +000012108
12109 // Handle the case of a templated-scope friend class. e.g.
12110 // template <class T> class A<T>::B;
12111 // FIXME: we don't support these right now.
Richard Smithce6426f2013-11-08 18:59:56 +000012112 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
12113 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
John McCall9a34edb2010-10-19 01:40:49 +000012114 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
12115 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
12116 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000012117 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000012118 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000012119 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000012120 TL.setNameLoc(NameLoc);
12121
12122 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000012123 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000012124 Friend->setAccess(AS_public);
12125 Friend->setUnsupportedFriend(true);
12126 CurContext->addDecl(Friend);
12127 return Friend;
12128}
12129
12130
John McCalldd4a3b02009-09-16 22:47:08 +000012131/// Handle a friend type declaration. This works in tandem with
12132/// ActOnTag.
12133///
12134/// Notes on friend class templates:
12135///
12136/// We generally treat friend class declarations as if they were
12137/// declaring a class. So, for example, the elaborated type specifier
12138/// in a friend declaration is required to obey the restrictions of a
12139/// class-head (i.e. no typedefs in the scope chain), template
12140/// parameters are required to match up with simple template-ids, &c.
12141/// However, unlike when declaring a template specialization, it's
12142/// okay to refer to a template specialization without an empty
12143/// template parameter declaration, e.g.
12144/// friend class A<T>::B<unsigned>;
12145/// We permit this as a special case; if there are any template
12146/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000012147/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000012148Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000012149 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000012150 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000012151
12152 assert(DS.isFriendSpecified());
12153 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12154
John McCalldd4a3b02009-09-16 22:47:08 +000012155 // Try to convert the decl specifier to a type. This works for
12156 // friend templates because ActOnTag never produces a ClassTemplateDecl
12157 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000012158 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000012159 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
12160 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000012161 if (TheDeclarator.isInvalidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012162 return nullptr;
John McCall67d1a672009-08-06 02:15:43 +000012163
Douglas Gregor6ccab972010-12-16 01:14:37 +000012164 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012165 return nullptr;
Douglas Gregor6ccab972010-12-16 01:14:37 +000012166
John McCalldd4a3b02009-09-16 22:47:08 +000012167 // This is definitely an error in C++98. It's probably meant to
12168 // be forbidden in C++0x, too, but the specification is just
12169 // poorly written.
12170 //
12171 // The problem is with declarations like the following:
12172 // template <T> friend A<T>::foo;
12173 // where deciding whether a class C is a friend or not now hinges
12174 // on whether there exists an instantiation of A that causes
12175 // 'foo' to equal C. There are restrictions on class-heads
12176 // (which we declare (by fiat) elaborated friend declarations to
12177 // be) that makes this tractable.
12178 //
12179 // FIXME: handle "template <> friend class A<T>;", which
12180 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000012181 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000012182 Diag(Loc, diag::err_tagless_friend_type_template)
12183 << DS.getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012184 return nullptr;
John McCalldd4a3b02009-09-16 22:47:08 +000012185 }
Douglas Gregor1d869352010-04-07 16:53:43 +000012186
John McCall02cace72009-08-28 07:59:38 +000012187 // C++98 [class.friend]p1: A friend of a class is a function
12188 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000012189 // This is fixed in DR77, which just barely didn't make the C++03
12190 // deadline. It's also a very silly restriction that seriously
12191 // affects inner classes and which nobody else seems to implement;
12192 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000012193 //
12194 // But note that we could warn about it: it's always useless to
12195 // friend one of your own members (it's not, however, worthless to
12196 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000012197
John McCalldd4a3b02009-09-16 22:47:08 +000012198 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000012199 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000012200 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000012201 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000012202 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000012203 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000012204 DS.getFriendSpecLoc());
12205 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000012206 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000012207
12208 if (!D)
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012209 return nullptr;
12210
John McCalldd4a3b02009-09-16 22:47:08 +000012211 D->setAccess(AS_public);
12212 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000012213
John McCalld226f652010-08-21 09:40:31 +000012214 return D;
John McCall02cace72009-08-28 07:59:38 +000012215}
12216
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000012217NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
12218 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000012219 const DeclSpec &DS = D.getDeclSpec();
12220
12221 assert(DS.isFriendSpecified());
12222 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
12223
12224 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000012225 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000012226
12227 // C++ [class.friend]p1
12228 // A friend of a class is a function or class....
12229 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000012230 // It *doesn't* see through dependent types, which is correct
12231 // according to [temp.arg.type]p3:
12232 // If a declaration acquires a function type through a
12233 // type dependent on a template-parameter and this causes
12234 // a declaration that does not use the syntactic form of a
12235 // function declarator to have a function type, the program
12236 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000012237 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000012238 Diag(Loc, diag::err_unexpected_friend);
12239
12240 // It might be worthwhile to try to recover by creating an
12241 // appropriate declaration.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012242 return nullptr;
John McCall67d1a672009-08-06 02:15:43 +000012243 }
12244
12245 // C++ [namespace.memdef]p3
12246 // - If a friend declaration in a non-local class first declares a
12247 // class or function, the friend class or function is a member
12248 // of the innermost enclosing namespace.
12249 // - The name of the friend is not found by simple name lookup
12250 // until a matching declaration is provided in that namespace
12251 // scope (either before or after the class declaration granting
12252 // friendship).
12253 // - If a friend function is called, its name may be found by the
12254 // name lookup that considers functions from namespaces and
12255 // classes associated with the types of the function arguments.
12256 // - When looking for a prior declaration of a class or a function
12257 // declared as a friend, scopes outside the innermost enclosing
12258 // namespace scope are not considered.
12259
John McCall337ec3d2010-10-12 23:13:28 +000012260 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000012261 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
12262 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000012263 assert(Name);
12264
Douglas Gregor6ccab972010-12-16 01:14:37 +000012265 // Check for unexpanded parameter packs.
12266 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
12267 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
12268 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012269 return nullptr;
Douglas Gregor6ccab972010-12-16 01:14:37 +000012270
John McCall67d1a672009-08-06 02:15:43 +000012271 // The context we found the declaration in, or in which we should
12272 // create the declaration.
12273 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000012274 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000012275 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000012276 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000012277
Richard Smith4e9686b2013-08-09 04:35:01 +000012278 // There are five cases here.
12279 // - There's no scope specifier and we're in a local class. Only look
12280 // for functions declared in the immediately-enclosing block scope.
12281 // We recover from invalid scope qualifiers as if they just weren't there.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012282 FunctionDecl *FunctionContainingLocalClass = nullptr;
Richard Smith4e9686b2013-08-09 04:35:01 +000012283 if ((SS.isInvalid() || !SS.isSet()) &&
12284 (FunctionContainingLocalClass =
12285 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
12286 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000012287 // If a friend declaration appears in a local class and the name
12288 // specified is an unqualified name, a prior declaration is
12289 // looked up without considering scopes that are outside the
12290 // innermost enclosing non-class scope. For a friend function
12291 // declaration, if there is no prior declaration, the program is
12292 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000012293
12294 // Find the innermost enclosing non-class scope. This is the block
12295 // scope containing the local class definition (or for a nested class,
12296 // the outer local class).
12297 DCScope = S->getFnParent();
12298
12299 // Look up the function name in the scope.
12300 Previous.clear(LookupLocalFriendName);
12301 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
12302
12303 if (!Previous.empty()) {
12304 // All possible previous declarations must have the same context:
12305 // either they were declared at block scope or they are members of
12306 // one of the enclosing local classes.
12307 DC = Previous.getRepresentativeDecl()->getDeclContext();
12308 } else {
12309 // This is ill-formed, but provide the context that we would have
12310 // declared the function in, if we were permitted to, for error recovery.
12311 DC = FunctionContainingLocalClass;
12312 }
Richard Smitha41c97a2013-09-20 01:15:31 +000012313 adjustContextForLocalExternDecl(DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000012314
12315 // C++ [class.friend]p6:
12316 // A function can be defined in a friend declaration of a class if and
12317 // only if the class is a non-local class (9.8), the function name is
12318 // unqualified, and the function has namespace scope.
12319 if (D.isFunctionDefinition()) {
12320 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
12321 }
12322
12323 // - There's no scope specifier, in which case we just go to the
12324 // appropriate scope and look for a function or function template
12325 // there as appropriate.
12326 } else if (SS.isInvalid() || !SS.isSet()) {
12327 // C++11 [namespace.memdef]p3:
12328 // If the name in a friend declaration is neither qualified nor
12329 // a template-id and the declaration is a function or an
12330 // elaborated-type-specifier, the lookup to determine whether
12331 // the entity has been previously declared shall not consider
12332 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000012333 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000012334
John McCall29ae6e52010-10-13 05:45:15 +000012335 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000012336 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000012337
Rafael Espindola11dc6342013-04-25 20:12:36 +000012338 // Skip class contexts. If someone can cite chapter and verse
12339 // for this behavior, that would be nice --- it's what GCC and
12340 // EDG do, and it seems like a reasonable intent, but the spec
12341 // really only says that checks for unqualified existing
12342 // declarations should stop at the nearest enclosing namespace,
12343 // not that they should only consider the nearest enclosing
12344 // namespace.
12345 while (DC->isRecord())
12346 DC = DC->getParent();
12347
12348 DeclContext *LookupDC = DC;
12349 while (LookupDC->isTransparentContext())
12350 LookupDC = LookupDC->getParent();
12351
12352 while (true) {
12353 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000012354
Rafael Espindola11dc6342013-04-25 20:12:36 +000012355 if (!Previous.empty()) {
12356 DC = LookupDC;
12357 break;
John McCall8a407372010-10-14 22:22:28 +000012358 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000012359
12360 if (isTemplateId) {
12361 if (isa<TranslationUnitDecl>(LookupDC)) break;
12362 } else {
12363 if (LookupDC->isFileContext()) break;
12364 }
12365 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000012366 }
12367
John McCall380aaa42010-10-13 06:22:15 +000012368 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000012369
John McCall337ec3d2010-10-12 23:13:28 +000012370 // - There's a non-dependent scope specifier, in which case we
12371 // compute it and do a previous lookup there for a function
12372 // or function template.
12373 } else if (!SS.getScopeRep()->isDependent()) {
12374 DC = computeDeclContext(SS);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012375 if (!DC) return nullptr;
John McCall337ec3d2010-10-12 23:13:28 +000012376
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012377 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
John McCall337ec3d2010-10-12 23:13:28 +000012378
12379 LookupQualifiedName(Previous, DC);
12380
12381 // Ignore things found implicitly in the wrong scope.
12382 // TODO: better diagnostics for this case. Suggesting the right
12383 // qualified scope would be nice...
12384 LookupResult::Filter F = Previous.makeFilter();
12385 while (F.hasNext()) {
12386 NamedDecl *D = F.next();
12387 if (!DC->InEnclosingNamespaceSetOf(
12388 D->getDeclContext()->getRedeclContext()))
12389 F.erase();
12390 }
12391 F.done();
12392
12393 if (Previous.empty()) {
12394 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000012395 Diag(Loc, diag::err_qualified_friend_not_found)
12396 << Name << TInfo->getType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012397 return nullptr;
John McCall337ec3d2010-10-12 23:13:28 +000012398 }
12399
12400 // C++ [class.friend]p1: A friend of a class is a function or
12401 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000012402 if (DC->Equals(CurContext))
12403 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000012404 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000012405 diag::warn_cxx98_compat_friend_is_member :
12406 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000012407
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000012408 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000012409 // C++ [class.friend]p6:
12410 // A function can be defined in a friend declaration of a class if and
12411 // only if the class is a non-local class (9.8), the function name is
12412 // unqualified, and the function has namespace scope.
12413 SemaDiagnosticBuilder DB
12414 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
12415
12416 DB << SS.getScopeRep();
12417 if (DC->isFileContext())
12418 DB << FixItHint::CreateRemoval(SS.getRange());
12419 SS.clear();
12420 }
John McCall337ec3d2010-10-12 23:13:28 +000012421
12422 // - There's a scope specifier that does not match any template
12423 // parameter lists, in which case we use some arbitrary context,
12424 // create a method or method template, and wait for instantiation.
12425 // - There's a scope specifier that does match some template
12426 // parameter lists, which we don't handle right now.
12427 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000012428 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000012429 // C++ [class.friend]p6:
12430 // A function can be defined in a friend declaration of a class if and
12431 // only if the class is a non-local class (9.8), the function name is
12432 // unqualified, and the function has namespace scope.
12433 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
12434 << SS.getScopeRep();
12435 }
12436
John McCall337ec3d2010-10-12 23:13:28 +000012437 DC = CurContext;
12438 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000012439 }
Douglas Gregor883af832011-10-10 01:11:59 +000012440
John McCall29ae6e52010-10-13 05:45:15 +000012441 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000012442 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000012443 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
12444 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
12445 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000012446 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000012447 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
12448 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012449 return nullptr;
John McCall67d1a672009-08-06 02:15:43 +000012450 }
John McCall67d1a672009-08-06 02:15:43 +000012451 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000012452
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000012453 // FIXME: This is an egregious hack to cope with cases where the scope stack
12454 // does not contain the declaration context, i.e., in an out-of-line
12455 // definition of a class.
12456 Scope FakeDCScope(S, Scope::DeclScope, Diags);
12457 if (!DCScope) {
12458 FakeDCScope.setEntity(DC);
12459 DCScope = &FakeDCScope;
12460 }
Richard Smith4e9686b2013-08-09 04:35:01 +000012461
Francois Pichetaf0f4d02011-08-14 03:52:19 +000012462 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000012463 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000012464 TemplateParams, AddToScope);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012465 if (!ND) return nullptr;
John McCallab88d972009-08-31 22:39:49 +000012466
Douglas Gregor182ddf02009-09-28 00:08:27 +000012467 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000012468
Richard Smith4e9686b2013-08-09 04:35:01 +000012469 // If we performed typo correction, we might have added a scope specifier
12470 // and changed the decl context.
12471 DC = ND->getDeclContext();
12472
John McCallab88d972009-08-31 22:39:49 +000012473 // Add the function declaration to the appropriate lookup tables,
12474 // adjusting the redeclarations list as necessary. We don't
12475 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000012476 //
John McCallab88d972009-08-31 22:39:49 +000012477 // Also update the scope-based lookup if the target context's
12478 // lookup context is in lexical scope.
12479 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000012480 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000012481 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000012482 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000012483 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000012484 }
John McCall02cace72009-08-28 07:59:38 +000012485
12486 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000012487 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000012488 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000012489 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000012490 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000012491
John McCall1f2e1a92012-08-10 03:15:35 +000012492 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000012493 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000012494 } else {
12495 if (DC->isRecord()) CheckFriendAccess(ND);
12496
John McCall6102ca12010-10-16 06:59:13 +000012497 FunctionDecl *FD;
12498 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
12499 FD = FTD->getTemplatedDecl();
12500 else
12501 FD = cast<FunctionDecl>(ND);
12502
David Majnemerf6a144f2013-06-25 23:09:30 +000012503 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
12504 // default argument expression, that declaration shall be a definition
12505 // and shall be the only declaration of the function or function
12506 // template in the translation unit.
12507 if (functionDeclHasDefaultArgument(FD)) {
12508 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
12509 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
12510 Diag(OldFD->getLocation(), diag::note_previous_declaration);
12511 } else if (!D.isFunctionDefinition())
12512 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
12513 }
12514
John McCall6102ca12010-10-16 06:59:13 +000012515 // Mark templated-scope function declarations as unsupported.
Stephen Hines176edba2014-12-01 14:53:08 -080012516 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
12517 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
12518 << SS.getScopeRep() << SS.getRange()
12519 << cast<CXXRecordDecl>(CurContext);
John McCall6102ca12010-10-16 06:59:13 +000012520 FrD->setUnsupportedFriend(true);
Stephen Hines176edba2014-12-01 14:53:08 -080012521 }
John McCall6102ca12010-10-16 06:59:13 +000012522 }
John McCall337ec3d2010-10-12 23:13:28 +000012523
John McCalld226f652010-08-21 09:40:31 +000012524 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000012525}
12526
John McCalld226f652010-08-21 09:40:31 +000012527void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
12528 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000012529
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000012530 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000012531 if (!Fn) {
12532 Diag(DelLoc, diag::err_deleted_non_function);
12533 return;
12534 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000012535
Douglas Gregoref96ee02012-01-14 16:38:05 +000012536 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000012537 // Don't consider the implicit declaration we generate for explicit
12538 // specializations. FIXME: Do not generate these implicit declarations.
Stephen Hines651f13c2014-04-23 16:59:28 -070012539 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
12540 Prev->getPreviousDecl()) &&
12541 !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000012542 Diag(DelLoc, diag::err_deleted_decl_not_first);
Stephen Hines651f13c2014-04-23 16:59:28 -070012543 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
12544 Prev->isImplicit() ? diag::note_previous_implicit_declaration
12545 : diag::note_previous_declaration);
David Blaikied9cf8262012-06-25 21:55:30 +000012546 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000012547 // If the declaration wasn't the first, we delete the function anyway for
12548 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000012549 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000012550 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000012551
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012552 // dllimport/dllexport cannot be deleted.
12553 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
12554 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
12555 Fn->setInvalidDecl();
12556 }
12557
Richard Smith0ab5b4c2013-04-02 19:38:47 +000012558 if (Fn->isDeleted())
12559 return;
12560
12561 // See if we're deleting a function which is already known to override a
12562 // non-deleted virtual function.
12563 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
12564 bool IssuedDiagnostic = false;
12565 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
12566 E = MD->end_overridden_methods();
12567 I != E; ++I) {
12568 if (!(*MD->begin_overridden_methods())->isDeleted()) {
12569 if (!IssuedDiagnostic) {
12570 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
12571 IssuedDiagnostic = true;
12572 }
12573 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
12574 }
12575 }
12576 }
12577
Stephen Hines651f13c2014-04-23 16:59:28 -070012578 // C++11 [basic.start.main]p3:
12579 // A program that defines main as deleted [...] is ill-formed.
12580 if (Fn->isMain())
12581 Diag(DelLoc, diag::err_deleted_main);
12582
Sean Hunt10620eb2011-05-06 20:44:56 +000012583 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000012584}
Sebastian Redl13e88542009-04-27 21:33:24 +000012585
Sean Hunte4246a62011-05-12 06:15:49 +000012586void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000012587 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000012588
12589 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000012590 if (MD->getParent()->isDependentType()) {
12591 MD->setDefaulted();
12592 MD->setExplicitlyDefaulted();
12593 return;
12594 }
12595
Sean Hunte4246a62011-05-12 06:15:49 +000012596 CXXSpecialMember Member = getSpecialMember(MD);
12597 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000012598 if (!MD->isInvalidDecl())
12599 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000012600 return;
12601 }
12602
12603 MD->setDefaulted();
12604 MD->setExplicitlyDefaulted();
12605
Sean Huntcd10dec2011-05-23 23:14:04 +000012606 // If this definition appears within the record, do the checking when
12607 // the record is complete.
12608 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000012609 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000012610 // Find the uninstantiated declaration that actually had the '= default'
12611 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000012612 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000012613
Richard Smith12fef492013-03-27 00:22:47 +000012614 // If the method was defaulted on its first declaration, we will have
12615 // already performed the checking in CheckCompletedCXXClass. Such a
12616 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000012617 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000012618 return;
12619
Richard Smithb9d0b762012-07-27 04:22:15 +000012620 CheckExplicitlyDefaultedSpecialMember(MD);
12621
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012622 if (MD->isInvalidDecl())
12623 return;
12624
Sean Hunte4246a62011-05-12 06:15:49 +000012625 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012626 case CXXDefaultConstructor:
12627 DefineImplicitDefaultConstructor(DefaultLoc,
12628 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000012629 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012630 case CXXCopyConstructor:
12631 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000012632 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012633 case CXXCopyAssignment:
12634 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000012635 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012636 case CXXDestructor:
12637 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000012638 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012639 case CXXMoveConstructor:
12640 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000012641 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012642 case CXXMoveAssignment:
12643 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012644 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012645 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000012646 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000012647 }
12648 } else {
12649 Diag(DefaultLoc, diag::err_default_special_members);
12650 }
12651}
12652
Sebastian Redl13e88542009-04-27 21:33:24 +000012653static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000012654 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000012655 Stmt *SubStmt = *CI;
12656 if (!SubStmt)
12657 continue;
12658 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000012659 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000012660 diag::err_return_in_constructor_handler);
12661 if (!isa<Expr>(SubStmt))
12662 SearchForReturnInStmt(Self, SubStmt);
12663 }
12664}
12665
12666void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12667 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12668 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12669 SearchForReturnInStmt(*this, Handler);
12670 }
12671}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012672
David Blaikie299adab2013-01-18 23:03:15 +000012673bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000012674 const CXXMethodDecl *Old) {
12675 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12676 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12677
12678 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12679
12680 // If the calling conventions match, everything is fine
12681 if (NewCC == OldCC)
12682 return false;
12683
Stephen Hines651f13c2014-04-23 16:59:28 -070012684 // If the calling conventions mismatch because the new function is static,
12685 // suppress the calling convention mismatch error; the error about static
12686 // function override (err_static_overrides_virtual from
12687 // Sema::CheckFunctionDeclaration) is more clear.
12688 if (New->getStorageClass() == SC_Static)
12689 return false;
12690
Reid Kleckneref072032013-08-27 23:08:25 +000012691 Diag(New->getLocation(),
12692 diag::err_conflicting_overriding_cc_attributes)
12693 << New->getDeclName() << New->getType() << Old->getType();
12694 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12695 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000012696}
12697
Mike Stump1eb44332009-09-09 15:08:12 +000012698bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012699 const CXXMethodDecl *Old) {
Stephen Hines651f13c2014-04-23 16:59:28 -070012700 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
12701 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012702
Chandler Carruth73857792010-02-15 11:53:20 +000012703 if (Context.hasSameType(NewTy, OldTy) ||
12704 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012705 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000012706
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012707 // Check if the return types are covariant
12708 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000012709
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012710 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012711 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12712 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012713 NewClassTy = NewPT->getPointeeType();
12714 OldClassTy = OldPT->getPointeeType();
12715 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012716 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12717 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12718 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12719 NewClassTy = NewRT->getPointeeType();
12720 OldClassTy = OldRT->getPointeeType();
12721 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012722 }
12723 }
Mike Stump1eb44332009-09-09 15:08:12 +000012724
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012725 // The return types aren't either both pointers or references to a class type.
12726 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000012727 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012728 diag::err_different_return_type_for_overriding_virtual_function)
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012729 << New->getDeclName() << NewTy << OldTy
12730 << New->getReturnTypeSourceRange();
12731 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12732 << Old->getReturnTypeSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +000012733
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012734 return true;
12735 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012736
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012737 // C++ [class.virtual]p6:
12738 // If the return type of D::f differs from the return type of B::f, the
12739 // class type in the return type of D::f shall be complete at the point of
12740 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000012741 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12742 if (!RT->isBeingDefined() &&
12743 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000012744 diag::err_covariant_return_incomplete,
12745 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012746 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000012747 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012748
Douglas Gregora4923eb2009-11-16 21:35:15 +000012749 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012750 // Check if the new class derives from the old class.
12751 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012752 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
12753 << New->getDeclName() << NewTy << OldTy
12754 << New->getReturnTypeSourceRange();
12755 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12756 << Old->getReturnTypeSourceRange();
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012757 return true;
12758 }
Mike Stump1eb44332009-09-09 15:08:12 +000012759
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012760 // Check if we the conversion from derived to base is valid.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012761 if (CheckDerivedToBaseConversion(
12762 NewClassTy, OldClassTy,
12763 diag::err_covariant_return_inaccessible_base,
12764 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12765 New->getLocation(), New->getReturnTypeSourceRange(),
12766 New->getDeclName(), nullptr)) {
John McCalleee1d542011-02-14 07:13:47 +000012767 // FIXME: this note won't trigger for delayed access control
12768 // diagnostics, and it's impossible to get an undelayed error
12769 // here from access control during the original parse because
12770 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012771 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12772 << Old->getReturnTypeSourceRange();
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012773 return true;
12774 }
12775 }
Mike Stump1eb44332009-09-09 15:08:12 +000012776
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012777 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012778 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012779 Diag(New->getLocation(),
12780 diag::err_covariant_return_type_different_qualifications)
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012781 << New->getDeclName() << NewTy << OldTy
12782 << New->getReturnTypeSourceRange();
12783 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12784 << Old->getReturnTypeSourceRange();
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012785 return true;
12786 };
Mike Stump1eb44332009-09-09 15:08:12 +000012787
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012788
12789 // The new class type must have the same or less qualifiers as the old type.
12790 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12791 Diag(New->getLocation(),
12792 diag::err_covariant_return_type_class_type_more_qualified)
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012793 << New->getDeclName() << NewTy << OldTy
12794 << New->getReturnTypeSourceRange();
12795 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
12796 << Old->getReturnTypeSourceRange();
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012797 return true;
12798 };
Mike Stump1eb44332009-09-09 15:08:12 +000012799
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012800 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012801}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012802
Douglas Gregor4ba31362009-12-01 17:24:26 +000012803/// \brief Mark the given method pure.
12804///
12805/// \param Method the method to be marked pure.
12806///
12807/// \param InitRange the source range that covers the "0" initializer.
12808bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000012809 SourceLocation EndLoc = InitRange.getEnd();
12810 if (EndLoc.isValid())
12811 Method->setRangeEnd(EndLoc);
12812
Douglas Gregor4ba31362009-12-01 17:24:26 +000012813 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12814 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000012815 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000012816 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000012817
12818 if (!Method->isInvalidDecl())
12819 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12820 << Method->getDeclName() << InitRange;
12821 return true;
12822}
12823
Douglas Gregor552e2992012-02-21 02:22:07 +000012824/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012825static bool isStaticDataMember(const Decl *D) {
12826 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12827 return Var->isStaticDataMember();
12828
12829 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000012830}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012831
John McCall731ad842009-12-19 09:28:58 +000012832/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12833/// an initializer for the out-of-line declaration 'Dcl'. The scope
12834/// is a fresh scope pushed for just this purpose.
12835///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012836/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12837/// static data member of class X, names should be looked up in the scope of
12838/// class X.
John McCalld226f652010-08-21 09:40:31 +000012839void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012840 // If there is no declaration, there was an error parsing it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012841 if (!D || D->isInvalidDecl())
12842 return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012843
Stephen Hines651f13c2014-04-23 16:59:28 -070012844 // We will always have a nested name specifier here, but this declaration
12845 // might not be out of line if the specifier names the current namespace:
12846 // extern int n;
12847 // int ::n = 0;
12848 if (D->isOutOfLine())
12849 EnterDeclaratorContext(S, D->getDeclContext());
12850
Douglas Gregor552e2992012-02-21 02:22:07 +000012851 // If we are parsing the initializer for a static data member, push a
12852 // new expression evaluation context that is associated with this static
12853 // data member.
12854 if (isStaticDataMember(D))
12855 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012856}
12857
12858/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000012859/// initializer for the out-of-line declaration 'D'.
12860void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012861 // If there is no declaration, there was an error parsing it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070012862 if (!D || D->isInvalidDecl())
12863 return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012864
Douglas Gregor552e2992012-02-21 02:22:07 +000012865 if (isStaticDataMember(D))
Stephen Hines651f13c2014-04-23 16:59:28 -070012866 PopExpressionEvaluationContext();
Douglas Gregor552e2992012-02-21 02:22:07 +000012867
Stephen Hines651f13c2014-04-23 16:59:28 -070012868 if (D->isOutOfLine())
12869 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012870}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012871
12872/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12873/// C++ if/switch/while/for statement.
12874/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000012875DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012876 // C++ 6.4p2:
12877 // The declarator shall not specify a function or an array.
12878 // The type-specifier-seq shall not contain typedef and shall not declare a
12879 // new class or enumeration.
12880 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12881 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012882
12883 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000012884 if (!Dcl)
12885 return true;
12886
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012887 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12888 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012889 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000012890 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012891 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012892
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012893 return Dcl;
12894}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012895
Douglas Gregordfe65432011-07-28 19:11:31 +000012896void Sema::LoadExternalVTableUses() {
12897 if (!ExternalSource)
12898 return;
12899
12900 SmallVector<ExternalVTableUse, 4> VTables;
12901 ExternalSource->ReadUsedVTables(VTables);
12902 SmallVector<VTableUse, 4> NewUses;
12903 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12904 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12905 = VTablesUsed.find(VTables[I].Record);
12906 // Even if a definition wasn't required before, it may be required now.
12907 if (Pos != VTablesUsed.end()) {
12908 if (!Pos->second && VTables[I].DefinitionRequired)
12909 Pos->second = true;
12910 continue;
12911 }
12912
12913 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12914 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12915 }
12916
12917 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12918}
12919
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012920void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12921 bool DefinitionRequired) {
12922 // Ignore any vtable uses in unevaluated operands or for classes that do
12923 // not have a vtable.
12924 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000012925 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000012926 return;
12927
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012928 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000012929 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012930 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12931 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12932 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12933 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000012934 // If we already had an entry, check to see if we are promoting this vtable
12935 // to required a definition. If so, we need to reappend to the VTableUses
12936 // list, since we may have already processed the first entry.
12937 if (DefinitionRequired && !Pos.first->second) {
12938 Pos.first->second = true;
12939 } else {
12940 // Otherwise, we can early exit.
12941 return;
12942 }
Stephen Hines651f13c2014-04-23 16:59:28 -070012943 } else {
12944 // The Microsoft ABI requires that we perform the destructor body
12945 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
12946 // the deleting destructor is emitted with the vtable, not with the
12947 // destructor definition as in the Itanium ABI.
12948 // If it has a definition, we do the check at that point instead.
12949 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12950 Class->hasUserDeclaredDestructor() &&
12951 !Class->getDestructor()->isDefined() &&
12952 !Class->getDestructor()->isDeleted()) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -070012953 CXXDestructorDecl *DD = Class->getDestructor();
12954 ContextRAII SavedContext(*this, DD);
12955 CheckDestructor(DD);
Stephen Hines651f13c2014-04-23 16:59:28 -070012956 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012957 }
12958
12959 // Local classes need to have their virtual members marked
12960 // immediately. For all other classes, we mark their virtual members
12961 // at the end of the translation unit.
12962 if (Class->isLocalClass())
12963 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000012964 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012965 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000012966}
12967
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012968bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000012969 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012970 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000012971 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000012972
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012973 // Note: The VTableUses vector could grow as a result of marking
12974 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000012975 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012976 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000012977 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012978 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000012979 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012980 if (!Class)
12981 continue;
12982
12983 SourceLocation Loc = VTableUses[I].second;
12984
Richard Smithb9d0b762012-07-27 04:22:15 +000012985 bool DefineVTable = true;
12986
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012987 // If this class has a key function, but that key function is
12988 // defined in another translation unit, we don't need to emit the
12989 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000012990 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000012991 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000012992 // The key function is in another translation unit.
12993 DefineVTable = false;
12994 TemplateSpecializationKind TSK =
12995 KeyFunction->getTemplateSpecializationKind();
12996 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12997 TSK != TSK_ImplicitInstantiation &&
12998 "Instantiations don't have key functions");
12999 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013000 } else if (!KeyFunction) {
13001 // If we have a class with no key function that is the subject
13002 // of an explicit instantiation declaration, suppress the
13003 // vtable; it will live with the explicit instantiation
13004 // definition.
13005 bool IsExplicitInstantiationDeclaration
13006 = Class->getTemplateSpecializationKind()
13007 == TSK_ExplicitInstantiationDeclaration;
Stephen Hines651f13c2014-04-23 16:59:28 -070013008 for (auto R : Class->redecls()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013009 TemplateSpecializationKind TSK
Stephen Hines651f13c2014-04-23 16:59:28 -070013010 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013011 if (TSK == TSK_ExplicitInstantiationDeclaration)
13012 IsExplicitInstantiationDeclaration = true;
13013 else if (TSK == TSK_ExplicitInstantiationDefinition) {
13014 IsExplicitInstantiationDeclaration = false;
13015 break;
13016 }
13017 }
13018
13019 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000013020 DefineVTable = false;
13021 }
13022
13023 // The exception specifications for all virtual members may be needed even
13024 // if we are not providing an authoritative form of the vtable in this TU.
13025 // We may choose to emit it available_externally anyway.
13026 if (!DefineVTable) {
13027 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
13028 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013029 }
13030
13031 // Mark all of the virtual members of this class as referenced, so
13032 // that we can build a vtable. Then, tell the AST consumer that a
13033 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000013034 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013035 MarkVirtualMembersReferenced(Loc, Class);
13036 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
13037 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
13038
13039 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000013040 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013041 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013042 const FunctionDecl *KeyFunctionDef = nullptr;
Douglas Gregora120d012011-09-23 19:04:03 +000013043 if (!KeyFunction ||
13044 (KeyFunction->hasBody(KeyFunctionDef) &&
13045 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000013046 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
13047 TSK_ExplicitInstantiationDefinition
13048 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
13049 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013050 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000013051 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000013052 VTableUses.clear();
13053
Douglas Gregor78844032011-04-22 22:25:37 +000013054 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000013055}
Anders Carlssond6a637f2009-12-07 08:24:59 +000013056
Richard Smithb9d0b762012-07-27 04:22:15 +000013057void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
13058 const CXXRecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -070013059 for (const auto *I : RD->methods())
13060 if (I->isVirtual() && !I->isPure())
13061 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
Richard Smithb9d0b762012-07-27 04:22:15 +000013062}
13063
Rafael Espindola3e1ae932010-03-26 00:36:59 +000013064void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
13065 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000013066 // Mark all functions which will appear in RD's vtable as used.
13067 CXXFinalOverriderMap FinalOverriders;
13068 RD->getFinalOverriders(FinalOverriders);
13069 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
13070 E = FinalOverriders.end();
13071 I != E; ++I) {
13072 for (OverridingMethods::const_iterator OI = I->second.begin(),
13073 OE = I->second.end();
13074 OI != OE; ++OI) {
13075 assert(OI->second.size() > 0 && "no final overrider");
13076 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000013077
Richard Smithff817f72012-07-07 06:59:51 +000013078 // C++ [basic.def.odr]p2:
13079 // [...] A virtual member function is used if it is not pure. [...]
13080 if (!Overrider->isPure())
13081 MarkFunctionReferenced(Loc, Overrider);
13082 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000013083 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000013084
13085 // Only classes that have virtual bases need a VTT.
13086 if (RD->getNumVBases() == 0)
13087 return;
13088
Stephen Hines651f13c2014-04-23 16:59:28 -070013089 for (const auto &I : RD->bases()) {
Rafael Espindola3e1ae932010-03-26 00:36:59 +000013090 const CXXRecordDecl *Base =
Stephen Hines651f13c2014-04-23 16:59:28 -070013091 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000013092 if (Base->getNumVBases() == 0)
13093 continue;
13094 MarkVirtualMembersReferenced(Loc, Base);
13095 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000013096}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013097
13098/// SetIvarInitializers - This routine builds initialization ASTs for the
13099/// Objective-C implementation whose ivars need be initialized.
13100void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000013101 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013102 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000013103 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000013104 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013105 CollectIvarsToConstructOrDestruct(OID, ivars);
13106 if (ivars.empty())
13107 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000013108 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013109 for (unsigned i = 0; i < ivars.size(); i++) {
13110 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000013111 if (Field->isInvalidDecl())
13112 continue;
13113
Sean Huntcbb67482011-01-08 20:30:50 +000013114 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013115 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
13116 InitializationKind InitKind =
13117 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000013118
13119 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
13120 ExprResult MemberInit =
13121 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000013122 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013123 // Note, MemberInit could actually come back empty if no initialization
13124 // is required (e.g., because it would call a trivial default constructor)
13125 if (!MemberInit.get() || MemberInit.isInvalid())
13126 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000013127
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013128 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000013129 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
13130 SourceLocation(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013131 MemberInit.getAs<Expr>(),
Sean Huntcbb67482011-01-08 20:30:50 +000013132 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013133 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000013134
13135 // Be sure that the destructor is accessible and is marked as referenced.
Stephen Hines176edba2014-12-01 14:53:08 -080013136 if (const RecordType *RecordTy =
13137 Context.getBaseElementType(Field->getType())
13138 ->getAs<RecordType>()) {
13139 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000013140 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000013141 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000013142 CheckDestructorAccess(Field->getLocation(), Destructor,
13143 PDiag(diag::err_access_dtor_ivar)
13144 << Context.getBaseElementType(Field->getType()));
13145 }
13146 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000013147 }
13148 ObjCImplementation->setIvarInitializers(Context,
13149 AllToInit.data(), AllToInit.size());
13150 }
13151}
Sean Huntfe57eef2011-05-04 05:57:24 +000013152
Sean Huntebcbe1d2011-05-04 23:29:54 +000013153static
13154void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
13155 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
13156 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
13157 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
13158 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000013159 if (Ctor->isInvalidDecl())
13160 return;
13161
Richard Smitha8eaf002012-08-23 06:16:52 +000013162 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
13163
13164 // Target may not be determinable yet, for instance if this is a dependent
13165 // call in an uninstantiated template.
13166 if (Target) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013167 const FunctionDecl *FNTarget = nullptr;
Richard Smitha8eaf002012-08-23 06:16:52 +000013168 (void)Target->hasBody(FNTarget);
13169 Target = const_cast<CXXConstructorDecl*>(
13170 cast_or_null<CXXConstructorDecl>(FNTarget));
13171 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000013172
13173 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
13174 // Avoid dereferencing a null pointer here.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013175 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
Sean Huntebcbe1d2011-05-04 23:29:54 +000013176
Stephen Hines176edba2014-12-01 14:53:08 -080013177 if (!Current.insert(Canonical).second)
Sean Huntebcbe1d2011-05-04 23:29:54 +000013178 return;
13179
13180 // We know that beyond here, we aren't chaining into a cycle.
13181 if (!Target || !Target->isDelegatingConstructor() ||
13182 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000013183 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000013184 Current.clear();
13185 // We've hit a cycle.
13186 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
13187 Current.count(TCanonical)) {
13188 // If we haven't diagnosed this cycle yet, do so now.
13189 if (!Invalid.count(TCanonical)) {
13190 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000013191 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000013192 << Ctor;
13193
Richard Smitha8eaf002012-08-23 06:16:52 +000013194 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000013195 if (TCanonical != Canonical)
13196 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
13197
13198 CXXConstructorDecl *C = Target;
13199 while (C->getCanonicalDecl() != Canonical) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013200 const FunctionDecl *FNTarget = nullptr;
Sean Huntebcbe1d2011-05-04 23:29:54 +000013201 (void)C->getTargetConstructor()->hasBody(FNTarget);
13202 assert(FNTarget && "Ctor cycle through bodiless function");
13203
Richard Smitha8eaf002012-08-23 06:16:52 +000013204 C = const_cast<CXXConstructorDecl*>(
13205 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000013206 S.Diag(C->getLocation(), diag::note_which_delegates_to);
13207 }
13208 }
13209
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000013210 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000013211 Current.clear();
13212 } else {
13213 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
13214 }
13215}
13216
13217
Sean Huntfe57eef2011-05-04 05:57:24 +000013218void Sema::CheckDelegatingCtorCycles() {
13219 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
13220
Douglas Gregor0129b562011-07-27 21:57:17 +000013221 for (DelegatingCtorDeclsType::iterator
13222 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000013223 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000013224 I != E; ++I)
13225 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000013226
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000013227 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
13228 CE = Invalid.end();
13229 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000013230 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000013231}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000013232
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013233namespace {
13234 /// \brief AST visitor that finds references to the 'this' expression.
13235 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
13236 Sema &S;
13237
13238 public:
13239 explicit FindCXXThisExpr(Sema &S) : S(S) { }
13240
13241 bool VisitCXXThisExpr(CXXThisExpr *E) {
13242 S.Diag(E->getLocation(), diag::err_this_static_member_func)
13243 << E->isImplicit();
13244 return false;
13245 }
13246 };
13247}
13248
13249bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
13250 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13251 if (!TSInfo)
13252 return false;
13253
13254 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000013255 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013256 if (!ProtoTL)
13257 return false;
13258
13259 // C++11 [expr.prim.general]p3:
13260 // [The expression this] shall not appear before the optional
13261 // cv-qualifier-seq and it shall not appear within the declaration of a
13262 // static member function (although its type and value category are defined
13263 // within a static member function as they are within a non-static member
13264 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000013265 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000013266 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013267 FindCXXThisExpr Finder(*this);
13268
13269 // If the return type came after the cv-qualifier-seq, check it now.
13270 if (Proto->hasTrailingReturn() &&
Stephen Hines651f13c2014-04-23 16:59:28 -070013271 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013272 return true;
13273
13274 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013275 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
13276 return true;
13277
13278 return checkThisInStaticMemberFunctionAttributes(Method);
13279}
13280
13281bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
13282 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
13283 if (!TSInfo)
13284 return false;
13285
13286 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000013287 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013288 if (!ProtoTL)
13289 return false;
13290
David Blaikie39e6ab42013-02-18 22:06:02 +000013291 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013292 FindCXXThisExpr Finder(*this);
13293
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013294 switch (Proto->getExceptionSpecType()) {
Stephen Hines176edba2014-12-01 14:53:08 -080013295 case EST_Unparsed:
Richard Smithe6975e92012-04-17 00:58:00 +000013296 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000013297 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013298 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013299 case EST_DynamicNone:
13300 case EST_MSAny:
13301 case EST_None:
13302 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013303
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013304 case EST_ComputedNoexcept:
13305 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
13306 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013307
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013308 case EST_Dynamic:
Stephen Hines651f13c2014-04-23 16:59:28 -070013309 for (const auto &E : Proto->exceptions()) {
13310 if (!Finder.TraverseType(E))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013311 return true;
13312 }
13313 break;
13314 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013315
13316 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013317}
13318
13319bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
13320 FindCXXThisExpr Finder(*this);
13321
13322 // Check attributes.
Stephen Hines651f13c2014-04-23 16:59:28 -070013323 for (const auto *A : Method->attrs()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013324 // FIXME: This should be emitted by tblgen.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013325 Expr *Arg = nullptr;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013326 ArrayRef<Expr *> Args;
Stephen Hines651f13c2014-04-23 16:59:28 -070013327 if (const auto *G = dyn_cast<GuardedByAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013328 Arg = G->getArg();
Stephen Hines651f13c2014-04-23 16:59:28 -070013329 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013330 Arg = G->getArg();
Stephen Hines651f13c2014-04-23 16:59:28 -070013331 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013332 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013333 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013334 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013335 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013336 Arg = ETLF->getSuccessValue();
Stephen Hines176edba2014-12-01 14:53:08 -080013337 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013338 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013339 Arg = STLF->getSuccessValue();
Stephen Hines176edba2014-12-01 14:53:08 -080013340 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013341 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013342 Arg = LR->getArg();
Stephen Hines651f13c2014-04-23 16:59:28 -070013343 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013344 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013345 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013346 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013347 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013348 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013349 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013350 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
Stephen Hines651f13c2014-04-23 16:59:28 -070013351 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
Stephen Hines176edba2014-12-01 14:53:08 -080013352 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
Douglas Gregorcefc3af2012-04-16 07:05:22 +000013353
13354 if (Arg && !Finder.TraverseStmt(Arg))
13355 return true;
13356
13357 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
13358 if (!Finder.TraverseStmt(Args[I]))
13359 return true;
13360 }
13361 }
13362
13363 return false;
13364}
13365
Stephen Hines176edba2014-12-01 14:53:08 -080013366void Sema::checkExceptionSpecification(
13367 bool IsTopLevel, ExceptionSpecificationType EST,
13368 ArrayRef<ParsedType> DynamicExceptions,
13369 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
13370 SmallVectorImpl<QualType> &Exceptions,
13371 FunctionProtoType::ExceptionSpecInfo &ESI) {
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013372 Exceptions.clear();
Stephen Hines176edba2014-12-01 14:53:08 -080013373 ESI.Type = EST;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013374 if (EST == EST_Dynamic) {
13375 Exceptions.reserve(DynamicExceptions.size());
13376 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
13377 // FIXME: Preserve type source info.
13378 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
13379
Stephen Hines176edba2014-12-01 14:53:08 -080013380 if (IsTopLevel) {
13381 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13382 collectUnexpandedParameterPacks(ET, Unexpanded);
13383 if (!Unexpanded.empty()) {
13384 DiagnoseUnexpandedParameterPacks(
13385 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
13386 Unexpanded);
13387 continue;
13388 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013389 }
13390
13391 // Check that the type is valid for an exception spec, and
13392 // drop it if not.
13393 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
13394 Exceptions.push_back(ET);
13395 }
Stephen Hines176edba2014-12-01 14:53:08 -080013396 ESI.Exceptions = Exceptions;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013397 return;
13398 }
Stephen Hines176edba2014-12-01 14:53:08 -080013399
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013400 if (EST == EST_ComputedNoexcept) {
13401 // If an error occurred, there's no expression here.
13402 if (NoexceptExpr) {
13403 assert((NoexceptExpr->isTypeDependent() ||
13404 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
13405 Context.BoolTy) &&
13406 "Parser should have made sure that the expression is boolean");
Stephen Hines176edba2014-12-01 14:53:08 -080013407 if (IsTopLevel && NoexceptExpr &&
13408 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
13409 ESI.Type = EST_BasicNoexcept;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013410 return;
13411 }
Stephen Hines176edba2014-12-01 14:53:08 -080013412
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013413 if (!NoexceptExpr->isValueDependent())
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013414 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
Douglas Gregorab41fe92012-05-04 22:38:52 +000013415 diag::err_noexcept_needs_constant_expression,
Stephen Hinesc568f1e2014-07-21 00:47:37 -070013416 /*AllowFold*/ false).get();
Stephen Hines176edba2014-12-01 14:53:08 -080013417 ESI.NoexceptExpr = NoexceptExpr;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000013418 }
13419 return;
13420 }
13421}
13422
Stephen Hines176edba2014-12-01 14:53:08 -080013423void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
13424 ExceptionSpecificationType EST,
13425 SourceRange SpecificationRange,
13426 ArrayRef<ParsedType> DynamicExceptions,
13427 ArrayRef<SourceRange> DynamicExceptionRanges,
13428 Expr *NoexceptExpr) {
13429 if (!MethodD)
13430 return;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000013431
Stephen Hines176edba2014-12-01 14:53:08 -080013432 // Dig out the method we're referring to.
13433 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
13434 MethodD = FunTmpl->getTemplatedDecl();
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000013435
Stephen Hines176edba2014-12-01 14:53:08 -080013436 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
13437 if (!Method)
13438 return;
13439
13440 // Check the exception specification.
13441 llvm::SmallVector<QualType, 4> Exceptions;
13442 FunctionProtoType::ExceptionSpecInfo ESI;
13443 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
13444 DynamicExceptionRanges, NoexceptExpr, Exceptions,
13445 ESI);
13446
13447 // Update the exception specification on the function type.
13448 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
13449
13450 if (Method->isStatic())
13451 checkThisInStaticMemberFunctionExceptionSpec(Method);
13452
13453 if (Method->isVirtual()) {
13454 // Check overrides, which we previously had to delay.
13455 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
13456 OEnd = Method->end_overridden_methods();
13457 O != OEnd; ++O)
13458 CheckOverridingFunctionExceptionSpec(Method, *O);
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000013459 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000013460}
John McCall76da55d2013-04-16 07:28:30 +000013461
13462/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
13463///
13464MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
13465 SourceLocation DeclStart,
13466 Declarator &D, Expr *BitWidth,
13467 InClassInitStyle InitStyle,
13468 AccessSpecifier AS,
13469 AttributeList *MSPropertyAttr) {
13470 IdentifierInfo *II = D.getIdentifier();
13471 if (!II) {
13472 Diag(DeclStart, diag::err_anonymous_property);
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013473 return nullptr;
John McCall76da55d2013-04-16 07:28:30 +000013474 }
13475 SourceLocation Loc = D.getIdentifierLoc();
13476
13477 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13478 QualType T = TInfo->getType();
13479 if (getLangOpts().CPlusPlus) {
13480 CheckExtraCXXDefaultArguments(D);
13481
13482 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13483 UPPC_DataMemberType)) {
13484 D.setInvalidType();
13485 T = Context.IntTy;
13486 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13487 }
13488 }
13489
13490 DiagnoseFunctionSpecifiers(D.getDeclSpec());
13491
13492 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13493 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13494 diag::err_invalid_thread)
13495 << DeclSpec::getSpecifierName(TSCS);
13496
13497 // Check to see if this name was declared as a member previously
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013498 NamedDecl *PrevDecl = nullptr;
John McCall76da55d2013-04-16 07:28:30 +000013499 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13500 LookupName(Previous, S);
13501 switch (Previous.getResultKind()) {
13502 case LookupResult::Found:
13503 case LookupResult::FoundUnresolvedValue:
13504 PrevDecl = Previous.getAsSingle<NamedDecl>();
13505 break;
13506
13507 case LookupResult::FoundOverloaded:
13508 PrevDecl = Previous.getRepresentativeDecl();
13509 break;
13510
13511 case LookupResult::NotFound:
13512 case LookupResult::NotFoundInCurrentInstantiation:
13513 case LookupResult::Ambiguous:
13514 break;
13515 }
13516
13517 if (PrevDecl && PrevDecl->isTemplateParameter()) {
13518 // Maybe we will complain about the shadowed template parameter.
13519 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13520 // Just pretend that we didn't see the previous declaration.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013521 PrevDecl = nullptr;
John McCall76da55d2013-04-16 07:28:30 +000013522 }
13523
13524 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
Stephen Hines6bcf27b2014-05-29 04:14:42 -070013525 PrevDecl = nullptr;
John McCall76da55d2013-04-16 07:28:30 +000013526
13527 SourceLocation TSSL = D.getLocStart();
John McCall76da55d2013-04-16 07:28:30 +000013528 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
Stephen Hines651f13c2014-04-23 16:59:28 -070013529 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
13530 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
John McCall76da55d2013-04-16 07:28:30 +000013531 ProcessDeclAttributes(TUScope, NewPD, D);
13532 NewPD->setAccess(AS);
13533
13534 if (NewPD->isInvalidDecl())
13535 Record->setInvalidDecl();
13536
13537 if (D.getDeclSpec().isModulePrivateSpecified())
13538 NewPD->setModulePrivate();
13539
13540 if (NewPD->isInvalidDecl() && PrevDecl) {
13541 // Don't introduce NewFD into scope; there's already something
13542 // with the same name in the same scope.
13543 } else if (II) {
13544 PushOnScopeChains(NewPD, S);
13545 } else
13546 Record->addDecl(NewPD);
13547
13548 return NewPD;
13549}