blob: 45b03badb2a87c5184a051ea69afc7f39cac615a [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"
Anders Carlsson8211eff2009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000022#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000023#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000029#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000030#include "clang/Basic/TargetInfo.h"
Richard Smith4ac537b2013-07-23 08:14:48 +000031#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000033#include "clang/Sema/CXXFieldCollector.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/ScopeInfo.h"
Douglas 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.
215 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
216 EEnd = Proto->exception_end();
217 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000219 Exceptions.push_back(*E);
220}
221
Richard Smith7a614d82011-06-11 17:19:42 +0000222void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000223 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000224 return;
225
226 // FIXME:
227 //
228 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000229 // [An] implicit exception-specification specifies the type-id T if and
230 // only if T is allowed by the exception-specification of a function directly
231 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000232 // function it directly invokes allows all exceptions, and f shall allow no
233 // exceptions if every function it directly invokes allows no exceptions.
234 //
235 // Note in particular that if an implicit exception-specification is generated
236 // for a function containing a throw-expression, that specification can still
237 // be noexcept(true).
238 //
239 // Note also that 'directly invoked' is not defined in the standard, and there
240 // is no indication that we should only consider potentially-evaluated calls.
241 //
242 // Ultimately we should implement the intent of the standard: the exception
243 // specification should be the set of exceptions which can be thrown by the
244 // implicit definition. For now, we assume that any non-nothrow expression can
245 // throw any exception.
246
Richard Smithe6975e92012-04-17 00:58:00 +0000247 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000248 ComputedEST = EST_None;
249}
250
Anders Carlssoned961f92009-08-25 02:29:20 +0000251bool
John McCall9ae2f072010-08-23 23:25:46 +0000252Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000253 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000254 if (RequireCompleteType(Param->getLocation(), Param->getType(),
255 diag::err_typecheck_decl_incomplete_type)) {
256 Param->setInvalidDecl();
257 return true;
258 }
259
Anders Carlssoned961f92009-08-25 02:29:20 +0000260 // C++ [dcl.fct.default]p5
261 // A default argument expression is implicitly converted (clause
262 // 4) to the parameter type. The default argument expression has
263 // the same semantic constraints as the initializer expression in
264 // a declaration of a variable of the parameter type, using the
265 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000270 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000272 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000273 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000274 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000275
Richard Smith6c3af3d2013-01-17 01:17:56 +0000276 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000277 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Anders Carlssoned961f92009-08-25 02:29:20 +0000279 // Okay: add the default argument to the parameter
280 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000282 // We have already instantiated this parameter; provide each of the
283 // instantiations with the uninstantiated default argument.
284 UnparsedDefaultArgInstantiationsMap::iterator InstPos
285 = UnparsedDefaultArgInstantiations.find(Param);
286 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
289
290 // We're done tracking this parameter's instantiations.
291 UnparsedDefaultArgInstantiations.erase(InstPos);
292 }
293
Anders Carlsson9351c172009-08-25 03:18:48 +0000294 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000295}
296
Chris Lattner8123a952008-04-10 02:22:51 +0000297/// ActOnParamDefaultArgument - Check whether the default argument
298/// provided for a function parameter is well-formed. If so, attach it
299/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000300void
John McCalld226f652010-08-21 09:40:31 +0000301Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000302 Expr *DefaultArg) {
303 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000304 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000305
John McCalld226f652010-08-21 09:40:31 +0000306 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000307 UnparsedDefaultArgLocs.erase(Param);
308
Chris Lattner3d1cee32008-04-08 05:04:30 +0000309 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000310 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000311 Diag(EqualLoc, diag::err_param_default_argument)
312 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000313 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000314 return;
315 }
316
Douglas Gregor6f526752010-12-16 08:48:57 +0000317 // Check for unexpanded parameter packs.
318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319 Param->setInvalidDecl();
320 return;
321 }
322
Anders Carlsson66e30672009-08-25 01:02:06 +0000323 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000324 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
325 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000326 Param->setInvalidDecl();
327 return;
328 }
Mike Stump1eb44332009-09-09 15:08:12 +0000329
John McCall9ae2f072010-08-23 23:25:46 +0000330 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000331}
332
Douglas Gregor61366e92008-12-24 00:01:03 +0000333/// ActOnParamUnparsedDefaultArgument - We've seen a default
334/// argument for a function parameter, but we can't parse it yet
335/// because we're inside a class definition. Note that this default
336/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000337void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000338 SourceLocation EqualLoc,
339 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000340 if (!param)
341 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000342
John McCalld226f652010-08-21 09:40:31 +0000343 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +0000344 Param->setUnparsedDefaultArg();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000345 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000346}
347
Douglas Gregor72b505b2008-12-16 21:30:33 +0000348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000351 if (!param)
352 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCalld226f652010-08-21 09:40:31 +0000354 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000355 Param->setInvalidDecl();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000356 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000357}
358
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000359/// CheckExtraCXXDefaultArguments - Check for any extra default
360/// arguments in the declarator, which is not a function declaration
361/// or definition and therefore is not permitted to have default
362/// arguments. This routine should be invoked for every declarator
363/// that is not a function declaration or definition.
364void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365 // C++ [dcl.fct.default]p3
366 // A default argument expression shall be specified only in the
367 // parameter-declaration-clause of a function declaration or in a
368 // template-parameter (14.1). It shall not be specified for a
369 // parameter pack. If it is specified in a
370 // parameter-declaration-clause, it shall not occur within a
371 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000372 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000373 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000374 DeclaratorChunk &chunk = D.getTypeObject(i);
375 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000376 if (MightBeFunction) {
377 // This is a function declaration. It can have default arguments, but
378 // keep looking in case its return type is a function type with default
379 // arguments.
380 MightBeFunction = false;
381 continue;
382 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000383 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
384 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000385 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000386 if (Param->hasUnparsedDefaultArg()) {
387 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000388 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000389 << SourceRange((*Toks)[1].getLocation(),
390 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 delete Toks;
392 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000393 } else if (Param->getDefaultArg()) {
394 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395 << Param->getDefaultArg()->getSourceRange();
396 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000397 }
398 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000399 } else if (chunk.Kind != DeclaratorChunk::Paren) {
400 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000401 }
402 }
403}
404
David Majnemerf6a144f2013-06-25 23:09:30 +0000405static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408 if (!PVD->hasDefaultArg())
409 return false;
410 if (!PVD->hasInheritedDefaultArg())
411 return true;
412 }
413 return false;
414}
415
Craig Topper1a6eac82012-09-21 04:33:26 +0000416/// MergeCXXFunctionDecl - Merge two declarations of the same C++
417/// function, once we already know that they have the same
418/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000422 bool Invalid = false;
423
Chris Lattner3d1cee32008-04-08 05:04:30 +0000424 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000425 // For non-template functions, default arguments can be added in
426 // later declarations of a function in the same
427 // scope. Declarations in different scopes have completely
428 // distinct sets of default arguments. That is, declarations in
429 // inner scopes do not acquire default arguments from
430 // declarations in outer scopes, and vice versa. In a given
431 // function declaration, all parameters subsequent to a
432 // parameter with a default argument shall have default
433 // arguments supplied in this or previous declarations. A
434 // default argument shall not be redefined by a later
435 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000436 //
437 // C++ [dcl.fct.default]p6:
Richard Smitha41c97a2013-09-20 01:15:31 +0000438 // Except for member functions of class templates, the default arguments
439 // in a member function definition that appears outside of the class
440 // definition are added to the set of default arguments provided by the
Douglas Gregor6cc15182009-09-11 18:44:32 +0000441 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000442 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443 ParmVarDecl *OldParam = Old->getParamDecl(p);
444 ParmVarDecl *NewParam = New->getParamDecl(p);
445
James Molloy9cda03f2012-03-13 08:55:35 +0000446 bool OldParamHasDfl = OldParam->hasDefaultArg();
447 bool NewParamHasDfl = NewParam->hasDefaultArg();
448
449 NamedDecl *ND = Old;
Richard Smitha41c97a2013-09-20 01:15:31 +0000450
451 // The declaration context corresponding to the scope is the semantic
452 // parent, unless this is a local function declaration, in which case
453 // it is that surrounding function.
454 DeclContext *ScopeDC = New->getLexicalDeclContext();
455 if (!ScopeDC->isFunctionOrMethod())
456 ScopeDC = New->getDeclContext();
457 if (S && !isDeclInScope(ND, ScopeDC, S) &&
458 !New->getDeclContext()->isRecord())
James Molloy9cda03f2012-03-13 08:55:35 +0000459 // Ignore default parameters of old decl if they are not in
Richard Smitha41c97a2013-09-20 01:15:31 +0000460 // the same scope and this is not an out-of-line definition of
461 // a member function.
James Molloy9cda03f2012-03-13 08:55:35 +0000462 OldParamHasDfl = false;
463
464 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000465
Francois Pichet8d051e02011-04-10 03:03:52 +0000466 unsigned DiagDefaultParamID =
467 diag::err_param_default_argument_redefinition;
468
469 // MSVC accepts that default parameters be redefined for member functions
470 // of template class. The new default parameter's value is ignored.
471 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000472 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000473 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000475 // Merge the old default argument into the new parameter.
476 NewParam->setHasInheritedDefaultArg();
477 if (OldParam->hasUninstantiatedDefaultArg())
478 NewParam->setUninstantiatedDefaultArg(
479 OldParam->getUninstantiatedDefaultArg());
480 else
481 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000482 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000483 Invalid = false;
484 }
485 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000486
Francois Pichet8cf90492011-04-10 04:58:30 +0000487 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488 // hint here. Alternatively, we could walk the type-source information
489 // for NewParam to find the last source location in the type... but it
490 // isn't worth the effort right now. This is the kind of test case that
491 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000492 // int f(int);
493 // void g(int (*fp)(int) = f);
494 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000495 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000496 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000497
498 // Look for the function declaration where the default argument was
499 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000500 for (FunctionDecl *Older = Old->getPreviousDecl();
501 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000502 if (!Older->getParamDecl(p)->hasDefaultArg())
503 break;
504
505 OldParam = Older->getParamDecl(p);
506 }
507
508 Diag(OldParam->getLocation(), diag::note_previous_definition)
509 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000510 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000511 // Merge the old default argument into the new parameter.
512 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000513 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000514 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000515 if (OldParam->hasUninstantiatedDefaultArg())
516 NewParam->setUninstantiatedDefaultArg(
517 OldParam->getUninstantiatedDefaultArg());
518 else
John McCall3d6c1782010-05-04 01:53:42 +0000519 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000520 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000521 if (New->getDescribedFunctionTemplate()) {
522 // Paragraph 4, quoted above, only applies to non-template functions.
523 Diag(NewParam->getLocation(),
524 diag::err_param_default_argument_template_redecl)
525 << NewParam->getDefaultArgRange();
526 Diag(Old->getLocation(), diag::note_template_prev_declaration)
527 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000528 } else if (New->getTemplateSpecializationKind()
529 != TSK_ImplicitInstantiation &&
530 New->getTemplateSpecializationKind() != TSK_Undeclared) {
531 // C++ [temp.expr.spec]p21:
532 // Default function arguments shall not be specified in a declaration
533 // or a definition for one of the following explicit specializations:
534 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000535 // - the explicit specialization of a member function template;
536 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000537 // template where the class template specialization to which the
538 // member function specialization belongs is implicitly
539 // instantiated.
540 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542 << New->getDeclName()
543 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000544 } else if (New->getDeclContext()->isDependentContext()) {
545 // C++ [dcl.fct.default]p6 (DR217):
546 // Default arguments for a member function of a class template shall
547 // be specified on the initial declaration of the member function
548 // within the class template.
549 //
550 // Reading the tea leaves a bit in DR217 and its reference to DR205
551 // leads me to the conclusion that one cannot add default function
552 // arguments for an out-of-line definition of a member function of a
553 // dependent type.
554 int WhichKind = 2;
555 if (CXXRecordDecl *Record
556 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557 if (Record->getDescribedClassTemplate())
558 WhichKind = 0;
559 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560 WhichKind = 1;
561 else
562 WhichKind = 2;
563 }
564
565 Diag(NewParam->getLocation(),
566 diag::err_param_default_argument_member_template_redecl)
567 << WhichKind
568 << NewParam->getDefaultArgRange();
569 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000570 }
571 }
572
Richard Smithb8abff62012-11-28 03:45:24 +0000573 // DR1344: If a default argument is added outside a class definition and that
574 // default argument makes the function a special member function, the program
575 // is ill-formed. This can only happen for constructors.
576 if (isa<CXXConstructorDecl>(New) &&
577 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580 if (NewSM != OldSM) {
581 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582 assert(NewParam->hasDefaultArg());
583 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584 << NewParam->getDefaultArgRange() << NewSM;
585 Diag(Old->getLocation(), diag::note_previous_declaration);
586 }
587 }
588
Richard Smithff234882012-02-20 23:28:05 +0000589 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000590 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000591 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000592 if (New->isConstexpr() != Old->isConstexpr()) {
593 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
594 << New << New->isConstexpr();
595 Diag(Old->getLocation(), diag::note_previous_declaration);
596 Invalid = true;
597 }
598
David Majnemerf6a144f2013-06-25 23:09:30 +0000599 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000600 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000601 // the only declaration of the function or function template in the
602 // translation unit.
603 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
604 functionDeclHasDefaultArgument(Old)) {
605 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
606 Diag(Old->getLocation(), diag::note_previous_declaration);
607 Invalid = true;
608 }
609
Douglas Gregore13ad832010-02-12 07:32:17 +0000610 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000611 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000612
Douglas Gregorcda9c672009-02-16 17:45:42 +0000613 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000614}
615
Sebastian Redl60618fa2011-03-12 11:50:43 +0000616/// \brief Merge the exception specifications of two variable declarations.
617///
618/// This is called when there's a redeclaration of a VarDecl. The function
619/// checks if the redeclaration might have an exception specification and
620/// validates compatibility and merges the specs if necessary.
621void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
622 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000623 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000624 return;
625
626 assert(Context.hasSameType(New->getType(), Old->getType()) &&
627 "Should only be called if types are otherwise the same.");
628
629 QualType NewType = New->getType();
630 QualType OldType = Old->getType();
631
632 // We're only interested in pointers and references to functions, as well
633 // as pointers to member functions.
634 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
635 NewType = R->getPointeeType();
636 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
637 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
638 NewType = P->getPointeeType();
639 OldType = OldType->getAs<PointerType>()->getPointeeType();
640 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
641 NewType = M->getPointeeType();
642 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
643 }
644
645 if (!NewType->isFunctionProtoType())
646 return;
647
648 // There's lots of special cases for functions. For function pointers, system
649 // libraries are hopefully not as broken so that we don't need these
650 // workarounds.
651 if (CheckEquivalentExceptionSpec(
652 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
653 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
654 New->setInvalidDecl();
655 }
656}
657
Chris Lattner3d1cee32008-04-08 05:04:30 +0000658/// CheckCXXDefaultArguments - Verify that the default arguments for a
659/// function declaration are well-formed according to C++
660/// [dcl.fct.default].
661void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
662 unsigned NumParams = FD->getNumParams();
663 unsigned p;
664
665 // Find first parameter with a default argument
666 for (p = 0; p < NumParams; ++p) {
667 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000668 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000669 break;
670 }
671
672 // C++ [dcl.fct.default]p4:
673 // In a given function declaration, all parameters
674 // subsequent to a parameter with a default argument shall
675 // have default arguments supplied in this or previous
676 // declarations. A default argument shall not be redefined
677 // by a later declaration (not even to the same value).
678 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000679 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000680 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000681 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000682 if (Param->isInvalidDecl())
683 /* We already complained about this parameter. */;
684 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000685 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000686 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000687 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000688 else
Mike Stump1eb44332009-09-09 15:08:12 +0000689 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000690 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Chris Lattner3d1cee32008-04-08 05:04:30 +0000692 LastMissingDefaultArg = p;
693 }
694 }
695
696 if (LastMissingDefaultArg > 0) {
697 // Some default arguments were missing. Clear out all of the
698 // default arguments up to (and including) the last missing
699 // default argument, so that we leave the function parameters
700 // in a semantically valid state.
701 for (p = 0; p <= LastMissingDefaultArg; ++p) {
702 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000703 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000704 Param->setDefaultArg(0);
705 }
706 }
707 }
708}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000709
Richard Smith9f569cc2011-10-01 02:31:28 +0000710// CheckConstexprParameterTypes - Check whether a function's parameter types
711// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000712// diagnostic and return false.
713static bool CheckConstexprParameterTypes(Sema &SemaRef,
714 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000715 unsigned ArgIndex = 0;
716 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
717 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
718 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
719 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
720 SourceLocation ParamLoc = PD->getLocation();
721 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000722 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000723 diag::err_constexpr_non_literal_param,
724 ArgIndex+1, PD->getSourceRange(),
725 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000726 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000727 }
Joao Matos17d35c32012-08-31 22:18:20 +0000728 return true;
729}
730
731/// \brief Get diagnostic %select index for tag kind for
732/// record diagnostic message.
733/// WARNING: Indexes apply to particular diagnostics only!
734///
735/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000736static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000737 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000738 case TTK_Struct: return 0;
739 case TTK_Interface: return 1;
740 case TTK_Class: return 2;
741 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000742 }
Joao Matos17d35c32012-08-31 22:18:20 +0000743}
744
745// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
746// the requirements of a constexpr function definition or a constexpr
747// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000748// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000749//
Richard Smith86c3ae42012-02-13 03:54:03 +0000750// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
751bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000752 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
753 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000754 // C++11 [dcl.constexpr]p4:
755 // The definition of a constexpr constructor shall satisfy the following
756 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000757 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000758 const CXXRecordDecl *RD = MD->getParent();
759 if (RD->getNumVBases()) {
760 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
761 << isa<CXXConstructorDecl>(NewFD)
762 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
763 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
764 E = RD->vbases_end(); I != E; ++I)
765 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000766 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 return false;
768 }
Richard Smith35340502012-01-13 04:54:00 +0000769 }
770
771 if (!isa<CXXConstructorDecl>(NewFD)) {
772 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000773 // The definition of a constexpr function shall satisfy the following
774 // constraints:
775 // - it shall not be virtual;
776 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
777 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000778 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000779
Richard Smith86c3ae42012-02-13 03:54:03 +0000780 // If it's not obvious why this function is virtual, find an overridden
781 // function which uses the 'virtual' keyword.
782 const CXXMethodDecl *WrittenVirtual = Method;
783 while (!WrittenVirtual->isVirtualAsWritten())
784 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
785 if (WrittenVirtual != Method)
786 Diag(WrittenVirtual->getLocation(),
787 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000788 return false;
789 }
790
791 // - its return type shall be a literal type;
792 QualType RT = NewFD->getResultType();
793 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000794 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000795 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000796 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000797 }
798
Richard Smith35340502012-01-13 04:54:00 +0000799 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000800 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000801 return false;
802
Richard Smith9f569cc2011-10-01 02:31:28 +0000803 return true;
804}
805
806/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000807/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000808///
Richard Smitha10b9782013-04-22 15:31:51 +0000809/// \return true if the body is OK (maybe only as an extension), false if we
810/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000811static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000812 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
813 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000814 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
815 // contain only
816 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
817 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
818 switch ((*DclIt)->getKind()) {
819 case Decl::StaticAssert:
820 case Decl::Using:
821 case Decl::UsingShadow:
822 case Decl::UsingDirective:
823 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000824 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000825 // - static_assert-declarations
826 // - using-declarations,
827 // - using-directives,
828 continue;
829
830 case Decl::Typedef:
831 case Decl::TypeAlias: {
832 // - typedef declarations and alias-declarations that do not define
833 // classes or enumerations,
834 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
835 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
836 // Don't allow variably-modified types in constexpr functions.
837 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
838 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
839 << TL.getSourceRange() << TL.getType()
840 << isa<CXXConstructorDecl>(Dcl);
841 return false;
842 }
843 continue;
844 }
845
846 case Decl::Enum:
847 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000848 // C++1y allows types to be defined, not just declared.
849 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
850 SemaRef.Diag(DS->getLocStart(),
851 SemaRef.getLangOpts().CPlusPlus1y
852 ? diag::warn_cxx11_compat_constexpr_type_definition
853 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000854 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000855 continue;
856
Richard Smitha10b9782013-04-22 15:31:51 +0000857 case Decl::EnumConstant:
858 case Decl::IndirectField:
859 case Decl::ParmVar:
860 // These can only appear with other declarations which are banned in
861 // C++11 and permitted in C++1y, so ignore them.
862 continue;
863
864 case Decl::Var: {
865 // C++1y [dcl.constexpr]p3 allows anything except:
866 // a definition of a variable of non-literal type or of static or
867 // thread storage duration or for which no initialization is performed.
868 VarDecl *VD = cast<VarDecl>(*DclIt);
869 if (VD->isThisDeclarationADefinition()) {
870 if (VD->isStaticLocal()) {
871 SemaRef.Diag(VD->getLocation(),
872 diag::err_constexpr_local_var_static)
873 << isa<CXXConstructorDecl>(Dcl)
874 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
875 return false;
876 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000877 if (!VD->getType()->isDependentType() &&
878 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000879 VD->getLocation(), VD->getType(),
880 diag::err_constexpr_local_var_non_literal_type,
881 isa<CXXConstructorDecl>(Dcl)))
882 return false;
883 if (!VD->hasInit()) {
884 SemaRef.Diag(VD->getLocation(),
885 diag::err_constexpr_local_var_no_init)
886 << isa<CXXConstructorDecl>(Dcl);
887 return false;
888 }
889 }
890 SemaRef.Diag(VD->getLocation(),
891 SemaRef.getLangOpts().CPlusPlus1y
892 ? diag::warn_cxx11_compat_constexpr_local_var
893 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000894 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000895 continue;
896 }
897
898 case Decl::NamespaceAlias:
899 case Decl::Function:
900 // These are disallowed in C++11 and permitted in C++1y. Allow them
901 // everywhere as an extension.
902 if (!Cxx1yLoc.isValid())
903 Cxx1yLoc = DS->getLocStart();
904 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000905
906 default:
907 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
908 << isa<CXXConstructorDecl>(Dcl);
909 return false;
910 }
911 }
912
913 return true;
914}
915
916/// Check that the given field is initialized within a constexpr constructor.
917///
918/// \param Dcl The constexpr constructor being checked.
919/// \param Field The field being checked. This may be a member of an anonymous
920/// struct or union nested within the class being checked.
921/// \param Inits All declarations, including anonymous struct/union members and
922/// indirect members, for which any initialization was provided.
923/// \param Diagnosed Set to true if an error is produced.
924static void CheckConstexprCtorInitializer(Sema &SemaRef,
925 const FunctionDecl *Dcl,
926 FieldDecl *Field,
927 llvm::SmallSet<Decl*, 16> &Inits,
928 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000929 if (Field->isInvalidDecl())
930 return;
931
Douglas Gregord61db332011-10-10 17:22:13 +0000932 if (Field->isUnnamedBitfield())
933 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000934
935 if (Field->isAnonymousStructOrUnion() &&
936 Field->getType()->getAsCXXRecordDecl()->isEmpty())
937 return;
938
Richard Smith9f569cc2011-10-01 02:31:28 +0000939 if (!Inits.count(Field)) {
940 if (!Diagnosed) {
941 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
942 Diagnosed = true;
943 }
944 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
945 } else if (Field->isAnonymousStructOrUnion()) {
946 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
947 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
948 I != E; ++I)
949 // If an anonymous union contains an anonymous struct of which any member
950 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000951 if (!RD->isUnion() || Inits.count(*I))
952 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000953 }
954}
955
Richard Smitha10b9782013-04-22 15:31:51 +0000956/// Check the provided statement is allowed in a constexpr function
957/// definition.
958static bool
959CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000960 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000961 SourceLocation &Cxx1yLoc) {
962 // - its function-body shall be [...] a compound-statement that contains only
963 switch (S->getStmtClass()) {
964 case Stmt::NullStmtClass:
965 // - null statements,
966 return true;
967
968 case Stmt::DeclStmtClass:
969 // - static_assert-declarations
970 // - using-declarations,
971 // - using-directives,
972 // - typedef declarations and alias-declarations that do not define
973 // classes or enumerations,
974 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
975 return false;
976 return true;
977
978 case Stmt::ReturnStmtClass:
979 // - and exactly one return statement;
980 if (isa<CXXConstructorDecl>(Dcl)) {
981 // C++1y allows return statements in constexpr constructors.
982 if (!Cxx1yLoc.isValid())
983 Cxx1yLoc = S->getLocStart();
984 return true;
985 }
986
987 ReturnStmts.push_back(S->getLocStart());
988 return true;
989
990 case Stmt::CompoundStmtClass: {
991 // C++1y allows compound-statements.
992 if (!Cxx1yLoc.isValid())
993 Cxx1yLoc = S->getLocStart();
994
995 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
996 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
997 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
998 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
999 Cxx1yLoc))
1000 return false;
1001 }
1002 return true;
1003 }
1004
1005 case Stmt::AttributedStmtClass:
1006 if (!Cxx1yLoc.isValid())
1007 Cxx1yLoc = S->getLocStart();
1008 return true;
1009
1010 case Stmt::IfStmtClass: {
1011 // C++1y allows if-statements.
1012 if (!Cxx1yLoc.isValid())
1013 Cxx1yLoc = S->getLocStart();
1014
1015 IfStmt *If = cast<IfStmt>(S);
1016 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1017 Cxx1yLoc))
1018 return false;
1019 if (If->getElse() &&
1020 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1021 Cxx1yLoc))
1022 return false;
1023 return true;
1024 }
1025
1026 case Stmt::WhileStmtClass:
1027 case Stmt::DoStmtClass:
1028 case Stmt::ForStmtClass:
1029 case Stmt::CXXForRangeStmtClass:
1030 case Stmt::ContinueStmtClass:
1031 // C++1y allows all of these. We don't allow them as extensions in C++11,
1032 // because they don't make sense without variable mutation.
1033 if (!SemaRef.getLangOpts().CPlusPlus1y)
1034 break;
1035 if (!Cxx1yLoc.isValid())
1036 Cxx1yLoc = S->getLocStart();
1037 for (Stmt::child_range Children = S->children(); Children; ++Children)
1038 if (*Children &&
1039 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1040 Cxx1yLoc))
1041 return false;
1042 return true;
1043
1044 case Stmt::SwitchStmtClass:
1045 case Stmt::CaseStmtClass:
1046 case Stmt::DefaultStmtClass:
1047 case Stmt::BreakStmtClass:
1048 // C++1y allows switch-statements, and since they don't need variable
1049 // mutation, we can reasonably allow them in C++11 as an extension.
1050 if (!Cxx1yLoc.isValid())
1051 Cxx1yLoc = S->getLocStart();
1052 for (Stmt::child_range Children = S->children(); Children; ++Children)
1053 if (*Children &&
1054 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1055 Cxx1yLoc))
1056 return false;
1057 return true;
1058
1059 default:
1060 if (!isa<Expr>(S))
1061 break;
1062
1063 // C++1y allows expression-statements.
1064 if (!Cxx1yLoc.isValid())
1065 Cxx1yLoc = S->getLocStart();
1066 return true;
1067 }
1068
1069 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1070 << isa<CXXConstructorDecl>(Dcl);
1071 return false;
1072}
1073
Richard Smith9f569cc2011-10-01 02:31:28 +00001074/// Check the body for the given constexpr function declaration only contains
1075/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1076///
1077/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001078bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001079 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001080 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 // The definition of a constexpr function shall satisfy the following
1082 // constraints: [...]
1083 // - its function-body shall be = delete, = default, or a
1084 // compound-statement
1085 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001086 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001087 // In the definition of a constexpr constructor, [...]
1088 // - its function-body shall not be a function-try-block;
1089 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1090 << isa<CXXConstructorDecl>(Dcl);
1091 return false;
1092 }
1093
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001094 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001095
1096 // - its function-body shall be [...] a compound-statement that contains only
1097 // [... list of cases ...]
1098 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1099 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001100 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1101 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001102 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1103 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001104 }
1105
Richard Smitha10b9782013-04-22 15:31:51 +00001106 if (Cxx1yLoc.isValid())
1107 Diag(Cxx1yLoc,
1108 getLangOpts().CPlusPlus1y
1109 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1110 : diag::ext_constexpr_body_invalid_stmt)
1111 << isa<CXXConstructorDecl>(Dcl);
1112
Richard Smith9f569cc2011-10-01 02:31:28 +00001113 if (const CXXConstructorDecl *Constructor
1114 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1115 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001116 // DR1359:
1117 // - every non-variant non-static data member and base class sub-object
1118 // shall be initialized;
1119 // - if the class is a non-empty union, or for each non-empty anonymous
1120 // union member of a non-union class, exactly one non-static data member
1121 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001122 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001123 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001124 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1125 return false;
1126 }
Richard Smith6e433752011-10-10 16:38:04 +00001127 } else if (!Constructor->isDependentContext() &&
1128 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001129 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1130
1131 // Skip detailed checking if we have enough initializers, and we would
1132 // allow at most one initializer per member.
1133 bool AnyAnonStructUnionMembers = false;
1134 unsigned Fields = 0;
1135 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1136 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001137 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001138 AnyAnonStructUnionMembers = true;
1139 break;
1140 }
1141 }
1142 if (AnyAnonStructUnionMembers ||
1143 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1144 // Check initialization of non-static data members. Base classes are
1145 // always initialized so do not need to be checked. Dependent bases
1146 // might not have initializers in the member initializer list.
1147 llvm::SmallSet<Decl*, 16> Inits;
1148 for (CXXConstructorDecl::init_const_iterator
1149 I = Constructor->init_begin(), E = Constructor->init_end();
1150 I != E; ++I) {
1151 if (FieldDecl *FD = (*I)->getMember())
1152 Inits.insert(FD);
1153 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1154 Inits.insert(ID->chain_begin(), ID->chain_end());
1155 }
1156
1157 bool Diagnosed = false;
1158 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1159 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001160 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001161 if (Diagnosed)
1162 return false;
1163 }
1164 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001165 } else {
1166 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001167 // C++1y doesn't require constexpr functions to contain a 'return'
1168 // statement. We still do, unless the return type is void, because
1169 // otherwise if there's no return statement, the function cannot
1170 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001171 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001172 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001173 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1174 : diag::err_constexpr_body_no_return);
1175 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001176 }
1177 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001178 Diag(ReturnStmts.back(),
1179 getLangOpts().CPlusPlus1y
1180 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1181 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001182 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1183 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001184 }
1185 }
1186
Richard Smith5ba73e12012-02-04 00:33:54 +00001187 // C++11 [dcl.constexpr]p5:
1188 // if no function argument values exist such that the function invocation
1189 // substitution would produce a constant expression, the program is
1190 // ill-formed; no diagnostic required.
1191 // C++11 [dcl.constexpr]p3:
1192 // - every constructor call and implicit conversion used in initializing the
1193 // return value shall be one of those allowed in a constant expression.
1194 // C++11 [dcl.constexpr]p4:
1195 // - every constructor involved in initializing non-static data members and
1196 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001197 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001198 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001199 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001200 << isa<CXXConstructorDecl>(Dcl);
1201 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1202 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001203 // Don't return false here: we allow this for compatibility in
1204 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001205 }
1206
Richard Smith9f569cc2011-10-01 02:31:28 +00001207 return true;
1208}
1209
Douglas Gregorb48fe382008-10-31 09:07:45 +00001210/// isCurrentClassName - Determine whether the identifier II is the
1211/// name of the class type currently being defined. In the case of
1212/// nested classes, this will only return true if II is the name of
1213/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001214bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1215 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001216 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001217
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001218 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001219 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001220 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001221 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1222 } else
1223 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1224
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001225 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001226 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001227 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001228}
1229
Richard Smithb79b17b2013-10-15 00:00:26 +00001230/// \brief Determine whether the identifier II is a typo for the name of
1231/// the class type currently being defined. If so, update it to the identifier
1232/// that should have been used.
1233bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1234 assert(getLangOpts().CPlusPlus && "No class names in C!");
1235
1236 if (!getLangOpts().SpellChecking)
1237 return false;
1238
1239 CXXRecordDecl *CurDecl;
1240 if (SS && SS->isSet() && !SS->isInvalid()) {
1241 DeclContext *DC = computeDeclContext(*SS, true);
1242 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1243 } else
1244 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1245
1246 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1247 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1248 < II->getLength()) {
1249 II = CurDecl->getIdentifier();
1250 return true;
1251 }
1252
1253 return false;
1254}
1255
Douglas Gregor229d47a2012-11-10 07:24:09 +00001256/// \brief Determine whether the given class is a base class of the given
1257/// class, including looking at dependent bases.
1258static bool findCircularInheritance(const CXXRecordDecl *Class,
1259 const CXXRecordDecl *Current) {
1260 SmallVector<const CXXRecordDecl*, 8> Queue;
1261
1262 Class = Class->getCanonicalDecl();
1263 while (true) {
1264 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1265 E = Current->bases_end();
1266 I != E; ++I) {
1267 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1268 if (!Base)
1269 continue;
1270
1271 Base = Base->getDefinition();
1272 if (!Base)
1273 continue;
1274
1275 if (Base->getCanonicalDecl() == Class)
1276 return true;
1277
1278 Queue.push_back(Base);
1279 }
1280
1281 if (Queue.empty())
1282 return false;
1283
Robert Wilhelm344472e2013-08-23 16:11:15 +00001284 Current = Queue.pop_back_val();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001285 }
1286
1287 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001288}
1289
Mike Stump1eb44332009-09-09 15:08:12 +00001290/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001291///
1292/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1293/// and returns NULL otherwise.
1294CXXBaseSpecifier *
1295Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1296 SourceRange SpecifierRange,
1297 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001298 TypeSourceInfo *TInfo,
1299 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001300 QualType BaseType = TInfo->getType();
1301
Douglas Gregor2943aed2009-03-03 04:44:36 +00001302 // C++ [class.union]p1:
1303 // A union shall not have base classes.
1304 if (Class->isUnion()) {
1305 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1306 << SpecifierRange;
1307 return 0;
1308 }
1309
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001310 if (EllipsisLoc.isValid() &&
1311 !TInfo->getType()->containsUnexpandedParameterPack()) {
1312 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1313 << TInfo->getTypeLoc().getSourceRange();
1314 EllipsisLoc = SourceLocation();
1315 }
Douglas Gregord777e282012-11-10 01:18:17 +00001316
1317 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1318
1319 if (BaseType->isDependentType()) {
1320 // Make sure that we don't have circular inheritance among our dependent
1321 // bases. For non-dependent bases, the check for completeness below handles
1322 // this.
1323 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1324 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1325 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001326 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001327 Diag(BaseLoc, diag::err_circular_inheritance)
1328 << BaseType << Context.getTypeDeclType(Class);
1329
1330 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1331 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1332 << BaseType;
1333
1334 return 0;
1335 }
1336 }
1337
Mike Stump1eb44332009-09-09 15:08:12 +00001338 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001339 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001340 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001341 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001342
1343 // Base specifiers must be record types.
1344 if (!BaseType->isRecordType()) {
1345 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1346 return 0;
1347 }
1348
1349 // C++ [class.union]p1:
1350 // A union shall not be used as a base class.
1351 if (BaseType->isUnionType()) {
1352 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1353 return 0;
1354 }
1355
1356 // C++ [class.derived]p2:
1357 // The class-name in a base-specifier shall not be an incompletely
1358 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001359 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001360 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001361 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001362 return 0;
John McCall572fc622010-08-17 07:23:57 +00001363 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001364
Eli Friedman1d954f62009-08-15 21:55:26 +00001365 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001366 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001367 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001368 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001369 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001370 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001371 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001372
David Majnemer28165b72013-11-02 12:00:36 +00001373 // A class which contains a flexible array member is not suitable for use as a
1374 // base class:
1375 // - If the layout determines that a base comes before another base,
1376 // the flexible array member would index into the subsequent base.
1377 // - If the layout determines that base comes before the derived class,
1378 // the flexible array member would index into the derived class.
1379 if (CXXBaseDecl->hasFlexibleArrayMember()) {
1380 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
1381 << CXXBaseDecl->getDeclName();
1382 return 0;
1383 }
1384
Anders Carlsson1d209272011-03-25 14:55:14 +00001385 // C++ [class]p3:
David Majnemer7041fcc2013-11-02 11:24:41 +00001386 // If a class is marked final and it appears as a base-type-specifier in
Anders Carlsson1d209272011-03-25 14:55:14 +00001387 // base-clause, the program is ill-formed.
David Majnemer7121bdb2013-10-18 00:33:31 +00001388 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
David Majnemer7041fcc2013-11-02 11:24:41 +00001389 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
David Majnemer7121bdb2013-10-18 00:33:31 +00001390 << CXXBaseDecl->getDeclName()
1391 << FA->isSpelledAsSealed();
Anders Carlssondfc2f102011-01-22 17:51:53 +00001392 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1393 << CXXBaseDecl->getDeclName();
1394 return 0;
1395 }
1396
John McCall572fc622010-08-17 07:23:57 +00001397 if (BaseDecl->isInvalidDecl())
1398 Class->setInvalidDecl();
David Majnemer7041fcc2013-11-02 11:24:41 +00001399
Anders Carlsson51f94042009-12-03 17:49:57 +00001400 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001401 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001402 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001403 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001404}
1405
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001406/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1407/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001408/// example:
1409/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001410/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001411BaseResult
John McCalld226f652010-08-21 09:40:31 +00001412Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001413 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001414 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001415 ParsedType basetype, SourceLocation BaseLoc,
1416 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001417 if (!classdecl)
1418 return true;
1419
Douglas Gregor40808ce2009-03-09 23:48:35 +00001420 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001421 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001422 if (!Class)
1423 return true;
1424
Richard Smith05321402013-02-19 23:47:15 +00001425 // We do not support any C++11 attributes on base-specifiers yet.
1426 // Diagnose any attributes we see.
1427 if (!Attributes.empty()) {
1428 for (AttributeList *Attr = Attributes.getList(); Attr;
1429 Attr = Attr->getNext()) {
1430 if (Attr->isInvalid() ||
1431 Attr->getKind() == AttributeList::IgnoredAttribute)
1432 continue;
1433 Diag(Attr->getLoc(),
1434 Attr->getKind() == AttributeList::UnknownAttribute
1435 ? diag::warn_unknown_attribute_ignored
1436 : diag::err_base_specifier_attribute)
1437 << Attr->getName();
1438 }
1439 }
1440
Nick Lewycky56062202010-07-26 16:56:01 +00001441 TypeSourceInfo *TInfo = 0;
1442 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001443
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001444 if (EllipsisLoc.isInvalid() &&
1445 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001446 UPPC_BaseType))
1447 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001448
Douglas Gregor2943aed2009-03-03 04:44:36 +00001449 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001450 Virtual, Access, TInfo,
1451 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001452 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001453 else
1454 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Douglas Gregor2943aed2009-03-03 04:44:36 +00001456 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001457}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001458
Douglas Gregor2943aed2009-03-03 04:44:36 +00001459/// \brief Performs the actual work of attaching the given base class
1460/// specifiers to a C++ class.
1461bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1462 unsigned NumBases) {
1463 if (NumBases == 0)
1464 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001465
1466 // Used to keep track of which base types we have already seen, so
1467 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001468 // that the key is always the unqualified canonical type of the base
1469 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001470 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1471
1472 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001473 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001474 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001475 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001476 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001477 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001478 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001479
1480 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1481 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001482 // C++ [class.mi]p3:
1483 // A class shall not be specified as a direct base class of a
1484 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001485 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001486 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001487 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001488 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001489
1490 // Delete the duplicate base class specifier; we're going to
1491 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001492 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001493
1494 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001495 } else {
1496 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001497 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001498 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001499 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1500 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1501 if (Class->isInterface() &&
1502 (!RD->isInterface() ||
1503 KnownBase->getAccessSpecifier() != AS_public)) {
1504 // The Microsoft extension __interface does not permit bases that
1505 // are not themselves public interfaces.
1506 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1507 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1508 << RD->getSourceRange();
1509 Invalid = true;
1510 }
1511 if (RD->hasAttr<WeakAttr>())
1512 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1513 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001514 }
1515 }
1516
1517 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001518 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001519
1520 // Delete the remaining (good) base class specifiers, since their
1521 // data has been copied into the CXXRecordDecl.
1522 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001523 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001524
1525 return Invalid;
1526}
1527
1528/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1529/// class, after checking whether there are any duplicate base
1530/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001531void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001532 unsigned NumBases) {
1533 if (!ClassDecl || !Bases || !NumBases)
1534 return;
1535
1536 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001537 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001538}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001539
Douglas Gregora8f32e02009-10-06 17:59:45 +00001540/// \brief Determine whether the type \p Derived is a C++ class that is
1541/// derived from the type \p Base.
1542bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001543 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001544 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001545
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001546 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001547 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001548 return false;
1549
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001550 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001551 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001552 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001553
1554 // If either the base or the derived type is invalid, don't try to
1555 // check whether one is derived from the other.
1556 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1557 return false;
1558
John McCall86ff3082010-02-04 22:26:26 +00001559 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1560 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001561}
1562
1563/// \brief Determine whether the type \p Derived is a C++ class that is
1564/// derived from the type \p Base.
1565bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001566 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001567 return false;
1568
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001569 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001570 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001571 return false;
1572
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001573 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001574 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001575 return false;
1576
Douglas Gregora8f32e02009-10-06 17:59:45 +00001577 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1578}
1579
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001580void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001581 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001582 assert(BasePathArray.empty() && "Base path array must be empty!");
1583 assert(Paths.isRecordingPaths() && "Must record paths!");
1584
1585 const CXXBasePath &Path = Paths.front();
1586
1587 // We first go backward and check if we have a virtual base.
1588 // FIXME: It would be better if CXXBasePath had the base specifier for
1589 // the nearest virtual base.
1590 unsigned Start = 0;
1591 for (unsigned I = Path.size(); I != 0; --I) {
1592 if (Path[I - 1].Base->isVirtual()) {
1593 Start = I - 1;
1594 break;
1595 }
1596 }
1597
1598 // Now add all bases.
1599 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001600 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001601}
1602
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001603/// \brief Determine whether the given base path includes a virtual
1604/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001605bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1606 for (CXXCastPath::const_iterator B = BasePath.begin(),
1607 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001608 B != BEnd; ++B)
1609 if ((*B)->isVirtual())
1610 return true;
1611
1612 return false;
1613}
1614
Douglas Gregora8f32e02009-10-06 17:59:45 +00001615/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1616/// conversion (where Derived and Base are class types) is
1617/// well-formed, meaning that the conversion is unambiguous (and
1618/// that all of the base classes are accessible). Returns true
1619/// and emits a diagnostic if the code is ill-formed, returns false
1620/// otherwise. Loc is the location where this routine should point to
1621/// if there is an error, and Range is the source range to highlight
1622/// if there is an error.
1623bool
1624Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001625 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001626 unsigned AmbigiousBaseConvID,
1627 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001628 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001629 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001630 // First, determine whether the path from Derived to Base is
1631 // ambiguous. This is slightly more expensive than checking whether
1632 // the Derived to Base conversion exists, because here we need to
1633 // explore multiple paths to determine if there is an ambiguity.
1634 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1635 /*DetectVirtual=*/false);
1636 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1637 assert(DerivationOkay &&
1638 "Can only be used with a derived-to-base conversion");
1639 (void)DerivationOkay;
1640
1641 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001642 if (InaccessibleBaseID) {
1643 // Check that the base class can be accessed.
1644 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1645 InaccessibleBaseID)) {
1646 case AR_inaccessible:
1647 return true;
1648 case AR_accessible:
1649 case AR_dependent:
1650 case AR_delayed:
1651 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001652 }
John McCall6b2accb2010-02-10 09:31:12 +00001653 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001654
1655 // Build a base path if necessary.
1656 if (BasePath)
1657 BuildBasePathArray(Paths, *BasePath);
1658 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001659 }
1660
David Majnemer2f686692013-06-22 06:43:58 +00001661 if (AmbigiousBaseConvID) {
1662 // We know that the derived-to-base conversion is ambiguous, and
1663 // we're going to produce a diagnostic. Perform the derived-to-base
1664 // search just one more time to compute all of the possible paths so
1665 // that we can print them out. This is more expensive than any of
1666 // the previous derived-to-base checks we've done, but at this point
1667 // performance isn't as much of an issue.
1668 Paths.clear();
1669 Paths.setRecordingPaths(true);
1670 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1671 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1672 (void)StillOkay;
1673
1674 // Build up a textual representation of the ambiguous paths, e.g.,
1675 // D -> B -> A, that will be used to illustrate the ambiguous
1676 // conversions in the diagnostic. We only print one of the paths
1677 // to each base class subobject.
1678 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1679
1680 Diag(Loc, AmbigiousBaseConvID)
1681 << Derived << Base << PathDisplayStr << Range << Name;
1682 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001683 return true;
1684}
1685
1686bool
1687Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001688 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001689 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001690 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001691 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001692 IgnoreAccess ? 0
1693 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001694 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001695 Loc, Range, DeclarationName(),
1696 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001697}
1698
1699
1700/// @brief Builds a string representing ambiguous paths from a
1701/// specific derived class to different subobjects of the same base
1702/// class.
1703///
1704/// This function builds a string that can be used in error messages
1705/// to show the different paths that one can take through the
1706/// inheritance hierarchy to go from the derived class to different
1707/// subobjects of a base class. The result looks something like this:
1708/// @code
1709/// struct D -> struct B -> struct A
1710/// struct D -> struct C -> struct A
1711/// @endcode
1712std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1713 std::string PathDisplayStr;
1714 std::set<unsigned> DisplayedPaths;
1715 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1716 Path != Paths.end(); ++Path) {
1717 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1718 // We haven't displayed a path to this particular base
1719 // class subobject yet.
1720 PathDisplayStr += "\n ";
1721 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1722 for (CXXBasePath::const_iterator Element = Path->begin();
1723 Element != Path->end(); ++Element)
1724 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1725 }
1726 }
1727
1728 return PathDisplayStr;
1729}
1730
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001731//===----------------------------------------------------------------------===//
1732// C++ class member Handling
1733//===----------------------------------------------------------------------===//
1734
Abramo Bagnara6206d532010-06-05 05:09:32 +00001735/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001736bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1737 SourceLocation ASLoc,
1738 SourceLocation ColonLoc,
1739 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001740 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001741 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001742 ASLoc, ColonLoc);
1743 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001744 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001745}
1746
Richard Smitha4b39652012-08-06 03:25:17 +00001747/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmandae92712013-09-05 23:51:03 +00001748void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001749 if (D->isInvalidDecl())
1750 return;
1751
Eli Friedmandae92712013-09-05 23:51:03 +00001752 // We only care about "override" and "final" declarations.
1753 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1754 return;
Anders Carlsson9e682d92011-01-20 05:57:14 +00001755
Eli Friedmandae92712013-09-05 23:51:03 +00001756 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001757
Eli Friedmandae92712013-09-05 23:51:03 +00001758 // We can't check dependent instance methods.
1759 if (MD && MD->isInstance() &&
1760 (MD->getParent()->hasAnyDependentBases() ||
1761 MD->getType()->isDependentType()))
1762 return;
1763
1764 if (MD && !MD->isVirtual()) {
1765 // If we have a non-virtual method, check if if hides a virtual method.
1766 // (In that case, it's most likely the method has the wrong type.)
1767 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1768 FindHiddenVirtualMethods(MD, OverloadedMethods);
1769
1770 if (!OverloadedMethods.empty()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001771 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1772 Diag(OA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001773 diag::override_keyword_hides_virtual_member_function)
1774 << "override" << (OverloadedMethods.size() > 1);
1775 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001776 Diag(FA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001777 diag::override_keyword_hides_virtual_member_function)
David Majnemer7121bdb2013-10-18 00:33:31 +00001778 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1779 << (OverloadedMethods.size() > 1);
Richard Smitha4b39652012-08-06 03:25:17 +00001780 }
Eli Friedmandae92712013-09-05 23:51:03 +00001781 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1782 MD->setInvalidDecl();
1783 return;
1784 }
1785 // Fall through into the general case diagnostic.
1786 // FIXME: We might want to attempt typo correction here.
1787 }
1788
1789 if (!MD || !MD->isVirtual()) {
1790 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1791 Diag(OA->getLocation(),
1792 diag::override_keyword_only_allowed_on_virtual_member_functions)
1793 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1794 D->dropAttr<OverrideAttr>();
1795 }
1796 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1797 Diag(FA->getLocation(),
1798 diag::override_keyword_only_allowed_on_virtual_member_functions)
David Majnemer7121bdb2013-10-18 00:33:31 +00001799 << (FA->isSpelledAsSealed() ? "sealed" : "final")
1800 << FixItHint::CreateRemoval(FA->getLocation());
Eli Friedmandae92712013-09-05 23:51:03 +00001801 D->dropAttr<FinalAttr>();
Richard Smitha4b39652012-08-06 03:25:17 +00001802 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001803 return;
1804 }
Richard Smitha4b39652012-08-06 03:25:17 +00001805
Richard Smitha4b39652012-08-06 03:25:17 +00001806 // C++11 [class.virtual]p5:
1807 // If a virtual function is marked with the virt-specifier override and
1808 // does not override a member function of a base class, the program is
1809 // ill-formed.
1810 bool HasOverriddenMethods =
1811 MD->begin_overridden_methods() != MD->end_overridden_methods();
1812 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1813 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1814 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001815}
1816
Richard Smitha4b39652012-08-06 03:25:17 +00001817/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001818/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001819/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001820bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1821 const CXXMethodDecl *Old) {
David Majnemer7121bdb2013-10-18 00:33:31 +00001822 FinalAttr *FA = Old->getAttr<FinalAttr>();
1823 if (!FA)
Anders Carlssonf89e0422011-01-23 21:07:30 +00001824 return false;
1825
1826 Diag(New->getLocation(), diag::err_final_function_overridden)
David Majnemer7121bdb2013-10-18 00:33:31 +00001827 << New->getDeclName()
1828 << FA->isSpelledAsSealed();
Anders Carlssonf89e0422011-01-23 21:07:30 +00001829 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1830 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001831}
1832
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001833static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001834 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1835 // FIXME: Destruction of ObjC lifetime types has side-effects.
1836 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1837 return !RD->isCompleteDefinition() ||
1838 !RD->hasTrivialDefaultConstructor() ||
1839 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001840 return false;
1841}
1842
John McCall76da55d2013-04-16 07:28:30 +00001843static AttributeList *getMSPropertyAttr(AttributeList *list) {
1844 for (AttributeList* it = list; it != 0; it = it->getNext())
1845 if (it->isDeclspecPropertyAttribute())
1846 return it;
1847 return 0;
1848}
1849
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001850/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1851/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001852/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001853/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1854/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001855NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001856Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001857 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001858 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001859 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001860 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001861 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1862 DeclarationName Name = NameInfo.getName();
1863 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001864
1865 // For anonymous bitfields, the location should point to the type.
1866 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001867 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001868
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001869 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001870
John McCall4bde1e12010-06-04 08:34:12 +00001871 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001872 assert(!DS.isFriendSpecified());
1873
Richard Smith1ab0d902011-06-25 02:28:38 +00001874 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001875
John McCalle402e722012-09-25 07:32:39 +00001876 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1877 // The Microsoft extension __interface only permits public member functions
1878 // and prohibits constructors, destructors, operators, non-public member
1879 // functions, static methods and data members.
1880 unsigned InvalidDecl;
1881 bool ShowDeclName = true;
1882 if (!isFunc)
1883 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1884 else if (AS != AS_public)
1885 InvalidDecl = 2;
1886 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1887 InvalidDecl = 3;
1888 else switch (Name.getNameKind()) {
1889 case DeclarationName::CXXConstructorName:
1890 InvalidDecl = 4;
1891 ShowDeclName = false;
1892 break;
1893
1894 case DeclarationName::CXXDestructorName:
1895 InvalidDecl = 5;
1896 ShowDeclName = false;
1897 break;
1898
1899 case DeclarationName::CXXOperatorName:
1900 case DeclarationName::CXXConversionFunctionName:
1901 InvalidDecl = 6;
1902 break;
1903
1904 default:
1905 InvalidDecl = 0;
1906 break;
1907 }
1908
1909 if (InvalidDecl) {
1910 if (ShowDeclName)
1911 Diag(Loc, diag::err_invalid_member_in_interface)
1912 << (InvalidDecl-1) << Name;
1913 else
1914 Diag(Loc, diag::err_invalid_member_in_interface)
1915 << (InvalidDecl-1) << "";
1916 return 0;
1917 }
1918 }
1919
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001920 // C++ 9.2p6: A member shall not be declared to have automatic storage
1921 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001922 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1923 // data members and cannot be applied to names declared const or static,
1924 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001925 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001926 case DeclSpec::SCS_unspecified:
1927 case DeclSpec::SCS_typedef:
1928 case DeclSpec::SCS_static:
1929 break;
1930 case DeclSpec::SCS_mutable:
1931 if (isFunc) {
1932 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Richard Smithec642442013-04-12 22:46:28 +00001934 // FIXME: It would be nicer if the keyword was ignored only for this
1935 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001936 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001937 }
1938 break;
1939 default:
1940 Diag(DS.getStorageClassSpecLoc(),
1941 diag::err_storageclass_invalid_for_member);
1942 D.getMutableDeclSpec().ClearStorageClassSpecs();
1943 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001944 }
1945
Sebastian Redl669d5d72008-11-14 23:42:31 +00001946 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1947 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001948 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001949
David Blaikie1d87fba2013-01-30 01:22:18 +00001950 if (DS.isConstexprSpecified() && isInstField) {
1951 SemaDiagnosticBuilder B =
1952 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1953 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1954 if (InitStyle == ICIS_NoInit) {
1955 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1956 D.getMutableDeclSpec().ClearConstexprSpec();
1957 const char *PrevSpec;
1958 unsigned DiagID;
1959 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1960 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001961 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001962 assert(!Failed && "Making a constexpr member const shouldn't fail");
1963 } else {
1964 B << 1;
1965 const char *PrevSpec;
1966 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001967 if (D.getMutableDeclSpec().SetStorageClassSpec(
1968 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001969 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001970 "This is the only DeclSpec that should fail to be applied");
1971 B << 1;
1972 } else {
1973 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1974 isInstField = false;
1975 }
1976 }
1977 }
1978
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001979 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001980 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001981 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001982
1983 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001984 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001985 Diag(Loc, diag::err_bad_variable_name)
1986 << Name;
1987 return 0;
1988 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001989
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001990 IdentifierInfo *II = Name.getAsIdentifierInfo();
1991
Douglas Gregorf2503652011-09-21 14:40:46 +00001992 // Member field could not be with "template" keyword.
1993 // So TemplateParameterLists should be empty in this case.
1994 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001995 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001996 if (TemplateParams->size()) {
1997 // There is no such thing as a member field template.
1998 Diag(D.getIdentifierLoc(), diag::err_template_member)
1999 << II
2000 << SourceRange(TemplateParams->getTemplateLoc(),
2001 TemplateParams->getRAngleLoc());
2002 } else {
2003 // There is an extraneous 'template<>' for this member.
2004 Diag(TemplateParams->getTemplateLoc(),
2005 diag::err_template_member_noparams)
2006 << II
2007 << SourceRange(TemplateParams->getTemplateLoc(),
2008 TemplateParams->getRAngleLoc());
2009 }
2010 return 0;
2011 }
2012
Douglas Gregor922fff22010-10-13 22:19:53 +00002013 if (SS.isSet() && !SS.isInvalid()) {
2014 // The user provided a superfluous scope specifier inside a class
2015 // definition:
2016 //
2017 // class X {
2018 // int X::member;
2019 // };
Douglas Gregor69605872012-03-28 16:01:27 +00002020 if (DeclContext *DC = computeDeclContext(SS, false))
2021 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00002022 else
2023 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2024 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00002025
Douglas Gregor922fff22010-10-13 22:19:53 +00002026 SS.clear();
2027 }
Douglas Gregorf2503652011-09-21 14:40:46 +00002028
John McCall76da55d2013-04-16 07:28:30 +00002029 AttributeList *MSPropertyAttr =
2030 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00002031 if (MSPropertyAttr) {
2032 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2033 BitWidth, InitStyle, AS, MSPropertyAttr);
2034 if (!Member)
2035 return 0;
2036 isInstField = false;
2037 } else {
2038 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2039 BitWidth, InitStyle, AS);
2040 assert(Member && "HandleField never returns null");
2041 }
2042 } else {
2043 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2044
2045 Member = HandleDeclarator(S, D, TemplateParameterLists);
2046 if (!Member)
2047 return 0;
2048
2049 // Non-instance-fields can't have a bitfield.
2050 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002051 if (Member->isInvalidDecl()) {
2052 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002053 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002054 // C++ 9.6p3: A bit-field shall not be a static member.
2055 // "static member 'A' cannot be a bit-field"
2056 Diag(Loc, diag::err_static_not_bitfield)
2057 << Name << BitWidth->getSourceRange();
2058 } else if (isa<TypedefDecl>(Member)) {
2059 // "typedef member 'x' cannot be a bit-field"
2060 Diag(Loc, diag::err_typedef_not_bitfield)
2061 << Name << BitWidth->getSourceRange();
2062 } else {
2063 // A function typedef ("typedef int f(); f a;").
2064 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2065 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00002066 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00002067 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00002068 }
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Chris Lattner8b963ef2009-03-05 23:01:03 +00002070 BitWidth = 0;
2071 Member->setInvalidDecl();
2072 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002073
2074 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Larisse Voufoef4579c2013-08-06 01:03:05 +00002076 // If we have declared a member function template or static data member
2077 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002078 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2079 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002080 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2081 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002082 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002083
Richard Smitha4b39652012-08-06 03:25:17 +00002084 if (VS.isOverrideSpecified())
2085 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2086 if (VS.isFinalSpecified())
David Majnemer7121bdb2013-10-18 00:33:31 +00002087 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2088 VS.isFinalSpelledSealed()));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002089
Douglas Gregorf5251602011-03-08 17:10:18 +00002090 if (VS.getLastLocation().isValid()) {
2091 // Update the end location of a method that has a virt-specifiers.
2092 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2093 MD->setRangeEnd(VS.getLastLocation());
2094 }
Richard Smitha4b39652012-08-06 03:25:17 +00002095
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002096 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002097
Douglas Gregor10bd3682008-11-17 22:58:34 +00002098 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002099
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002100 if (isInstField) {
2101 FieldDecl *FD = cast<FieldDecl>(Member);
2102 FieldCollector->Add(FD);
2103
2104 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2105 FD->getLocation())
2106 != DiagnosticsEngine::Ignored) {
2107 // Remember all explicit private FieldDecls that have a name, no side
2108 // effects and are not part of a dependent type declaration.
2109 if (!FD->isImplicit() && FD->getDeclName() &&
2110 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002111 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002112 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002113 !InitializationHasSideEffects(*FD))
2114 UnusedPrivateFields.insert(FD);
2115 }
2116 }
2117
John McCalld226f652010-08-21 09:40:31 +00002118 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002119}
2120
Hans Wennborg471f9852012-09-18 15:58:06 +00002121namespace {
2122 class UninitializedFieldVisitor
2123 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2124 Sema &S;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002125 // List of Decls to generate a warning on. Also remove Decls that become
2126 // initialized.
Richard Trieuef8f90c2013-09-20 03:03:06 +00002127 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002128 // If non-null, add a note to the warning pointing back to the constructor.
2129 const CXXConstructorDecl *Constructor;
Hans Wennborg471f9852012-09-18 15:58:06 +00002130 public:
2131 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieu858d2ba2013-10-25 00:56:00 +00002132 UninitializedFieldVisitor(Sema &S,
Richard Trieuef8f90c2013-09-20 03:03:06 +00002133 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
Richard Trieuef8f90c2013-09-20 03:03:06 +00002134 const CXXConstructorDecl *Constructor)
Richard Trieu858d2ba2013-10-25 00:56:00 +00002135 : Inherited(S.Context), S(S), Decls(Decls),
2136 Constructor(Constructor) { }
Hans Wennborg471f9852012-09-18 15:58:06 +00002137
Richard Trieu3ddec882013-09-16 20:46:50 +00002138 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieufbb08b52013-09-13 03:20:53 +00002139 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2140 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002141
Richard Trieufbb08b52013-09-13 03:20:53 +00002142 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2143 // or union.
2144 MemberExpr *FieldME = ME;
2145
2146 Expr *Base = ME;
2147 while (isa<MemberExpr>(Base)) {
2148 ME = cast<MemberExpr>(Base);
2149
2150 if (isa<VarDecl>(ME->getMemberDecl()))
2151 return;
2152
2153 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2154 if (!FD->isAnonymousStructOrUnion())
2155 FieldME = ME;
2156
2157 Base = ME->getBase();
2158 }
2159
Richard Trieu3ddec882013-09-16 20:46:50 +00002160 if (!isa<CXXThisExpr>(Base))
2161 return;
2162
Richard Trieuef8f90c2013-09-20 03:03:06 +00002163 ValueDecl* FoundVD = FieldME->getMemberDecl();
2164
Richard Trieu858d2ba2013-10-25 00:56:00 +00002165 if (!Decls.count(FoundVD))
Richard Trieuef8f90c2013-09-20 03:03:06 +00002166 return;
2167
Richard Trieu858d2ba2013-10-25 00:56:00 +00002168 const bool IsReference = FoundVD->getType()->isReferenceType();
Richard Trieuef8f90c2013-09-20 03:03:06 +00002169
Richard Trieu858d2ba2013-10-25 00:56:00 +00002170 // Prevent double warnings on use of unbounded references.
2171 if (IsReference != CheckReferenceOnly)
2172 return;
2173
2174 unsigned diag = IsReference
2175 ? diag::warn_reference_field_is_uninit
2176 : diag::warn_field_is_uninit;
2177 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2178 if (Constructor)
2179 S.Diag(Constructor->getLocation(),
2180 diag::note_uninit_in_this_constructor)
2181 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2182
Hans Wennborg471f9852012-09-18 15:58:06 +00002183 }
2184
2185 void HandleValue(Expr *E) {
2186 E = E->IgnoreParens();
2187
2188 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002189 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002190 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002191 }
2192
2193 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2194 HandleValue(CO->getTrueExpr());
2195 HandleValue(CO->getFalseExpr());
2196 return;
2197 }
2198
2199 if (BinaryConditionalOperator *BCO =
2200 dyn_cast<BinaryConditionalOperator>(E)) {
2201 HandleValue(BCO->getCommon());
2202 HandleValue(BCO->getFalseExpr());
2203 return;
2204 }
2205
2206 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2207 switch (BO->getOpcode()) {
2208 default:
2209 return;
2210 case(BO_PtrMemD):
2211 case(BO_PtrMemI):
2212 HandleValue(BO->getLHS());
2213 return;
2214 case(BO_Comma):
2215 HandleValue(BO->getRHS());
2216 return;
2217 }
2218 }
2219 }
2220
Richard Trieufbb08b52013-09-13 03:20:53 +00002221 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieu858d2ba2013-10-25 00:56:00 +00002222 // All uses of unbounded reference fields will warn.
Richard Trieu3ddec882013-09-16 20:46:50 +00002223 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002224
2225 Inherited::VisitMemberExpr(ME);
2226 }
2227
Hans Wennborg471f9852012-09-18 15:58:06 +00002228 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2229 if (E->getCastKind() == CK_LValueToRValue)
2230 HandleValue(E->getSubExpr());
2231
2232 Inherited::VisitImplicitCastExpr(E);
2233 }
2234
Richard Trieufbb08b52013-09-13 03:20:53 +00002235 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002236 if (E->getConstructor()->isCopyConstructor())
Richard Trieufbb08b52013-09-13 03:20:53 +00002237 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2238 if (ICE->getCastKind() == CK_NoOp)
2239 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieu3ddec882013-09-16 20:46:50 +00002240 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002241
2242 Inherited::VisitCXXConstructExpr(E);
2243 }
2244
Hans Wennborg471f9852012-09-18 15:58:06 +00002245 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2246 Expr *Callee = E->getCallee();
2247 if (isa<MemberExpr>(Callee))
2248 HandleValue(Callee);
2249
2250 Inherited::VisitCXXMemberCallExpr(E);
2251 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002252
2253 void VisitBinaryOperator(BinaryOperator *E) {
2254 // If a field assignment is detected, remove the field from the
2255 // uninitiailized field set.
2256 if (E->getOpcode() == BO_Assign)
2257 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2258 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
Richard Trieu858d2ba2013-10-25 00:56:00 +00002259 if (!FD->getType()->isReferenceType())
2260 Decls.erase(FD);
Richard Trieuef8f90c2013-09-20 03:03:06 +00002261
2262 Inherited::VisitBinaryOperator(E);
2263 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002264 };
Richard Trieuef8f90c2013-09-20 03:03:06 +00002265 static void CheckInitExprContainsUninitializedFields(
Richard Trieu858d2ba2013-10-25 00:56:00 +00002266 Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2267 const CXXConstructorDecl *Constructor) {
2268 if (Decls.size() == 0)
Richard Trieuef8f90c2013-09-20 03:03:06 +00002269 return;
2270
Richard Trieu858d2ba2013-10-25 00:56:00 +00002271 if (!E)
2272 return;
2273
2274 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2275 E = Default->getExpr();
2276 if (!E)
2277 return;
2278 // In class initializers will point to the constructor.
2279 UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2280 } else {
2281 UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2282 }
2283 }
2284
2285 // Diagnose value-uses of fields to initialize themselves, e.g.
2286 // foo(foo)
2287 // where foo is not also a parameter to the constructor.
2288 // Also diagnose across field uninitialized use such as
2289 // x(y), y(x)
2290 // TODO: implement -Wuninitialized and fold this into that framework.
2291 static void DiagnoseUninitializedFields(
2292 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2293
2294 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2295 Constructor->getLocation())
2296 == DiagnosticsEngine::Ignored) {
2297 return;
2298 }
2299
2300 if (Constructor->isInvalidDecl())
2301 return;
2302
2303 const CXXRecordDecl *RD = Constructor->getParent();
2304
2305 // Holds fields that are uninitialized.
2306 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2307
2308 // At the beginning, all fields are uninitialized.
2309 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
2310 I != E; ++I) {
2311 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
2312 UninitializedFields.insert(FD);
2313 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
2314 UninitializedFields.insert(IFD->getAnonField());
2315 }
2316 }
2317
2318 for (CXXConstructorDecl::init_const_iterator FieldInit =
2319 Constructor->init_begin(),
2320 FieldInitEnd = Constructor->init_end();
2321 FieldInit != FieldInitEnd; ++FieldInit) {
2322
2323 Expr *InitExpr = (*FieldInit)->getInit();
2324
2325 CheckInitExprContainsUninitializedFields(
2326 SemaRef, InitExpr, UninitializedFields, Constructor);
2327
2328 if (FieldDecl *Field = (*FieldInit)->getAnyMember())
2329 UninitializedFields.erase(Field);
2330 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002331 }
2332} // namespace
2333
Richard Smith7a614d82011-06-11 17:19:42 +00002334/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002335/// in-class initializer for a non-static C++ class member, and after
2336/// instantiating an in-class initializer in a class template. Such actions
2337/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002338void
Richard Smithca523302012-06-10 03:12:00 +00002339Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002340 Expr *InitExpr) {
2341 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002342 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2343 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002344
2345 if (!InitExpr) {
2346 FD->setInvalidDecl();
2347 FD->removeInClassInitializer();
2348 return;
2349 }
2350
Peter Collingbournefef21892011-10-23 18:59:44 +00002351 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2352 FD->setInvalidDecl();
2353 FD->removeInClassInitializer();
2354 return;
2355 }
2356
Richard Smith7a614d82011-06-11 17:19:42 +00002357 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002358 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002359 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002360 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002361 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002362 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002363 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2364 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002365 if (Init.isInvalid()) {
2366 FD->setInvalidDecl();
2367 return;
2368 }
Richard Smith7a614d82011-06-11 17:19:42 +00002369 }
2370
Richard Smith41956372013-01-14 22:39:08 +00002371 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002372 // The initialization of each base and member constitutes a
2373 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002374 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002375 if (Init.isInvalid()) {
2376 FD->setInvalidDecl();
2377 return;
2378 }
2379
2380 InitExpr = Init.release();
2381
2382 FD->setInClassInitializer(InitExpr);
2383}
2384
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002385/// \brief Find the direct and/or virtual base specifiers that
2386/// correspond to the given base type, for use in base initialization
2387/// within a constructor.
2388static bool FindBaseInitializer(Sema &SemaRef,
2389 CXXRecordDecl *ClassDecl,
2390 QualType BaseType,
2391 const CXXBaseSpecifier *&DirectBaseSpec,
2392 const CXXBaseSpecifier *&VirtualBaseSpec) {
2393 // First, check for a direct base class.
2394 DirectBaseSpec = 0;
2395 for (CXXRecordDecl::base_class_const_iterator Base
2396 = ClassDecl->bases_begin();
2397 Base != ClassDecl->bases_end(); ++Base) {
2398 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2399 // We found a direct base of this type. That's what we're
2400 // initializing.
2401 DirectBaseSpec = &*Base;
2402 break;
2403 }
2404 }
2405
2406 // Check for a virtual base class.
2407 // FIXME: We might be able to short-circuit this if we know in advance that
2408 // there are no virtual bases.
2409 VirtualBaseSpec = 0;
2410 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2411 // We haven't found a base yet; search the class hierarchy for a
2412 // virtual base class.
2413 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2414 /*DetectVirtual=*/false);
2415 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2416 BaseType, Paths)) {
2417 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2418 Path != Paths.end(); ++Path) {
2419 if (Path->back().Base->isVirtual()) {
2420 VirtualBaseSpec = Path->back().Base;
2421 break;
2422 }
2423 }
2424 }
2425 }
2426
2427 return DirectBaseSpec || VirtualBaseSpec;
2428}
2429
Sebastian Redl6df65482011-09-24 17:48:25 +00002430/// \brief Handle a C++ member initializer using braced-init-list syntax.
2431MemInitResult
2432Sema::ActOnMemInitializer(Decl *ConstructorD,
2433 Scope *S,
2434 CXXScopeSpec &SS,
2435 IdentifierInfo *MemberOrBase,
2436 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002437 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002438 SourceLocation IdLoc,
2439 Expr *InitList,
2440 SourceLocation EllipsisLoc) {
2441 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002442 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002443 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002444}
2445
2446/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002447MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002448Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002449 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002450 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002451 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002452 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002453 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002454 SourceLocation IdLoc,
2455 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002456 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002457 SourceLocation RParenLoc,
2458 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002459 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002460 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002461 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002462 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002463}
2464
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002465namespace {
2466
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002467// Callback to only accept typo corrections that can be a valid C++ member
2468// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002469class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002470public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002471 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2472 : ClassDecl(ClassDecl) {}
2473
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002474 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002475 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2476 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2477 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002478 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002479 }
2480 return false;
2481 }
2482
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002483private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002484 CXXRecordDecl *ClassDecl;
2485};
2486
2487}
2488
Sebastian Redl6df65482011-09-24 17:48:25 +00002489/// \brief Handle a C++ member initializer.
2490MemInitResult
2491Sema::BuildMemInitializer(Decl *ConstructorD,
2492 Scope *S,
2493 CXXScopeSpec &SS,
2494 IdentifierInfo *MemberOrBase,
2495 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002496 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002497 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002498 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002499 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002500 if (!ConstructorD)
2501 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002502
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002503 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002504
2505 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002506 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002507 if (!Constructor) {
2508 // The user wrote a constructor initializer on a function that is
2509 // not a C++ constructor. Ignore the error for now, because we may
2510 // have more member initializers coming; we'll diagnose it just
2511 // once in ActOnMemInitializers.
2512 return true;
2513 }
2514
2515 CXXRecordDecl *ClassDecl = Constructor->getParent();
2516
2517 // C++ [class.base.init]p2:
2518 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002519 // constructor's class and, if not found in that scope, are looked
2520 // up in the scope containing the constructor's definition.
2521 // [Note: if the constructor's class contains a member with the
2522 // same name as a direct or virtual base class of the class, a
2523 // mem-initializer-id naming the member or base class and composed
2524 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002525 // mem-initializer-id for the hidden base class may be specified
2526 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002527 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002528 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002529 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002530 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002531 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002532 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002533 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2534 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002535 if (EllipsisLoc.isValid())
2536 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002537 << MemberOrBase
2538 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002539
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002540 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002541 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002542 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002543 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002544 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002545 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002546 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002547
2548 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002549 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002550 } else if (DS.getTypeSpecType() == TST_decltype) {
2551 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002552 } else {
2553 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2554 LookupParsedName(R, S, &SS);
2555
2556 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2557 if (!TyD) {
2558 if (R.isAmbiguous()) return true;
2559
John McCallfd225442010-04-09 19:01:14 +00002560 // We don't want access-control diagnostics here.
2561 R.suppressDiagnostics();
2562
Douglas Gregor7a886e12010-01-19 06:46:48 +00002563 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2564 bool NotUnknownSpecialization = false;
2565 DeclContext *DC = computeDeclContext(SS, false);
2566 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2567 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2568
2569 if (!NotUnknownSpecialization) {
2570 // When the scope specifier can refer to a member of an unknown
2571 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002572 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2573 SS.getWithLocInContext(Context),
2574 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002575 if (BaseType.isNull())
2576 return true;
2577
Douglas Gregor7a886e12010-01-19 06:46:48 +00002578 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002579 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002580 }
2581 }
2582
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002583 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002584 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002585 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002586 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002587 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002588 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002589 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002590 // We have found a non-static data member with a similar
2591 // name to what was typed; complain and initialize that
2592 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002593 diagnoseTypo(Corr,
2594 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2595 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002596 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002597 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002598 const CXXBaseSpecifier *DirectBaseSpec;
2599 const CXXBaseSpecifier *VirtualBaseSpec;
2600 if (FindBaseInitializer(*this, ClassDecl,
2601 Context.getTypeDeclType(Type),
2602 DirectBaseSpec, VirtualBaseSpec)) {
2603 // We have found a direct or virtual base class with a
2604 // similar name to what was typed; complain and initialize
2605 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002606 diagnoseTypo(Corr,
2607 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2608 << MemberOrBase << false,
2609 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002610
Richard Smith2d670972013-08-17 00:46:16 +00002611 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2612 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002613 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002614 diag::note_base_class_specified_here)
2615 << BaseSpec->getType()
2616 << BaseSpec->getSourceRange();
2617
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002618 TyD = Type;
2619 }
2620 }
2621 }
2622
Douglas Gregor7a886e12010-01-19 06:46:48 +00002623 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002624 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002625 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002626 return true;
2627 }
John McCall2b194412009-12-21 10:41:20 +00002628 }
2629
Douglas Gregor7a886e12010-01-19 06:46:48 +00002630 if (BaseType.isNull()) {
2631 BaseType = Context.getTypeDeclType(TyD);
2632 if (SS.isSet()) {
2633 NestedNameSpecifier *Qualifier =
2634 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002635
Douglas Gregor7a886e12010-01-19 06:46:48 +00002636 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002637 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002638 }
John McCall2b194412009-12-21 10:41:20 +00002639 }
2640 }
Mike Stump1eb44332009-09-09 15:08:12 +00002641
John McCalla93c9342009-12-07 02:54:59 +00002642 if (!TInfo)
2643 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002644
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002645 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002646}
2647
Chandler Carruth81c64772011-09-03 01:14:15 +00002648/// Checks a member initializer expression for cases where reference (or
2649/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002650static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2651 Expr *Init,
2652 SourceLocation IdLoc) {
2653 QualType MemberTy = Member->getType();
2654
2655 // We only handle pointers and references currently.
2656 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2657 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2658 return;
2659
2660 const bool IsPointer = MemberTy->isPointerType();
2661 if (IsPointer) {
2662 if (const UnaryOperator *Op
2663 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2664 // The only case we're worried about with pointers requires taking the
2665 // address.
2666 if (Op->getOpcode() != UO_AddrOf)
2667 return;
2668
2669 Init = Op->getSubExpr();
2670 } else {
2671 // We only handle address-of expression initializers for pointers.
2672 return;
2673 }
2674 }
2675
Richard Smitha4bb99c2013-06-12 21:51:50 +00002676 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002677 // We only warn when referring to a non-reference parameter declaration.
2678 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2679 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002680 return;
2681
2682 S.Diag(Init->getExprLoc(),
2683 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2684 : diag::warn_bind_ref_member_to_parameter)
2685 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002686 } else {
2687 // Other initializers are fine.
2688 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002689 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002690
2691 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2692 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002693}
2694
John McCallf312b1e2010-08-26 23:41:50 +00002695MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002696Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002697 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002698 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2699 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2700 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002701 "Member must be a FieldDecl or IndirectFieldDecl");
2702
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002703 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002704 return true;
2705
Douglas Gregor464b2f02010-11-05 22:21:31 +00002706 if (Member->isInvalidDecl())
2707 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002708
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002709 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002710 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002711 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002712 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002713 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002714 } else {
2715 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002716 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002717 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002718
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002719 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002720
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002721 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002722 // Can't check initialization for a member of dependent type or when
2723 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002724 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002725 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002726 bool InitList = false;
2727 if (isa<InitListExpr>(Init)) {
2728 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002729 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002730 }
2731
Chandler Carruth894aed92010-12-06 09:23:57 +00002732 // Initialize the member.
2733 InitializedEntity MemberEntity =
2734 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2735 : InitializedEntity::InitializeMember(IndirectMember, 0);
2736 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002737 InitList ? InitializationKind::CreateDirectList(IdLoc)
2738 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2739 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002740
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002741 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2742 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002743 if (MemberInit.isInvalid())
2744 return true;
2745
Richard Smith8a07cd32013-06-12 20:42:33 +00002746 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2747
Richard Smith41956372013-01-14 22:39:08 +00002748 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002749 // The initialization of each base and member constitutes a
2750 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002751 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002752 if (MemberInit.isInvalid())
2753 return true;
2754
Richard Smithc83c2302012-12-19 01:39:02 +00002755 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002756 }
2757
Chandler Carruth894aed92010-12-06 09:23:57 +00002758 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002759 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2760 InitRange.getBegin(), Init,
2761 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002762 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002763 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2764 InitRange.getBegin(), Init,
2765 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002766 }
Eli Friedman59c04372009-07-29 19:44:27 +00002767}
2768
John McCallf312b1e2010-08-26 23:41:50 +00002769MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002770Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002771 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002772 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002773 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002774 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002775 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002776 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002777
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002778 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002779 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002780 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2781 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002782 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002783 }
2784
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002785 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002786 // Initialize the object.
2787 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2788 QualType(ClassDecl->getTypeForDecl(), 0));
2789 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002790 InitList ? InitializationKind::CreateDirectList(NameLoc)
2791 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2792 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002793 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002794 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002795 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002796 if (DelegationInit.isInvalid())
2797 return true;
2798
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002799 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2800 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002801
Richard Smith41956372013-01-14 22:39:08 +00002802 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002803 // The initialization of each base and member constitutes a
2804 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002805 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2806 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002807 if (DelegationInit.isInvalid())
2808 return true;
2809
Eli Friedmand21016f2012-05-19 23:35:23 +00002810 // If we are in a dependent context, template instantiation will
2811 // perform this type-checking again. Just save the arguments that we
2812 // received in a ParenListExpr.
2813 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2814 // of the information that we have about the base
2815 // initializer. However, deconstructing the ASTs is a dicey process,
2816 // and this approach is far more likely to get the corner cases right.
2817 if (CurContext->isDependentContext())
2818 DelegationInit = Owned(Init);
2819
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002820 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002821 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002822 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002823}
2824
2825MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002826Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002827 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002828 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002829 SourceLocation BaseLoc
2830 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002831
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002832 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2833 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2834 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2835
2836 // C++ [class.base.init]p2:
2837 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002838 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002839 // of that class, the mem-initializer is ill-formed. A
2840 // mem-initializer-list can initialize a base class using any
2841 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002842 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002843
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002844 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002845 if (EllipsisLoc.isValid()) {
2846 // This is a pack expansion.
2847 if (!BaseType->containsUnexpandedParameterPack()) {
2848 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002849 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002850
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002851 EllipsisLoc = SourceLocation();
2852 }
2853 } else {
2854 // Check for any unexpanded parameter packs.
2855 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2856 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002857
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002858 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002859 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002860 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002861
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002862 // Check for direct and virtual base classes.
2863 const CXXBaseSpecifier *DirectBaseSpec = 0;
2864 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2865 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002866 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2867 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002868 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002869
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002870 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2871 VirtualBaseSpec);
2872
2873 // C++ [base.class.init]p2:
2874 // Unless the mem-initializer-id names a nonstatic data member of the
2875 // constructor's class or a direct or virtual base of that class, the
2876 // mem-initializer is ill-formed.
2877 if (!DirectBaseSpec && !VirtualBaseSpec) {
2878 // If the class has any dependent bases, then it's possible that
2879 // one of those types will resolve to the same type as
2880 // BaseType. Therefore, just treat this as a dependent base
2881 // class initialization. FIXME: Should we try to check the
2882 // initialization anyway? It seems odd.
2883 if (ClassDecl->hasAnyDependentBases())
2884 Dependent = true;
2885 else
2886 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2887 << BaseType << Context.getTypeDeclType(ClassDecl)
2888 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2889 }
2890 }
2891
2892 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002893 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002894
Sebastian Redl6df65482011-09-24 17:48:25 +00002895 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2896 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002897 InitRange.getBegin(), Init,
2898 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002899 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002900
2901 // C++ [base.class.init]p2:
2902 // If a mem-initializer-id is ambiguous because it designates both
2903 // a direct non-virtual base class and an inherited virtual base
2904 // class, the mem-initializer is ill-formed.
2905 if (DirectBaseSpec && VirtualBaseSpec)
2906 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002907 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002908
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002909 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002910 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002911 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002912
2913 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002914 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002915 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002916 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002917 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002918 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002919 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002920
2921 InitializedEntity BaseEntity =
2922 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2923 InitializationKind Kind =
2924 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2925 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2926 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002927 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2928 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002929 if (BaseInit.isInvalid())
2930 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002931
Richard Smith41956372013-01-14 22:39:08 +00002932 // C++11 [class.base.init]p7:
2933 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002934 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002935 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002936 if (BaseInit.isInvalid())
2937 return true;
2938
2939 // If we are in a dependent context, template instantiation will
2940 // perform this type-checking again. Just save the arguments that we
2941 // received in a ParenListExpr.
2942 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2943 // of the information that we have about the base
2944 // initializer. However, deconstructing the ASTs is a dicey process,
2945 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002946 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002947 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002948
Sean Huntcbb67482011-01-08 20:30:50 +00002949 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002950 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002951 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002952 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002953 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002954}
2955
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002956// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002957static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2958 if (T.isNull()) T = E->getType();
2959 QualType TargetType = SemaRef.BuildReferenceType(
2960 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002961 SourceLocation ExprLoc = E->getLocStart();
2962 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2963 TargetType, ExprLoc);
2964
2965 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2966 SourceRange(ExprLoc, ExprLoc),
2967 E->getSourceRange()).take();
2968}
2969
Anders Carlssone5ef7402010-04-23 03:10:23 +00002970/// ImplicitInitializerKind - How an implicit base or member initializer should
2971/// initialize its base or member.
2972enum ImplicitInitializerKind {
2973 IIK_Default,
2974 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002975 IIK_Move,
2976 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002977};
2978
Anders Carlssondefefd22010-04-23 02:00:02 +00002979static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002980BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002981 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002982 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002983 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002984 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002985 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002986 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2987 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002988
John McCall60d7b3a2010-08-24 06:29:42 +00002989 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002990
2991 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002992 case IIK_Inherit: {
2993 const CXXRecordDecl *Inherited =
2994 Constructor->getInheritedConstructor()->getParent();
2995 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2996 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2997 // C++11 [class.inhctor]p8:
2998 // Each expression in the expression-list is of the form
2999 // static_cast<T&&>(p), where p is the name of the corresponding
3000 // constructor parameter and T is the declared type of p.
3001 SmallVector<Expr*, 16> Args;
3002 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
3003 ParmVarDecl *PD = Constructor->getParamDecl(I);
3004 ExprResult ArgExpr =
3005 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
3006 VK_LValue, SourceLocation());
3007 if (ArgExpr.isInvalid())
3008 return true;
3009 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
3010 }
3011
3012 InitializationKind InitKind = InitializationKind::CreateDirect(
3013 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003014 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00003015 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3016 break;
3017 }
3018 }
3019 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00003020 case IIK_Default: {
3021 InitializationKind InitKind
3022 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003023 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3024 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003025 break;
3026 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003027
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003028 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00003029 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003030 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00003031 ParmVarDecl *Param = Constructor->getParamDecl(0);
3032 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00003033
Anders Carlssone5ef7402010-04-23 03:10:23 +00003034 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003035 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003036 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00003037 Constructor->getLocation(), ParamType,
3038 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003039
Eli Friedman5f2987c2012-02-02 03:46:19 +00003040 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3041
Anders Carlssonc7957502010-04-24 22:02:54 +00003042 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00003043 QualType ArgTy =
3044 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3045 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00003046
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003047 if (Moving) {
3048 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3049 }
3050
John McCallf871d0c2010-08-07 06:22:56 +00003051 CXXCastPath BasePath;
3052 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00003053 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3054 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003055 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003056 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00003057
Anders Carlssone5ef7402010-04-23 03:10:23 +00003058 InitializationKind InitKind
3059 = InitializationKind::CreateDirect(Constructor->getLocation(),
3060 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003061 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3062 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003063 break;
3064 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00003065 }
John McCall9ae2f072010-08-23 23:25:46 +00003066
Douglas Gregor53c374f2010-12-07 00:41:46 +00003067 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00003068 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00003069 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00003070
Anders Carlssondefefd22010-04-23 02:00:02 +00003071 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00003072 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00003073 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3074 SourceLocation()),
3075 BaseSpec->isVirtual(),
3076 SourceLocation(),
3077 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003078 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00003079 SourceLocation());
3080
Anders Carlssondefefd22010-04-23 02:00:02 +00003081 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00003082}
3083
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003084static bool RefersToRValueRef(Expr *MemRef) {
3085 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3086 return Referenced->getType()->isRValueReferenceType();
3087}
3088
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003089static bool
3090BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003091 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003092 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00003093 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003094 if (Field->isInvalidDecl())
3095 return true;
3096
Chandler Carruthf186b542010-06-29 23:50:44 +00003097 SourceLocation Loc = Constructor->getLocation();
3098
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003099 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3100 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003101 ParmVarDecl *Param = Constructor->getParamDecl(0);
3102 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00003103
3104 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003105 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3106 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00003107
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003108 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003109 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003110 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00003111 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003112
Eli Friedman5f2987c2012-02-02 03:46:19 +00003113 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3114
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003115 if (Moving) {
3116 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3117 }
3118
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003119 // Build a reference to this field within the parameter.
3120 CXXScopeSpec SS;
3121 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3122 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003123 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3124 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003125 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00003126 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00003127 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003128 ParamType, Loc,
3129 /*IsArrow=*/false,
3130 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003131 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003132 /*FirstQualifierInScope=*/0,
3133 MemberLookup,
3134 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003135 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003136 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003137
3138 // C++11 [class.copy]p15:
3139 // - if a member m has rvalue reference type T&&, it is direct-initialized
3140 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003141 if (RefersToRValueRef(CtorArg.get())) {
3142 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003143 }
3144
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003145 // When the field we are copying is an array, create index variables for
3146 // each dimension of the array. We use these index variables to subscript
3147 // the source array, and other clients (e.g., CodeGen) will perform the
3148 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003149 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003150 QualType BaseType = Field->getType();
3151 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003152 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003153 while (const ConstantArrayType *Array
3154 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003155 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003156 // Create the iteration variable for this array index.
3157 IdentifierInfo *IterationVarName = 0;
3158 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003159 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003160 llvm::raw_svector_ostream OS(Str);
3161 OS << "__i" << IndexVariables.size();
3162 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3163 }
3164 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003165 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003166 IterationVarName, SizeType,
3167 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003168 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003169 IndexVariables.push_back(IterationVar);
3170
3171 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003172 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003173 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003174 assert(!IterationVarRef.isInvalid() &&
3175 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003176 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3177 assert(!IterationVarRef.isInvalid() &&
3178 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003179
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003180 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003181 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003182 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003183 Loc);
3184 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003185 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003186
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003187 BaseType = Array->getElementType();
3188 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003189
3190 // The array subscript expression is an lvalue, which is wrong for moving.
3191 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003192 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003193
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003194 // Construct the entity that we will be initializing. For an array, this
3195 // will be first element in the array, which may require several levels
3196 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003197 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003198 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003199 if (Indirect)
3200 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3201 else
3202 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003203 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3204 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3205 0,
3206 Entities.back()));
3207
3208 // Direct-initialize to use the copy constructor.
3209 InitializationKind InitKind =
3210 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3211
Sebastian Redl74e611a2011-09-04 18:14:28 +00003212 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003213 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003214
John McCall60d7b3a2010-08-24 06:29:42 +00003215 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003216 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003217 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003218 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003219 if (MemberInit.isInvalid())
3220 return true;
3221
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003222 if (Indirect) {
3223 assert(IndexVariables.size() == 0 &&
3224 "Indirect field improperly initialized");
3225 CXXMemberInit
3226 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3227 Loc, Loc,
3228 MemberInit.takeAs<Expr>(),
3229 Loc);
3230 } else
3231 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3232 Loc, MemberInit.takeAs<Expr>(),
3233 Loc,
3234 IndexVariables.data(),
3235 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003236 return false;
3237 }
3238
Richard Smith07b0fdc2013-03-18 21:12:30 +00003239 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3240 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003241
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003242 QualType FieldBaseElementType =
3243 SemaRef.Context.getBaseElementType(Field->getType());
3244
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003245 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003246 InitializedEntity InitEntity
3247 = Indirect? InitializedEntity::InitializeMember(Indirect)
3248 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003249 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003250 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003251
3252 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3253 ExprResult MemberInit =
3254 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003255
Douglas Gregor53c374f2010-12-07 00:41:46 +00003256 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003257 if (MemberInit.isInvalid())
3258 return true;
3259
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003260 if (Indirect)
3261 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3262 Indirect, Loc,
3263 Loc,
3264 MemberInit.get(),
3265 Loc);
3266 else
3267 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3268 Field, Loc, Loc,
3269 MemberInit.get(),
3270 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003271 return false;
3272 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003273
Sean Hunt1f2f3842011-05-17 00:19:05 +00003274 if (!Field->getParent()->isUnion()) {
3275 if (FieldBaseElementType->isReferenceType()) {
3276 SemaRef.Diag(Constructor->getLocation(),
3277 diag::err_uninitialized_member_in_ctor)
3278 << (int)Constructor->isImplicit()
3279 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3280 << 0 << Field->getDeclName();
3281 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3282 return true;
3283 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003284
Sean Hunt1f2f3842011-05-17 00:19:05 +00003285 if (FieldBaseElementType.isConstQualified()) {
3286 SemaRef.Diag(Constructor->getLocation(),
3287 diag::err_uninitialized_member_in_ctor)
3288 << (int)Constructor->isImplicit()
3289 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3290 << 1 << Field->getDeclName();
3291 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3292 return true;
3293 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003294 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003295
David Blaikie4e4d0842012-03-11 07:00:24 +00003296 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003297 FieldBaseElementType->isObjCRetainableType() &&
3298 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3299 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003300 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003301 // Default-initialize Objective-C pointers to NULL.
3302 CXXMemberInit
3303 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3304 Loc, Loc,
3305 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3306 Loc);
3307 return false;
3308 }
3309
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003310 // Nothing to initialize.
3311 CXXMemberInit = 0;
3312 return false;
3313}
John McCallf1860e52010-05-20 23:23:51 +00003314
3315namespace {
3316struct BaseAndFieldInfo {
3317 Sema &S;
3318 CXXConstructorDecl *Ctor;
3319 bool AnyErrorsInInits;
3320 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003321 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003322 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003323
3324 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3325 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003326 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3327 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003328 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003329 else if (Generated && Ctor->isMoveConstructor())
3330 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003331 else if (Ctor->getInheritedConstructor())
3332 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003333 else
3334 IIK = IIK_Default;
3335 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003336
3337 bool isImplicitCopyOrMove() const {
3338 switch (IIK) {
3339 case IIK_Copy:
3340 case IIK_Move:
3341 return true;
3342
3343 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003344 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003345 return false;
3346 }
David Blaikie30263482012-01-20 21:50:17 +00003347
3348 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003349 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003350
3351 bool addFieldInitializer(CXXCtorInitializer *Init) {
3352 AllToInit.push_back(Init);
3353
3354 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003355 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003356 S.UnusedPrivateFields.remove(Init->getAnyMember());
3357
3358 return false;
3359 }
John McCallf1860e52010-05-20 23:23:51 +00003360};
3361}
3362
Richard Smitha4950662011-09-19 13:34:43 +00003363/// \brief Determine whether the given indirect field declaration is somewhere
3364/// within an anonymous union.
3365static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3366 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3367 CEnd = F->chain_end();
3368 C != CEnd; ++C)
3369 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3370 if (Record->isUnion())
3371 return true;
3372
3373 return false;
3374}
3375
Douglas Gregorddb21472011-11-02 23:04:16 +00003376/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3377/// array type.
3378static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3379 if (T->isIncompleteArrayType())
3380 return true;
3381
3382 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3383 if (!ArrayT->getSize())
3384 return true;
3385
3386 T = ArrayT->getElementType();
3387 }
3388
3389 return false;
3390}
3391
Richard Smith7a614d82011-06-11 17:19:42 +00003392static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003393 FieldDecl *Field,
3394 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003395 if (Field->isInvalidDecl())
3396 return false;
John McCallf1860e52010-05-20 23:23:51 +00003397
Chandler Carruthe861c602010-06-30 02:59:29 +00003398 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003399 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3400 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003401
Richard Smith0b8220a2012-08-07 21:30:42 +00003402 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003403 // has a brace-or-equal-initializer, the entity is initialized as specified
3404 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003405 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003406 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3407 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003408 CXXCtorInitializer *Init;
3409 if (Indirect)
3410 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3411 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003412 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003413 SourceLocation());
3414 else
3415 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3416 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003417 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003418 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003419 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003420 }
3421
Richard Smithc115f632011-09-18 11:14:50 +00003422 // Don't build an implicit initializer for union members if none was
3423 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003424 if (Field->getParent()->isUnion() ||
3425 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003426 return false;
3427
Douglas Gregorddb21472011-11-02 23:04:16 +00003428 // Don't initialize incomplete or zero-length arrays.
3429 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3430 return false;
3431
John McCallf1860e52010-05-20 23:23:51 +00003432 // Don't try to build an implicit initializer if there were semantic
3433 // errors in any of the initializers (and therefore we might be
3434 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003435 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003436 return false;
3437
Sean Huntcbb67482011-01-08 20:30:50 +00003438 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003439 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3440 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003441 return true;
John McCallf1860e52010-05-20 23:23:51 +00003442
Richard Smith0b8220a2012-08-07 21:30:42 +00003443 if (!Init)
3444 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003445
Richard Smith0b8220a2012-08-07 21:30:42 +00003446 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003447}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003448
3449bool
3450Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3451 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003452 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003453 Constructor->setNumCtorInitializers(1);
3454 CXXCtorInitializer **initializer =
3455 new (Context) CXXCtorInitializer*[1];
3456 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3457 Constructor->setCtorInitializers(initializer);
3458
Sean Huntb76af9c2011-05-03 23:05:34 +00003459 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003460 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003461 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3462 }
3463
Sean Huntc1598702011-05-05 00:05:47 +00003464 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003465
Sean Hunt059ce0d2011-05-01 07:04:31 +00003466 return false;
3467}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003468
David Blaikie93c86172013-01-17 05:26:25 +00003469bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3470 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003471 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003472 // Just store the initializers as written, they will be checked during
3473 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003474 if (!Initializers.empty()) {
3475 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003476 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003477 new (Context) CXXCtorInitializer*[Initializers.size()];
3478 memcpy(baseOrMemberInitializers, Initializers.data(),
3479 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003480 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003481 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003482
3483 // Let template instantiation know whether we had errors.
3484 if (AnyErrors)
3485 Constructor->setInvalidDecl();
3486
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003487 return false;
3488 }
3489
John McCallf1860e52010-05-20 23:23:51 +00003490 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003491
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003492 // We need to build the initializer AST according to order of construction
3493 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003494 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003495 if (!ClassDecl)
3496 return true;
3497
Eli Friedman80c30da2009-11-09 19:20:36 +00003498 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003499
David Blaikie93c86172013-01-17 05:26:25 +00003500 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003501 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003502
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003503 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003504 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003505 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003506 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003507 }
3508
Anders Carlsson711f34a2010-04-21 19:52:01 +00003509 // Keep track of the direct virtual bases.
3510 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3511 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3512 E = ClassDecl->bases_end(); I != E; ++I) {
3513 if (I->isVirtual())
3514 DirectVBases.insert(I);
3515 }
3516
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003517 // Push virtual bases before others.
3518 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3519 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3520
Sean Huntcbb67482011-01-08 20:30:50 +00003521 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003522 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003523 // [class.base.init]p7, per DR257:
3524 // A mem-initializer where the mem-initializer-id names a virtual base
3525 // class is ignored during execution of a constructor of any class that
3526 // is not the most derived class.
3527 if (ClassDecl->isAbstract()) {
3528 // FIXME: Provide a fixit to remove the base specifier. This requires
3529 // tracking the location of the associated comma for a base specifier.
3530 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3531 << VBase->getType() << ClassDecl;
3532 DiagnoseAbstractType(ClassDecl);
3533 }
3534
John McCallf1860e52010-05-20 23:23:51 +00003535 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003536 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3537 // [class.base.init]p8, per DR257:
3538 // If a given [...] base class is not named by a mem-initializer-id
3539 // [...] and the entity is not a virtual base class of an abstract
3540 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003541 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003542 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003543 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003544 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003545 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003546 HadError = true;
3547 continue;
3548 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003549
John McCallf1860e52010-05-20 23:23:51 +00003550 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003551 }
3552 }
Mike Stump1eb44332009-09-09 15:08:12 +00003553
John McCallf1860e52010-05-20 23:23:51 +00003554 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003555 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3556 E = ClassDecl->bases_end(); Base != E; ++Base) {
3557 // Virtuals are in the virtual base list and already constructed.
3558 if (Base->isVirtual())
3559 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Sean Huntcbb67482011-01-08 20:30:50 +00003561 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003562 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3563 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003564 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003565 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003566 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003567 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003568 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003569 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003570 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003571 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003572
John McCallf1860e52010-05-20 23:23:51 +00003573 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003574 }
3575 }
Mike Stump1eb44332009-09-09 15:08:12 +00003576
John McCallf1860e52010-05-20 23:23:51 +00003577 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003578 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3579 MemEnd = ClassDecl->decls_end();
3580 Mem != MemEnd; ++Mem) {
3581 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003582 // C++ [class.bit]p2:
3583 // A declaration for a bit-field that omits the identifier declares an
3584 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3585 // initialized.
3586 if (F->isUnnamedBitfield())
3587 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003588
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003589 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003590 // handle anonymous struct/union fields based on their individual
3591 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003592 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003593 continue;
3594
3595 if (CollectFieldInitializer(*this, Info, F))
3596 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003597 continue;
3598 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003599
3600 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003601 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003602 continue;
3603
3604 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3605 if (F->getType()->isIncompleteArrayType()) {
3606 assert(ClassDecl->hasFlexibleArrayMember() &&
3607 "Incomplete array type is not valid");
3608 continue;
3609 }
3610
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003611 // Initialize each field of an anonymous struct individually.
3612 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3613 HadError = true;
3614
3615 continue;
3616 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003617 }
Mike Stump1eb44332009-09-09 15:08:12 +00003618
David Blaikie93c86172013-01-17 05:26:25 +00003619 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003620 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003621 Constructor->setNumCtorInitializers(NumInitializers);
3622 CXXCtorInitializer **baseOrMemberInitializers =
3623 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003624 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003625 NumInitializers * sizeof(CXXCtorInitializer*));
3626 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003627
John McCallef027fe2010-03-16 21:39:52 +00003628 // Constructors implicitly reference the base and member
3629 // destructors.
3630 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3631 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003632 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003633
3634 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003635}
3636
David Blaikieee000bb2013-01-17 08:49:22 +00003637static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003638 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003639 const RecordDecl *RD = RT->getDecl();
3640 if (RD->isAnonymousStructOrUnion()) {
3641 for (RecordDecl::field_iterator Field = RD->field_begin(),
3642 E = RD->field_end(); Field != E; ++Field)
3643 PopulateKeysForFields(*Field, IdealInits);
3644 return;
3645 }
Eli Friedman6347f422009-07-21 19:28:10 +00003646 }
David Blaikieee000bb2013-01-17 08:49:22 +00003647 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003648}
3649
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003650static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3651 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003652}
3653
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003654static const void *GetKeyForMember(ASTContext &Context,
3655 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003656 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003657 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003658
David Blaikieee000bb2013-01-17 08:49:22 +00003659 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003660}
3661
David Blaikie93c86172013-01-17 05:26:25 +00003662static void DiagnoseBaseOrMemInitializerOrder(
3663 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3664 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003665 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003666 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003667
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003668 // Don't check initializers order unless the warning is enabled at the
3669 // location of at least one initializer.
3670 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003671 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003672 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003673 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3674 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003675 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003676 ShouldCheckOrder = true;
3677 break;
3678 }
3679 }
3680 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003681 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003682
John McCalld6ca8da2010-04-10 07:37:23 +00003683 // Build the list of bases and members in the order that they'll
3684 // actually be initialized. The explicit initializers should be in
3685 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003686 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003687
Anders Carlsson071d6102010-04-02 03:38:04 +00003688 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3689
John McCalld6ca8da2010-04-10 07:37:23 +00003690 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003691 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003692 ClassDecl->vbases_begin(),
3693 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003694 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003695
John McCalld6ca8da2010-04-10 07:37:23 +00003696 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003697 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003698 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003699 if (Base->isVirtual())
3700 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003701 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003702 }
Mike Stump1eb44332009-09-09 15:08:12 +00003703
John McCalld6ca8da2010-04-10 07:37:23 +00003704 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003705 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003706 E = ClassDecl->field_end(); Field != E; ++Field) {
3707 if (Field->isUnnamedBitfield())
3708 continue;
3709
David Blaikieee000bb2013-01-17 08:49:22 +00003710 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003711 }
3712
John McCalld6ca8da2010-04-10 07:37:23 +00003713 unsigned NumIdealInits = IdealInitKeys.size();
3714 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003715
Sean Huntcbb67482011-01-08 20:30:50 +00003716 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003717 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003718 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003719 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003720
3721 // Scan forward to try to find this initializer in the idealized
3722 // initializers list.
3723 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3724 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003725 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003726
3727 // If we didn't find this initializer, it must be because we
3728 // scanned past it on a previous iteration. That can only
3729 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003730 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003731 Sema::SemaDiagnosticBuilder D =
3732 SemaRef.Diag(PrevInit->getSourceLocation(),
3733 diag::warn_initializer_out_of_order);
3734
Francois Pichet00eb3f92010-12-04 09:14:42 +00003735 if (PrevInit->isAnyMemberInitializer())
3736 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003737 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003738 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003739
Francois Pichet00eb3f92010-12-04 09:14:42 +00003740 if (Init->isAnyMemberInitializer())
3741 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003742 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003743 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003744
3745 // Move back to the initializer's location in the ideal list.
3746 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3747 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003748 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003749
3750 assert(IdealIndex != NumIdealInits &&
3751 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003752 }
John McCalld6ca8da2010-04-10 07:37:23 +00003753
3754 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003755 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003756}
3757
John McCall3c3ccdb2010-04-10 09:28:51 +00003758namespace {
3759bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003760 CXXCtorInitializer *Init,
3761 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003762 if (!PrevInit) {
3763 PrevInit = Init;
3764 return false;
3765 }
3766
Douglas Gregordc392c12013-03-25 23:28:23 +00003767 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003768 S.Diag(Init->getSourceLocation(),
3769 diag::err_multiple_mem_initialization)
3770 << Field->getDeclName()
3771 << Init->getSourceRange();
3772 else {
John McCallf4c73712011-01-19 06:33:43 +00003773 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003774 assert(BaseClass && "neither field nor base");
3775 S.Diag(Init->getSourceLocation(),
3776 diag::err_multiple_base_initialization)
3777 << QualType(BaseClass, 0)
3778 << Init->getSourceRange();
3779 }
3780 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3781 << 0 << PrevInit->getSourceRange();
3782
3783 return true;
3784}
3785
Sean Huntcbb67482011-01-08 20:30:50 +00003786typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003787typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3788
3789bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003790 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003791 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003792 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003793 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003794 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003795
3796 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003797 if (Parent->isUnion()) {
3798 UnionEntry &En = Unions[Parent];
3799 if (En.first && En.first != Child) {
3800 S.Diag(Init->getSourceLocation(),
3801 diag::err_multiple_mem_union_initialization)
3802 << Field->getDeclName()
3803 << Init->getSourceRange();
3804 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3805 << 0 << En.second->getSourceRange();
3806 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003807 }
3808 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003809 En.first = Child;
3810 En.second = Init;
3811 }
David Blaikie6fe29652011-11-17 06:01:57 +00003812 if (!Parent->isAnonymousStructOrUnion())
3813 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003814 }
3815
3816 Child = Parent;
3817 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003818 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003819
3820 return false;
3821}
3822}
3823
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003824/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003825void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003826 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003827 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003828 bool AnyErrors) {
3829 if (!ConstructorDecl)
3830 return;
3831
3832 AdjustDeclIfTemplate(ConstructorDecl);
3833
3834 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003835 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003836
3837 if (!Constructor) {
3838 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3839 return;
3840 }
3841
John McCall3c3ccdb2010-04-10 09:28:51 +00003842 // Mapping for the duplicate initializers check.
3843 // For member initializers, this is keyed with a FieldDecl*.
3844 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003845 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003846
3847 // Mapping for the inconsistent anonymous-union initializers check.
3848 RedundantUnionMap MemberUnions;
3849
Anders Carlssonea356fb2010-04-02 05:42:15 +00003850 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003851 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003852 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003853
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003854 // Set the source order index.
3855 Init->setSourceOrder(i);
3856
Francois Pichet00eb3f92010-12-04 09:14:42 +00003857 if (Init->isAnyMemberInitializer()) {
3858 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003859 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3860 CheckRedundantUnionInit(*this, Init, MemberUnions))
3861 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003862 } else if (Init->isBaseInitializer()) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003863 const void *Key =
3864 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall3c3ccdb2010-04-10 09:28:51 +00003865 if (CheckRedundantInit(*this, Init, Members[Key]))
3866 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003867 } else {
3868 assert(Init->isDelegatingInitializer());
3869 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003870 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003871 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003872 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003873 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003874 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003875 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003876 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003877 // Return immediately as the initializer is set.
3878 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003879 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003880 }
3881
Anders Carlssonea356fb2010-04-02 05:42:15 +00003882 if (HadError)
3883 return;
3884
David Blaikie93c86172013-01-17 05:26:25 +00003885 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003886
David Blaikie93c86172013-01-17 05:26:25 +00003887 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu225e9822013-09-16 21:54:53 +00003888
Richard Trieu858d2ba2013-10-25 00:56:00 +00003889 DiagnoseUninitializedFields(*this, Constructor);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003890}
3891
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003892void
John McCallef027fe2010-03-16 21:39:52 +00003893Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3894 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003895 // Ignore dependent contexts. Also ignore unions, since their members never
3896 // have destructors implicitly called.
3897 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003898 return;
John McCall58e6f342010-03-16 05:22:47 +00003899
3900 // FIXME: all the access-control diagnostics are positioned on the
3901 // field/base declaration. That's probably good; that said, the
3902 // user might reasonably want to know why the destructor is being
3903 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003904
Anders Carlsson9f853df2009-11-17 04:44:12 +00003905 // Non-static data members.
3906 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3907 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003908 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003909 if (Field->isInvalidDecl())
3910 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003911
3912 // Don't destroy incomplete or zero-length arrays.
3913 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3914 continue;
3915
Anders Carlsson9f853df2009-11-17 04:44:12 +00003916 QualType FieldType = Context.getBaseElementType(Field->getType());
3917
3918 const RecordType* RT = FieldType->getAs<RecordType>();
3919 if (!RT)
3920 continue;
3921
3922 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003923 if (FieldClassDecl->isInvalidDecl())
3924 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003925 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003926 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003927 // The destructor for an implicit anonymous union member is never invoked.
3928 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3929 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003930
Douglas Gregordb89f282010-07-01 22:47:18 +00003931 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003932 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003933 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003934 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003935 << Field->getDeclName()
3936 << FieldType);
3937
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003938 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003939 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003940 }
3941
John McCall58e6f342010-03-16 05:22:47 +00003942 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3943
Anders Carlsson9f853df2009-11-17 04:44:12 +00003944 // Bases.
3945 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3946 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003947 // Bases are always records in a well-formed non-dependent class.
3948 const RecordType *RT = Base->getType()->getAs<RecordType>();
3949
3950 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003951 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003952 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003953
John McCall58e6f342010-03-16 05:22:47 +00003954 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003955 // If our base class is invalid, we probably can't get its dtor anyway.
3956 if (BaseClassDecl->isInvalidDecl())
3957 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003958 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003959 continue;
John McCall58e6f342010-03-16 05:22:47 +00003960
Douglas Gregordb89f282010-07-01 22:47:18 +00003961 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003962 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003963
3964 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003965 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003966 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003967 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003968 << Base->getSourceRange(),
3969 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003970
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003971 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003972 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003973 }
3974
3975 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003976 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3977 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003978
3979 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003980 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003981
3982 // Ignore direct virtual bases.
3983 if (DirectVirtualBases.count(RT))
3984 continue;
3985
John McCall58e6f342010-03-16 05:22:47 +00003986 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003987 // If our base class is invalid, we probably can't get its dtor anyway.
3988 if (BaseClassDecl->isInvalidDecl())
3989 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003990 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003991 continue;
John McCall58e6f342010-03-16 05:22:47 +00003992
Douglas Gregordb89f282010-07-01 22:47:18 +00003993 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003994 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00003995 if (CheckDestructorAccess(
3996 ClassDecl->getLocation(), Dtor,
3997 PDiag(diag::err_access_dtor_vbase)
3998 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3999 Context.getTypeDeclType(ClassDecl)) ==
4000 AR_accessible) {
4001 CheckDerivedToBaseConversion(
4002 Context.getTypeDeclType(ClassDecl), VBase->getType(),
4003 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4004 SourceRange(), DeclarationName(), 0);
4005 }
John McCall58e6f342010-03-16 05:22:47 +00004006
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004007 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004008 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004009 }
4010}
4011
John McCalld226f652010-08-21 09:40:31 +00004012void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00004013 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004014 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Mike Stump1eb44332009-09-09 15:08:12 +00004016 if (CXXConstructorDecl *Constructor
Richard Trieu858d2ba2013-10-25 00:56:00 +00004017 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
David Blaikie93c86172013-01-17 05:26:25 +00004018 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Richard Trieu858d2ba2013-10-25 00:56:00 +00004019 DiagnoseUninitializedFields(*this, Constructor);
4020 }
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004021}
4022
Mike Stump1eb44332009-09-09 15:08:12 +00004023bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00004024 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004025 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4026 unsigned DiagID;
4027 AbstractDiagSelID SelID;
4028
4029 public:
4030 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4031 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004032
4033 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman2217f852012-08-14 02:06:07 +00004034 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004035 if (SelID == -1)
4036 S.Diag(Loc, DiagID) << T;
4037 else
4038 S.Diag(Loc, DiagID) << SelID << T;
4039 }
4040 } Diagnoser(DiagID, SelID);
4041
4042 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004043}
4044
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00004045bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004046 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004047 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004048 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004049
Anders Carlsson11f21a02009-03-23 19:10:31 +00004050 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004051 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004052
Ted Kremenek6217b802009-07-29 21:53:49 +00004053 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004054 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004055 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004056 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00004057
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004058 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004059 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004060 }
Mike Stump1eb44332009-09-09 15:08:12 +00004061
Ted Kremenek6217b802009-07-29 21:53:49 +00004062 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004063 if (!RT)
4064 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004065
John McCall86ff3082010-02-04 22:26:26 +00004066 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004067
John McCall94c3b562010-08-18 09:41:07 +00004068 // We can't answer whether something is abstract until it has a
4069 // definition. If it's currently being defined, we'll walk back
4070 // over all the declarations when we have a full definition.
4071 const CXXRecordDecl *Def = RD->getDefinition();
4072 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00004073 return false;
4074
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004075 if (!RD->isAbstract())
4076 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004077
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004078 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00004079 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00004080
John McCall94c3b562010-08-18 09:41:07 +00004081 return true;
4082}
4083
4084void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4085 // Check if we've already emitted the list of pure virtual functions
4086 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004087 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00004088 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004089
Richard Smithcbc820a2013-07-22 02:56:56 +00004090 // If the diagnostic is suppressed, don't emit the notes. We're only
4091 // going to emit them once, so try to attach them to a diagnostic we're
4092 // actually going to show.
4093 if (Diags.isLastDiagnosticIgnored())
4094 return;
4095
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004096 CXXFinalOverriderMap FinalOverriders;
4097 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00004098
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004099 // Keep a set of seen pure methods so we won't diagnose the same method
4100 // more than once.
4101 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4102
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004103 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4104 MEnd = FinalOverriders.end();
4105 M != MEnd;
4106 ++M) {
4107 for (OverridingMethods::iterator SO = M->second.begin(),
4108 SOEnd = M->second.end();
4109 SO != SOEnd; ++SO) {
4110 // C++ [class.abstract]p4:
4111 // A class is abstract if it contains or inherits at least one
4112 // pure virtual function for which the final overrider is pure
4113 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00004114
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004115 //
4116 if (SO->second.size() != 1)
4117 continue;
4118
4119 if (!SO->second.front().Method->isPure())
4120 continue;
4121
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004122 if (!SeenPureMethods.insert(SO->second.front().Method))
4123 continue;
4124
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004125 Diag(SO->second.front().Method->getLocation(),
4126 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00004127 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004128 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004129 }
4130
4131 if (!PureVirtualClassDiagSet)
4132 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4133 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004134}
4135
Anders Carlsson8211eff2009-03-24 01:19:16 +00004136namespace {
John McCall94c3b562010-08-18 09:41:07 +00004137struct AbstractUsageInfo {
4138 Sema &S;
4139 CXXRecordDecl *Record;
4140 CanQualType AbstractType;
4141 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00004142
John McCall94c3b562010-08-18 09:41:07 +00004143 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4144 : S(S), Record(Record),
4145 AbstractType(S.Context.getCanonicalType(
4146 S.Context.getTypeDeclType(Record))),
4147 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00004148
John McCall94c3b562010-08-18 09:41:07 +00004149 void DiagnoseAbstractType() {
4150 if (Invalid) return;
4151 S.DiagnoseAbstractType(Record);
4152 Invalid = true;
4153 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00004154
John McCall94c3b562010-08-18 09:41:07 +00004155 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4156};
4157
4158struct CheckAbstractUsage {
4159 AbstractUsageInfo &Info;
4160 const NamedDecl *Ctx;
4161
4162 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4163 : Info(Info), Ctx(Ctx) {}
4164
4165 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4166 switch (TL.getTypeLocClass()) {
4167#define ABSTRACT_TYPELOC(CLASS, PARENT)
4168#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004169 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004170#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004171 }
John McCall94c3b562010-08-18 09:41:07 +00004172 }
Mike Stump1eb44332009-09-09 15:08:12 +00004173
John McCall94c3b562010-08-18 09:41:07 +00004174 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4175 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4176 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00004177 if (!TL.getArg(I))
4178 continue;
4179
John McCall94c3b562010-08-18 09:41:07 +00004180 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4181 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004182 }
John McCall94c3b562010-08-18 09:41:07 +00004183 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004184
John McCall94c3b562010-08-18 09:41:07 +00004185 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4186 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4187 }
Mike Stump1eb44332009-09-09 15:08:12 +00004188
John McCall94c3b562010-08-18 09:41:07 +00004189 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4190 // Visit the type parameters from a permissive context.
4191 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4192 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4193 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4194 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4195 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4196 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004197 }
John McCall94c3b562010-08-18 09:41:07 +00004198 }
Mike Stump1eb44332009-09-09 15:08:12 +00004199
John McCall94c3b562010-08-18 09:41:07 +00004200 // Visit pointee types from a permissive context.
4201#define CheckPolymorphic(Type) \
4202 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4203 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4204 }
4205 CheckPolymorphic(PointerTypeLoc)
4206 CheckPolymorphic(ReferenceTypeLoc)
4207 CheckPolymorphic(MemberPointerTypeLoc)
4208 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004209 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004210
John McCall94c3b562010-08-18 09:41:07 +00004211 /// Handle all the types we haven't given a more specific
4212 /// implementation for above.
4213 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4214 // Every other kind of type that we haven't called out already
4215 // that has an inner type is either (1) sugar or (2) contains that
4216 // inner type in some way as a subobject.
4217 if (TypeLoc Next = TL.getNextTypeLoc())
4218 return Visit(Next, Sel);
4219
4220 // If there's no inner type and we're in a permissive context,
4221 // don't diagnose.
4222 if (Sel == Sema::AbstractNone) return;
4223
4224 // Check whether the type matches the abstract type.
4225 QualType T = TL.getType();
4226 if (T->isArrayType()) {
4227 Sel = Sema::AbstractArrayType;
4228 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004229 }
John McCall94c3b562010-08-18 09:41:07 +00004230 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4231 if (CT != Info.AbstractType) return;
4232
4233 // It matched; do some magic.
4234 if (Sel == Sema::AbstractArrayType) {
4235 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4236 << T << TL.getSourceRange();
4237 } else {
4238 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4239 << Sel << T << TL.getSourceRange();
4240 }
4241 Info.DiagnoseAbstractType();
4242 }
4243};
4244
4245void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4246 Sema::AbstractDiagSelID Sel) {
4247 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4248}
4249
4250}
4251
4252/// Check for invalid uses of an abstract type in a method declaration.
4253static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4254 CXXMethodDecl *MD) {
4255 // No need to do the check on definitions, which require that
4256 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004257 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004258 return;
4259
4260 // For safety's sake, just ignore it if we don't have type source
4261 // information. This should never happen for non-implicit methods,
4262 // but...
4263 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4264 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4265}
4266
4267/// Check for invalid uses of an abstract type within a class definition.
4268static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4269 CXXRecordDecl *RD) {
4270 for (CXXRecordDecl::decl_iterator
4271 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4272 Decl *D = *I;
4273 if (D->isImplicit()) continue;
4274
4275 // Methods and method templates.
4276 if (isa<CXXMethodDecl>(D)) {
4277 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4278 } else if (isa<FunctionTemplateDecl>(D)) {
4279 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4280 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4281
4282 // Fields and static variables.
4283 } else if (isa<FieldDecl>(D)) {
4284 FieldDecl *FD = cast<FieldDecl>(D);
4285 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4286 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4287 } else if (isa<VarDecl>(D)) {
4288 VarDecl *VD = cast<VarDecl>(D);
4289 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4290 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4291
4292 // Nested classes and class templates.
4293 } else if (isa<CXXRecordDecl>(D)) {
4294 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4295 } else if (isa<ClassTemplateDecl>(D)) {
4296 CheckAbstractClassUsage(Info,
4297 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4298 }
4299 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004300}
4301
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004302/// \brief Perform semantic checks on a class definition that has been
4303/// completing, introducing implicitly-declared members, checking for
4304/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004305void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004306 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004307 return;
4308
John McCall94c3b562010-08-18 09:41:07 +00004309 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4310 AbstractUsageInfo Info(*this, Record);
4311 CheckAbstractClassUsage(Info, Record);
4312 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004313
4314 // If this is not an aggregate type and has no user-declared constructor,
4315 // complain about any non-static data members of reference or const scalar
4316 // type, since they will never get initializers.
4317 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004318 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4319 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004320 bool Complained = false;
4321 for (RecordDecl::field_iterator F = Record->field_begin(),
4322 FEnd = Record->field_end();
4323 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004324 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004325 continue;
4326
Douglas Gregor325e5932010-04-15 00:00:53 +00004327 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004328 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004329 if (!Complained) {
4330 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4331 << Record->getTagKind() << Record;
4332 Complained = true;
4333 }
4334
4335 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4336 << F->getType()->isReferenceType()
4337 << F->getDeclName();
4338 }
4339 }
4340 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004341
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004342 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004343 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004344
4345 if (Record->getIdentifier()) {
4346 // C++ [class.mem]p13:
4347 // If T is the name of a class, then each of the following shall have a
4348 // name different from T:
4349 // - every member of every anonymous union that is a member of class T.
4350 //
4351 // C++ [class.mem]p14:
4352 // In addition, if class T has a user-declared constructor (12.1), every
4353 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004354 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4355 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4356 ++I) {
4357 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004358 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4359 isa<IndirectFieldDecl>(D)) {
4360 Diag(D->getLocation(), diag::err_member_name_of_class)
4361 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004362 break;
4363 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004364 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004365 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004366
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004367 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004368 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004369 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004370 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004371 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4372 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4373 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004374
David Majnemer7121bdb2013-10-18 00:33:31 +00004375 if (Record->isAbstract()) {
4376 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4377 Diag(Record->getLocation(), diag::warn_abstract_final_class)
4378 << FA->isSpelledAsSealed();
4379 DiagnoseAbstractType(Record);
4380 }
David Blaikieb6b5b972012-09-21 03:21:07 +00004381 }
4382
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004383 if (!Record->isDependentType()) {
4384 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4385 MEnd = Record->method_end();
4386 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004387 // See if a method overloads virtual methods in a base
4388 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004389 if (!M->isStatic())
Eli Friedmandae92712013-09-05 23:51:03 +00004390 DiagnoseHiddenVirtualMethods(*M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004391
4392 // Check whether the explicitly-defaulted special members are valid.
4393 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4394 CheckExplicitlyDefaultedSpecialMember(*M);
4395
4396 // For an explicitly defaulted or deleted special member, we defer
4397 // determining triviality until the class is complete. That time is now!
4398 if (!M->isImplicit() && !M->isUserProvided()) {
4399 CXXSpecialMember CSM = getSpecialMember(*M);
4400 if (CSM != CXXInvalid) {
4401 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4402
4403 // Inform the class that we've finished declaring this member.
4404 Record->finishedDefaultedOrDeletedMember(*M);
4405 }
4406 }
4407 }
4408 }
4409
4410 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4411 // function that is not a constructor declares that member function to be
4412 // const. [...] The class of which that function is a member shall be
4413 // a literal type.
4414 //
4415 // If the class has virtual bases, any constexpr members will already have
4416 // been diagnosed by the checks performed on the member declaration, so
4417 // suppress this (less useful) diagnostic.
4418 //
4419 // We delay this until we know whether an explicitly-defaulted (or deleted)
4420 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004421 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004422 !Record->isLiteral() && !Record->getNumVBases()) {
4423 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4424 MEnd = Record->method_end();
4425 M != MEnd; ++M) {
4426 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4427 switch (Record->getTemplateSpecializationKind()) {
4428 case TSK_ImplicitInstantiation:
4429 case TSK_ExplicitInstantiationDeclaration:
4430 case TSK_ExplicitInstantiationDefinition:
4431 // If a template instantiates to a non-literal type, but its members
4432 // instantiate to constexpr functions, the template is technically
4433 // ill-formed, but we allow it for sanity.
4434 continue;
4435
4436 case TSK_Undeclared:
4437 case TSK_ExplicitSpecialization:
4438 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4439 diag::err_constexpr_method_non_literal);
4440 break;
4441 }
4442
4443 // Only produce one error per class.
4444 break;
4445 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004446 }
4447 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004448
Warren Huntb2969b12013-10-11 20:19:00 +00004449 // Check to see if we're trying to lay out a struct using the ms_struct
4450 // attribute that is dynamic.
4451 if (Record->isMsStruct(Context) && Record->isDynamicClass()) {
4452 Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed);
4453 Record->dropAttr<MsStructAttr>();
4454 }
4455
Richard Smith07b0fdc2013-03-18 21:12:30 +00004456 // Declare inheriting constructors. We do this eagerly here because:
4457 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004458 // constructors from different classes.
4459 // - The lazy declaration of the other implicit constructors is so as to not
4460 // waste space and performance on classes that are not meant to be
4461 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004462 // have inheriting constructors.
4463 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004464}
4465
Richard Smith7756afa2012-06-10 05:43:50 +00004466/// Is the special member function which would be selected to perform the
4467/// specified operation on the specified class type a constexpr constructor?
4468static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4469 Sema::CXXSpecialMember CSM,
4470 bool ConstArg) {
4471 Sema::SpecialMemberOverloadResult *SMOR =
4472 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4473 false, false, false, false);
4474 if (!SMOR || !SMOR->getMethod())
4475 // A constructor we wouldn't select can't be "involved in initializing"
4476 // anything.
4477 return true;
4478 return SMOR->getMethod()->isConstexpr();
4479}
4480
4481/// Determine whether the specified special member function would be constexpr
4482/// if it were implicitly defined.
4483static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4484 Sema::CXXSpecialMember CSM,
4485 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004486 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004487 return false;
4488
4489 // C++11 [dcl.constexpr]p4:
4490 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004491 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004492 switch (CSM) {
4493 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004494 // Since default constructor lookup is essentially trivial (and cannot
4495 // involve, for instance, template instantiation), we compute whether a
4496 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4497 //
4498 // This is important for performance; we need to know whether the default
4499 // constructor is constexpr to determine whether the type is a literal type.
4500 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4501
Richard Smith7756afa2012-06-10 05:43:50 +00004502 case Sema::CXXCopyConstructor:
4503 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004504 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004505 break;
4506
4507 case Sema::CXXCopyAssignment:
4508 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004509 if (!S.getLangOpts().CPlusPlus1y)
4510 return false;
4511 // In C++1y, we need to perform overload resolution.
4512 Ctor = false;
4513 break;
4514
Richard Smith7756afa2012-06-10 05:43:50 +00004515 case Sema::CXXDestructor:
4516 case Sema::CXXInvalid:
4517 return false;
4518 }
4519
4520 // -- if the class is a non-empty union, or for each non-empty anonymous
4521 // union member of a non-union class, exactly one non-static data member
4522 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004523 //
4524 // If we squint, this is guaranteed, since exactly one non-static data member
4525 // will be initialized (if the constructor isn't deleted), we just don't know
4526 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004527 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004528 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004529
4530 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004531 if (Ctor && ClassDecl->getNumVBases())
4532 return false;
4533
4534 // C++1y [class.copy]p26:
4535 // -- [the class] is a literal type, and
4536 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004537 return false;
4538
4539 // -- every constructor involved in initializing [...] base class
4540 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004541 // -- the assignment operator selected to copy/move each direct base
4542 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004543 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4544 BEnd = ClassDecl->bases_end();
4545 B != BEnd; ++B) {
4546 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4547 if (!BaseType) continue;
4548
4549 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4550 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4551 return false;
4552 }
4553
4554 // -- every constructor involved in initializing non-static data members
4555 // [...] shall be a constexpr constructor;
4556 // -- every non-static data member and base class sub-object shall be
4557 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004558 // -- for each non-stastic data member of X that is of class type (or array
4559 // thereof), the assignment operator selected to copy/move that member is
4560 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004561 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4562 FEnd = ClassDecl->field_end();
4563 F != FEnd; ++F) {
4564 if (F->isInvalidDecl())
4565 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004566 if (const RecordType *RecordTy =
4567 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004568 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4569 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4570 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004571 }
4572 }
4573
4574 // All OK, it's constexpr!
4575 return true;
4576}
4577
Richard Smithb9d0b762012-07-27 04:22:15 +00004578static Sema::ImplicitExceptionSpecification
4579computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4580 switch (S.getSpecialMember(MD)) {
4581 case Sema::CXXDefaultConstructor:
4582 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4583 case Sema::CXXCopyConstructor:
4584 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4585 case Sema::CXXCopyAssignment:
4586 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4587 case Sema::CXXMoveConstructor:
4588 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4589 case Sema::CXXMoveAssignment:
4590 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4591 case Sema::CXXDestructor:
4592 return S.ComputeDefaultedDtorExceptionSpec(MD);
4593 case Sema::CXXInvalid:
4594 break;
4595 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004596 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4597 "only special members have implicit exception specs");
4598 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004599}
4600
Richard Smithdd25e802012-07-30 23:48:14 +00004601static void
4602updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4603 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4604 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4605 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004606 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4607 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004608}
4609
Reid Kleckneref072032013-08-27 23:08:25 +00004610static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4611 CXXMethodDecl *MD) {
4612 FunctionProtoType::ExtProtoInfo EPI;
4613
4614 // Build an exception specification pointing back at this member.
4615 EPI.ExceptionSpecType = EST_Unevaluated;
4616 EPI.ExceptionSpecDecl = MD;
4617
4618 // Set the calling convention to the default for C++ instance methods.
4619 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4620 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4621 /*IsCXXMethod=*/true));
4622 return EPI;
4623}
4624
Richard Smithb9d0b762012-07-27 04:22:15 +00004625void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4626 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4627 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4628 return;
4629
Richard Smithdd25e802012-07-30 23:48:14 +00004630 // Evaluate the exception specification.
4631 ImplicitExceptionSpecification ExceptSpec =
4632 computeImplicitExceptionSpec(*this, Loc, MD);
4633
4634 // Update the type of the special member to use it.
4635 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4636
4637 // A user-provided destructor can be defined outside the class. When that
4638 // happens, be sure to update the exception specification on both
4639 // declarations.
4640 const FunctionProtoType *CanonicalFPT =
4641 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4642 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4643 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4644 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004645}
4646
Richard Smith3003e1d2012-05-15 04:39:51 +00004647void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4648 CXXRecordDecl *RD = MD->getParent();
4649 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004650
Richard Smith3003e1d2012-05-15 04:39:51 +00004651 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4652 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004653
4654 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004655 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004656 bool First = MD == MD->getCanonicalDecl();
4657
4658 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004659
4660 // C++11 [dcl.fct.def.default]p1:
4661 // A function that is explicitly defaulted shall
4662 // -- be a special member function (checked elsewhere),
4663 // -- have the same type (except for ref-qualifiers, and except that a
4664 // copy operation can take a non-const reference) as an implicit
4665 // declaration, and
4666 // -- not have default arguments.
4667 unsigned ExpectedParams = 1;
4668 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4669 ExpectedParams = 0;
4670 if (MD->getNumParams() != ExpectedParams) {
4671 // This also checks for default arguments: a copy or move constructor with a
4672 // default argument is classified as a default constructor, and assignment
4673 // operations and destructors can't have default arguments.
4674 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4675 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004676 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004677 } else if (MD->isVariadic()) {
4678 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4679 << CSM << MD->getSourceRange();
4680 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004681 }
4682
Richard Smith3003e1d2012-05-15 04:39:51 +00004683 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004684
Richard Smith7756afa2012-06-10 05:43:50 +00004685 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004686 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004687 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004688 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004689 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004690
Richard Smith3003e1d2012-05-15 04:39:51 +00004691 QualType ReturnType = Context.VoidTy;
4692 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4693 // Check for return type matching.
4694 ReturnType = Type->getResultType();
4695 QualType ExpectedReturnType =
4696 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4697 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4698 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4699 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4700 HadError = true;
4701 }
4702
4703 // A defaulted special member cannot have cv-qualifiers.
4704 if (Type->getTypeQuals()) {
4705 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004706 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004707 HadError = true;
4708 }
4709 }
4710
4711 // Check for parameter type matching.
4712 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004713 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004714 if (ExpectedParams && ArgType->isReferenceType()) {
4715 // Argument must be reference to possibly-const T.
4716 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004717 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004718
4719 if (ReferentType.isVolatileQualified()) {
4720 Diag(MD->getLocation(),
4721 diag::err_defaulted_special_member_volatile_param) << CSM;
4722 HadError = true;
4723 }
4724
Richard Smith7756afa2012-06-10 05:43:50 +00004725 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004726 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4727 Diag(MD->getLocation(),
4728 diag::err_defaulted_special_member_copy_const_param)
4729 << (CSM == CXXCopyAssignment);
4730 // FIXME: Explain why this special member can't be const.
4731 } else {
4732 Diag(MD->getLocation(),
4733 diag::err_defaulted_special_member_move_const_param)
4734 << (CSM == CXXMoveAssignment);
4735 }
4736 HadError = true;
4737 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004738 } else if (ExpectedParams) {
4739 // A copy assignment operator can take its argument by value, but a
4740 // defaulted one cannot.
4741 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004742 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004743 HadError = true;
4744 }
Sean Huntbe631222011-05-17 20:44:43 +00004745
Richard Smith61802452011-12-22 02:22:31 +00004746 // C++11 [dcl.fct.def.default]p2:
4747 // An explicitly-defaulted function may be declared constexpr only if it
4748 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004749 // Do not apply this rule to members of class templates, since core issue 1358
4750 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004751 // functions which cannot be constexpr (for non-constructors in C++11 and for
4752 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004753 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4754 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004755 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4756 : isa<CXXConstructorDecl>(MD)) &&
4757 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004758 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4759 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004760 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004761 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004762 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004763
Richard Smith61802452011-12-22 02:22:31 +00004764 // and may have an explicit exception-specification only if it is compatible
4765 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004766 if (Type->hasExceptionSpec()) {
4767 // Delay the check if this is the first declaration of the special member,
4768 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004769 if (First) {
4770 // If the exception specification needs to be instantiated, do so now,
4771 // before we clobber it with an EST_Unevaluated specification below.
4772 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4773 InstantiateExceptionSpec(MD->getLocStart(), MD);
4774 Type = MD->getType()->getAs<FunctionProtoType>();
4775 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004776 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004777 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004778 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4779 }
Richard Smith61802452011-12-22 02:22:31 +00004780
4781 // If a function is explicitly defaulted on its first declaration,
4782 if (First) {
4783 // -- it is implicitly considered to be constexpr if the implicit
4784 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004785 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004786
Richard Smith3003e1d2012-05-15 04:39:51 +00004787 // -- it is implicitly considered to have the same exception-specification
4788 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004789 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4790 EPI.ExceptionSpecType = EST_Unevaluated;
4791 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004792 MD->setType(Context.getFunctionType(ReturnType,
4793 ArrayRef<QualType>(&ArgType,
4794 ExpectedParams),
4795 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004796 }
4797
Richard Smith3003e1d2012-05-15 04:39:51 +00004798 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004799 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004800 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004801 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004802 // C++11 [dcl.fct.def.default]p4:
4803 // [For a] user-provided explicitly-defaulted function [...] if such a
4804 // function is implicitly defined as deleted, the program is ill-formed.
4805 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4806 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004807 }
4808 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004809
Richard Smith3003e1d2012-05-15 04:39:51 +00004810 if (HadError)
4811 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004812}
4813
Richard Smith1d28caf2012-12-11 01:14:52 +00004814/// Check whether the exception specification provided for an
4815/// explicitly-defaulted special member matches the exception specification
4816/// that would have been generated for an implicit special member, per
4817/// C++11 [dcl.fct.def.default]p2.
4818void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4819 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4820 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00004821 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4822 /*IsCXXMethod=*/true);
4823 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith1d28caf2012-12-11 01:14:52 +00004824 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4825 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004826 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004827
4828 // Ensure that it matches.
4829 CheckEquivalentExceptionSpec(
4830 PDiag(diag::err_incorrect_defaulted_exception_spec)
4831 << getSpecialMember(MD), PDiag(),
4832 ImplicitType, SourceLocation(),
4833 SpecifiedType, MD->getLocation());
4834}
4835
Alp Toker08235662013-10-18 05:54:19 +00004836void Sema::CheckDelayedMemberExceptionSpecs() {
4837 SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4838 2> Checks;
4839 SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
Richard Smith1d28caf2012-12-11 01:14:52 +00004840
Alp Toker08235662013-10-18 05:54:19 +00004841 std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4842 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4843
4844 // Perform any deferred checking of exception specifications for virtual
4845 // destructors.
4846 for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4847 const CXXDestructorDecl *Dtor = Checks[i].first;
4848 assert(!Dtor->getParent()->isDependentType() &&
4849 "Should not ever add destructors of templates into the list.");
4850 CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4851 }
4852
4853 // Check that any explicitly-defaulted methods have exception specifications
4854 // compatible with their implicit exception specifications.
4855 for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4856 CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4857 Specs[I].second);
Richard Smith1d28caf2012-12-11 01:14:52 +00004858}
4859
Richard Smith7d5088a2012-02-18 02:02:13 +00004860namespace {
4861struct SpecialMemberDeletionInfo {
4862 Sema &S;
4863 CXXMethodDecl *MD;
4864 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004865 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004866
4867 // Properties of the special member, computed for convenience.
4868 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4869 SourceLocation Loc;
4870
4871 bool AllFieldsAreConst;
4872
4873 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004874 Sema::CXXSpecialMember CSM, bool Diagnose)
4875 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004876 IsConstructor(false), IsAssignment(false), IsMove(false),
4877 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4878 AllFieldsAreConst(true) {
4879 switch (CSM) {
4880 case Sema::CXXDefaultConstructor:
4881 case Sema::CXXCopyConstructor:
4882 IsConstructor = true;
4883 break;
4884 case Sema::CXXMoveConstructor:
4885 IsConstructor = true;
4886 IsMove = true;
4887 break;
4888 case Sema::CXXCopyAssignment:
4889 IsAssignment = true;
4890 break;
4891 case Sema::CXXMoveAssignment:
4892 IsAssignment = true;
4893 IsMove = true;
4894 break;
4895 case Sema::CXXDestructor:
4896 break;
4897 case Sema::CXXInvalid:
4898 llvm_unreachable("invalid special member kind");
4899 }
4900
4901 if (MD->getNumParams()) {
4902 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4903 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4904 }
4905 }
4906
4907 bool inUnion() const { return MD->getParent()->isUnion(); }
4908
4909 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004910 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4911 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004912 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004913 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4914 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4915 Quals = 0;
4916 return S.LookupSpecialMember(Class, CSM,
4917 ConstArg || (Quals & Qualifiers::Const),
4918 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004919 MD->getRefQualifier() == RQ_RValue,
4920 TQ & Qualifiers::Const,
4921 TQ & Qualifiers::Volatile);
4922 }
4923
Richard Smith6c4c36c2012-03-30 20:53:28 +00004924 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004925
Richard Smith6c4c36c2012-03-30 20:53:28 +00004926 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004927 bool shouldDeleteForField(FieldDecl *FD);
4928 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004929
Richard Smith517bb842012-07-18 03:51:16 +00004930 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4931 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004932 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4933 Sema::SpecialMemberOverloadResult *SMOR,
4934 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004935
4936 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004937};
4938}
4939
John McCall12d8d802012-04-09 20:53:23 +00004940/// Is the given special member inaccessible when used on the given
4941/// sub-object.
4942bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4943 CXXMethodDecl *target) {
4944 /// If we're operating on a base class, the object type is the
4945 /// type of this special member.
4946 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004947 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004948 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4949 objectTy = S.Context.getTypeDeclType(MD->getParent());
4950 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4951
4952 // If we're operating on a field, the object type is the type of the field.
4953 } else {
4954 objectTy = S.Context.getTypeDeclType(target->getParent());
4955 }
4956
4957 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4958}
4959
Richard Smith6c4c36c2012-03-30 20:53:28 +00004960/// Check whether we should delete a special member due to the implicit
4961/// definition containing a call to a special member of a subobject.
4962bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4963 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4964 bool IsDtorCallInCtor) {
4965 CXXMethodDecl *Decl = SMOR->getMethod();
4966 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4967
4968 int DiagKind = -1;
4969
4970 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4971 DiagKind = !Decl ? 0 : 1;
4972 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4973 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004974 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004975 DiagKind = 3;
4976 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4977 !Decl->isTrivial()) {
4978 // A member of a union must have a trivial corresponding special member.
4979 // As a weird special case, a destructor call from a union's constructor
4980 // must be accessible and non-deleted, but need not be trivial. Such a
4981 // destructor is never actually called, but is semantically checked as
4982 // if it were.
4983 DiagKind = 4;
4984 }
4985
4986 if (DiagKind == -1)
4987 return false;
4988
4989 if (Diagnose) {
4990 if (Field) {
4991 S.Diag(Field->getLocation(),
4992 diag::note_deleted_special_member_class_subobject)
4993 << CSM << MD->getParent() << /*IsField*/true
4994 << Field << DiagKind << IsDtorCallInCtor;
4995 } else {
4996 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4997 S.Diag(Base->getLocStart(),
4998 diag::note_deleted_special_member_class_subobject)
4999 << CSM << MD->getParent() << /*IsField*/false
5000 << Base->getType() << DiagKind << IsDtorCallInCtor;
5001 }
5002
5003 if (DiagKind == 1)
5004 S.NoteDeletedFunction(Decl);
5005 // FIXME: Explain inaccessibility if DiagKind == 3.
5006 }
5007
5008 return true;
5009}
5010
Richard Smith9a561d52012-02-26 09:11:52 +00005011/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00005012/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00005013bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00005014 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005015 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00005016
5017 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00005018 // -- any direct or virtual base class, or non-static data member with no
5019 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00005020 // either M has no default constructor or overload resolution as applied
5021 // to M's default constructor results in an ambiguity or in a function
5022 // that is deleted or inaccessible
5023 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5024 // -- a direct or virtual base class B that cannot be copied/moved because
5025 // overload resolution, as applied to B's corresponding special member,
5026 // results in an ambiguity or a function that is deleted or inaccessible
5027 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00005028 // C++11 [class.dtor]p5:
5029 // -- any direct or virtual base class [...] has a type with a destructor
5030 // that is deleted or inaccessible
5031 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00005032 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00005033 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00005034 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005035
Richard Smith6c4c36c2012-03-30 20:53:28 +00005036 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5037 // -- any direct or virtual base class or non-static data member has a
5038 // type with a destructor that is deleted or inaccessible
5039 if (IsConstructor) {
5040 Sema::SpecialMemberOverloadResult *SMOR =
5041 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5042 false, false, false, false, false);
5043 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5044 return true;
5045 }
5046
Richard Smith9a561d52012-02-26 09:11:52 +00005047 return false;
5048}
5049
5050/// Check whether we should delete a special member function due to the class
5051/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005052bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00005053 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00005054 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00005055}
5056
5057/// Check whether we should delete a special member function due to the class
5058/// having a particular non-static data member.
5059bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5060 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5061 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5062
5063 if (CSM == Sema::CXXDefaultConstructor) {
5064 // For a default constructor, all references must be initialized in-class
5065 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005066 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5067 if (Diagnose)
5068 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5069 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005070 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005071 }
Richard Smith79363f52012-02-27 06:07:25 +00005072 // C++11 [class.ctor]p5: any non-variant non-static data member of
5073 // const-qualified type (or array thereof) with no
5074 // brace-or-equal-initializer does not have a user-provided default
5075 // constructor.
5076 if (!inUnion() && FieldType.isConstQualified() &&
5077 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005078 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5079 if (Diagnose)
5080 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005081 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00005082 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005083 }
5084
5085 if (inUnion() && !FieldType.isConstQualified())
5086 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005087 } else if (CSM == Sema::CXXCopyConstructor) {
5088 // For a copy constructor, data members must not be of rvalue reference
5089 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005090 if (FieldType->isRValueReferenceType()) {
5091 if (Diagnose)
5092 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5093 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00005094 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005095 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005096 } else if (IsAssignment) {
5097 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005098 if (FieldType->isReferenceType()) {
5099 if (Diagnose)
5100 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5101 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005102 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005103 }
5104 if (!FieldRecord && FieldType.isConstQualified()) {
5105 // C++11 [class.copy]p23:
5106 // -- a non-static data member of const non-class type (or array thereof)
5107 if (Diagnose)
5108 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005109 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005110 return true;
5111 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005112 }
5113
5114 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005115 // Some additional restrictions exist on the variant members.
5116 if (!inUnion() && FieldRecord->isUnion() &&
5117 FieldRecord->isAnonymousStructOrUnion()) {
5118 bool AllVariantFieldsAreConst = true;
5119
Richard Smithdf8dc862012-03-29 19:00:10 +00005120 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00005121 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5122 UE = FieldRecord->field_end();
5123 UI != UE; ++UI) {
5124 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00005125
5126 if (!UnionFieldType.isConstQualified())
5127 AllVariantFieldsAreConst = false;
5128
Richard Smith9a561d52012-02-26 09:11:52 +00005129 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5130 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00005131 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5132 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00005133 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005134 }
5135
5136 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00005137 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005138 FieldRecord->field_begin() != FieldRecord->field_end()) {
5139 if (Diagnose)
5140 S.Diag(FieldRecord->getLocation(),
5141 diag::note_deleted_default_ctor_all_const)
5142 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00005143 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005144 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005145
Richard Smithdf8dc862012-03-29 19:00:10 +00005146 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00005147 // This is technically non-conformant, but sanity demands it.
5148 return false;
5149 }
5150
Richard Smith517bb842012-07-18 03:51:16 +00005151 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5152 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00005153 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005154 }
5155
5156 return false;
5157}
5158
5159/// C++11 [class.ctor] p5:
5160/// A defaulted default constructor for a class X is defined as deleted if
5161/// X is a union and all of its variant members are of const-qualified type.
5162bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00005163 // This is a silly definition, because it gives an empty union a deleted
5164 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005165 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5166 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5167 if (Diagnose)
5168 S.Diag(MD->getParent()->getLocation(),
5169 diag::note_deleted_default_ctor_all_const)
5170 << MD->getParent() << /*not anonymous union*/0;
5171 return true;
5172 }
5173 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005174}
5175
5176/// Determine whether a defaulted special member function should be defined as
5177/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5178/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005179bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5180 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00005181 if (MD->isInvalidDecl())
5182 return false;
Sean Hunte16da072011-10-10 06:18:57 +00005183 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00005184 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00005185 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005186 return false;
5187
Richard Smith7d5088a2012-02-18 02:02:13 +00005188 // C++11 [expr.lambda.prim]p19:
5189 // The closure type associated with a lambda-expression has a
5190 // deleted (8.4.3) default constructor and a deleted copy
5191 // assignment operator.
5192 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005193 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5194 if (Diagnose)
5195 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005196 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005197 }
5198
Richard Smith5bdaac52012-04-02 20:59:25 +00005199 // For an anonymous struct or union, the copy and assignment special members
5200 // will never be used, so skip the check. For an anonymous union declared at
5201 // namespace scope, the constructor and destructor are used.
5202 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5203 RD->isAnonymousStructOrUnion())
5204 return false;
5205
Richard Smith6c4c36c2012-03-30 20:53:28 +00005206 // C++11 [class.copy]p7, p18:
5207 // If the class definition declares a move constructor or move assignment
5208 // operator, an implicitly declared copy constructor or copy assignment
5209 // operator is defined as deleted.
5210 if (MD->isImplicit() &&
5211 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5212 CXXMethodDecl *UserDeclaredMove = 0;
5213
5214 // In Microsoft mode, a user-declared move only causes the deletion of the
5215 // corresponding copy operation, not both copy operations.
5216 if (RD->hasUserDeclaredMoveConstructor() &&
5217 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5218 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005219
5220 // Find any user-declared move constructor.
5221 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5222 E = RD->ctor_end(); I != E; ++I) {
5223 if (I->isMoveConstructor()) {
5224 UserDeclaredMove = *I;
5225 break;
5226 }
5227 }
Richard Smith1c931be2012-04-02 18:40:40 +00005228 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005229 } else if (RD->hasUserDeclaredMoveAssignment() &&
5230 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5231 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005232
5233 // Find any user-declared move assignment operator.
5234 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5235 E = RD->method_end(); I != E; ++I) {
5236 if (I->isMoveAssignmentOperator()) {
5237 UserDeclaredMove = *I;
5238 break;
5239 }
5240 }
Richard Smith1c931be2012-04-02 18:40:40 +00005241 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005242 }
5243
5244 if (UserDeclaredMove) {
5245 Diag(UserDeclaredMove->getLocation(),
5246 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005247 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005248 << UserDeclaredMove->isMoveAssignmentOperator();
5249 return true;
5250 }
5251 }
Sean Hunte16da072011-10-10 06:18:57 +00005252
Richard Smith5bdaac52012-04-02 20:59:25 +00005253 // Do access control from the special member function
5254 ContextRAII MethodContext(*this, MD);
5255
Richard Smith9a561d52012-02-26 09:11:52 +00005256 // C++11 [class.dtor]p5:
5257 // -- for a virtual destructor, lookup of the non-array deallocation function
5258 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005259 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005260 FunctionDecl *OperatorDelete = 0;
5261 DeclarationName Name =
5262 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5263 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005264 OperatorDelete, false)) {
5265 if (Diagnose)
5266 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005267 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005268 }
Richard Smith9a561d52012-02-26 09:11:52 +00005269 }
5270
Richard Smith6c4c36c2012-03-30 20:53:28 +00005271 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005272
Sean Huntcdee3fe2011-05-11 22:34:38 +00005273 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005274 BE = RD->bases_end(); BI != BE; ++BI)
5275 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005276 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005277 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005278
Richard Smithe0883602013-07-22 18:06:23 +00005279 // Per DR1611, do not consider virtual bases of constructors of abstract
5280 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005281 if (!RD->isAbstract() || !SMI.IsConstructor) {
5282 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5283 BE = RD->vbases_end();
5284 BI != BE; ++BI)
5285 if (SMI.shouldDeleteForBase(BI))
5286 return true;
5287 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005288
5289 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005290 FE = RD->field_end(); FI != FE; ++FI)
5291 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005292 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005293 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005294
Richard Smith7d5088a2012-02-18 02:02:13 +00005295 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005296 return true;
5297
5298 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005299}
5300
Richard Smithac713512012-12-08 02:53:02 +00005301/// Perform lookup for a special member of the specified kind, and determine
5302/// whether it is trivial. If the triviality can be determined without the
5303/// lookup, skip it. This is intended for use when determining whether a
5304/// special member of a containing object is trivial, and thus does not ever
5305/// perform overload resolution for default constructors.
5306///
5307/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5308/// member that was most likely to be intended to be trivial, if any.
5309static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5310 Sema::CXXSpecialMember CSM, unsigned Quals,
5311 CXXMethodDecl **Selected) {
5312 if (Selected)
5313 *Selected = 0;
5314
5315 switch (CSM) {
5316 case Sema::CXXInvalid:
5317 llvm_unreachable("not a special member");
5318
5319 case Sema::CXXDefaultConstructor:
5320 // C++11 [class.ctor]p5:
5321 // A default constructor is trivial if:
5322 // - all the [direct subobjects] have trivial default constructors
5323 //
5324 // Note, no overload resolution is performed in this case.
5325 if (RD->hasTrivialDefaultConstructor())
5326 return true;
5327
5328 if (Selected) {
5329 // If there's a default constructor which could have been trivial, dig it
5330 // out. Otherwise, if there's any user-provided default constructor, point
5331 // to that as an example of why there's not a trivial one.
5332 CXXConstructorDecl *DefCtor = 0;
5333 if (RD->needsImplicitDefaultConstructor())
5334 S.DeclareImplicitDefaultConstructor(RD);
5335 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5336 CE = RD->ctor_end(); CI != CE; ++CI) {
5337 if (!CI->isDefaultConstructor())
5338 continue;
5339 DefCtor = *CI;
5340 if (!DefCtor->isUserProvided())
5341 break;
5342 }
5343
5344 *Selected = DefCtor;
5345 }
5346
5347 return false;
5348
5349 case Sema::CXXDestructor:
5350 // C++11 [class.dtor]p5:
5351 // A destructor is trivial if:
5352 // - all the direct [subobjects] have trivial destructors
5353 if (RD->hasTrivialDestructor())
5354 return true;
5355
5356 if (Selected) {
5357 if (RD->needsImplicitDestructor())
5358 S.DeclareImplicitDestructor(RD);
5359 *Selected = RD->getDestructor();
5360 }
5361
5362 return false;
5363
5364 case Sema::CXXCopyConstructor:
5365 // C++11 [class.copy]p12:
5366 // A copy constructor is trivial if:
5367 // - the constructor selected to copy each direct [subobject] is trivial
5368 if (RD->hasTrivialCopyConstructor()) {
5369 if (Quals == Qualifiers::Const)
5370 // We must either select the trivial copy constructor or reach an
5371 // ambiguity; no need to actually perform overload resolution.
5372 return true;
5373 } else if (!Selected) {
5374 return false;
5375 }
5376 // In C++98, we are not supposed to perform overload resolution here, but we
5377 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5378 // cases like B as having a non-trivial copy constructor:
5379 // struct A { template<typename T> A(T&); };
5380 // struct B { mutable A a; };
5381 goto NeedOverloadResolution;
5382
5383 case Sema::CXXCopyAssignment:
5384 // C++11 [class.copy]p25:
5385 // A copy assignment operator is trivial if:
5386 // - the assignment operator selected to copy each direct [subobject] is
5387 // trivial
5388 if (RD->hasTrivialCopyAssignment()) {
5389 if (Quals == Qualifiers::Const)
5390 return true;
5391 } else if (!Selected) {
5392 return false;
5393 }
5394 // In C++98, we are not supposed to perform overload resolution here, but we
5395 // treat that as a language defect.
5396 goto NeedOverloadResolution;
5397
5398 case Sema::CXXMoveConstructor:
5399 case Sema::CXXMoveAssignment:
5400 NeedOverloadResolution:
5401 Sema::SpecialMemberOverloadResult *SMOR =
5402 S.LookupSpecialMember(RD, CSM,
5403 Quals & Qualifiers::Const,
5404 Quals & Qualifiers::Volatile,
5405 /*RValueThis*/false, /*ConstThis*/false,
5406 /*VolatileThis*/false);
5407
5408 // The standard doesn't describe how to behave if the lookup is ambiguous.
5409 // We treat it as not making the member non-trivial, just like the standard
5410 // mandates for the default constructor. This should rarely matter, because
5411 // the member will also be deleted.
5412 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5413 return true;
5414
5415 if (!SMOR->getMethod()) {
5416 assert(SMOR->getKind() ==
5417 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5418 return false;
5419 }
5420
5421 // We deliberately don't check if we found a deleted special member. We're
5422 // not supposed to!
5423 if (Selected)
5424 *Selected = SMOR->getMethod();
5425 return SMOR->getMethod()->isTrivial();
5426 }
5427
5428 llvm_unreachable("unknown special method kind");
5429}
5430
Benjamin Kramera574c892013-02-15 12:30:38 +00005431static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005432 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5433 CI != CE; ++CI)
5434 if (!CI->isImplicit())
5435 return *CI;
5436
5437 // Look for constructor templates.
5438 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5439 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5440 if (CXXConstructorDecl *CD =
5441 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5442 return CD;
5443 }
5444
5445 return 0;
5446}
5447
5448/// The kind of subobject we are checking for triviality. The values of this
5449/// enumeration are used in diagnostics.
5450enum TrivialSubobjectKind {
5451 /// The subobject is a base class.
5452 TSK_BaseClass,
5453 /// The subobject is a non-static data member.
5454 TSK_Field,
5455 /// The object is actually the complete object.
5456 TSK_CompleteObject
5457};
5458
5459/// Check whether the special member selected for a given type would be trivial.
5460static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5461 QualType SubType,
5462 Sema::CXXSpecialMember CSM,
5463 TrivialSubobjectKind Kind,
5464 bool Diagnose) {
5465 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5466 if (!SubRD)
5467 return true;
5468
5469 CXXMethodDecl *Selected;
5470 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5471 Diagnose ? &Selected : 0))
5472 return true;
5473
5474 if (Diagnose) {
5475 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5476 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5477 << Kind << SubType.getUnqualifiedType();
5478 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5479 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5480 } else if (!Selected)
5481 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5482 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5483 else if (Selected->isUserProvided()) {
5484 if (Kind == TSK_CompleteObject)
5485 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5486 << Kind << SubType.getUnqualifiedType() << CSM;
5487 else {
5488 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5489 << Kind << SubType.getUnqualifiedType() << CSM;
5490 S.Diag(Selected->getLocation(), diag::note_declared_at);
5491 }
5492 } else {
5493 if (Kind != TSK_CompleteObject)
5494 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5495 << Kind << SubType.getUnqualifiedType() << CSM;
5496
5497 // Explain why the defaulted or deleted special member isn't trivial.
5498 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5499 }
5500 }
5501
5502 return false;
5503}
5504
5505/// Check whether the members of a class type allow a special member to be
5506/// trivial.
5507static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5508 Sema::CXXSpecialMember CSM,
5509 bool ConstArg, bool Diagnose) {
5510 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5511 FE = RD->field_end(); FI != FE; ++FI) {
5512 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5513 continue;
5514
5515 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5516
5517 // Pretend anonymous struct or union members are members of this class.
5518 if (FI->isAnonymousStructOrUnion()) {
5519 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5520 CSM, ConstArg, Diagnose))
5521 return false;
5522 continue;
5523 }
5524
5525 // C++11 [class.ctor]p5:
5526 // A default constructor is trivial if [...]
5527 // -- no non-static data member of its class has a
5528 // brace-or-equal-initializer
5529 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5530 if (Diagnose)
5531 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5532 return false;
5533 }
5534
5535 // Objective C ARC 4.3.5:
5536 // [...] nontrivally ownership-qualified types are [...] not trivially
5537 // default constructible, copy constructible, move constructible, copy
5538 // assignable, move assignable, or destructible [...]
5539 if (S.getLangOpts().ObjCAutoRefCount &&
5540 FieldType.hasNonTrivialObjCLifetime()) {
5541 if (Diagnose)
5542 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5543 << RD << FieldType.getObjCLifetime();
5544 return false;
5545 }
5546
5547 if (ConstArg && !FI->isMutable())
5548 FieldType.addConst();
5549 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5550 TSK_Field, Diagnose))
5551 return false;
5552 }
5553
5554 return true;
5555}
5556
5557/// Diagnose why the specified class does not have a trivial special member of
5558/// the given kind.
5559void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5560 QualType Ty = Context.getRecordType(RD);
5561 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5562 Ty.addConst();
5563
5564 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5565 TSK_CompleteObject, /*Diagnose*/true);
5566}
5567
5568/// Determine whether a defaulted or deleted special member function is trivial,
5569/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5570/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5571bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5572 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005573 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5574
5575 CXXRecordDecl *RD = MD->getParent();
5576
5577 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005578
Richard Smitha8d478e2013-11-04 02:02:27 +00005579 // C++11 [class.copy]p12, p25: [DR1593]
5580 // A [special member] is trivial if [...] its parameter-type-list is
5581 // equivalent to the parameter-type-list of an implicit declaration [...]
Richard Smithac713512012-12-08 02:53:02 +00005582 switch (CSM) {
5583 case CXXDefaultConstructor:
5584 case CXXDestructor:
5585 // Trivial default constructors and destructors cannot have parameters.
5586 break;
5587
5588 case CXXCopyConstructor:
5589 case CXXCopyAssignment: {
5590 // Trivial copy operations always have const, non-volatile parameter types.
5591 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005592 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005593 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5594 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5595 if (Diagnose)
5596 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5597 << Param0->getSourceRange() << Param0->getType()
5598 << Context.getLValueReferenceType(
5599 Context.getRecordType(RD).withConst());
5600 return false;
5601 }
5602 break;
5603 }
5604
5605 case CXXMoveConstructor:
5606 case CXXMoveAssignment: {
5607 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005608 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005609 const RValueReferenceType *RT =
5610 Param0->getType()->getAs<RValueReferenceType>();
5611 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5612 if (Diagnose)
5613 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5614 << Param0->getSourceRange() << Param0->getType()
5615 << Context.getRValueReferenceType(Context.getRecordType(RD));
5616 return false;
5617 }
5618 break;
5619 }
5620
5621 case CXXInvalid:
5622 llvm_unreachable("not a special member");
5623 }
5624
Richard Smithac713512012-12-08 02:53:02 +00005625 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5626 if (Diagnose)
5627 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5628 diag::note_nontrivial_default_arg)
5629 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5630 return false;
5631 }
5632 if (MD->isVariadic()) {
5633 if (Diagnose)
5634 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5635 return false;
5636 }
5637
5638 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5639 // A copy/move [constructor or assignment operator] is trivial if
5640 // -- the [member] selected to copy/move each direct base class subobject
5641 // is trivial
5642 //
5643 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5644 // A [default constructor or destructor] is trivial if
5645 // -- all the direct base classes have trivial [default constructors or
5646 // destructors]
5647 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5648 BE = RD->bases_end(); BI != BE; ++BI)
5649 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5650 ConstArg ? BI->getType().withConst()
5651 : BI->getType(),
5652 CSM, TSK_BaseClass, Diagnose))
5653 return false;
5654
5655 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5656 // A copy/move [constructor or assignment operator] for a class X is
5657 // trivial if
5658 // -- for each non-static data member of X that is of class type (or array
5659 // thereof), the constructor selected to copy/move that member is
5660 // trivial
5661 //
5662 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5663 // A [default constructor or destructor] is trivial if
5664 // -- for all of the non-static data members of its class that are of class
5665 // type (or array thereof), each such class has a trivial [default
5666 // constructor or destructor]
5667 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5668 return false;
5669
5670 // C++11 [class.dtor]p5:
5671 // A destructor is trivial if [...]
5672 // -- the destructor is not virtual
5673 if (CSM == CXXDestructor && MD->isVirtual()) {
5674 if (Diagnose)
5675 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5676 return false;
5677 }
5678
5679 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5680 // A [special member] for class X is trivial if [...]
5681 // -- class X has no virtual functions and no virtual base classes
5682 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5683 if (!Diagnose)
5684 return false;
5685
5686 if (RD->getNumVBases()) {
5687 // Check for virtual bases. We already know that the corresponding
5688 // member in all bases is trivial, so vbases must all be direct.
5689 CXXBaseSpecifier &BS = *RD->vbases_begin();
5690 assert(BS.isVirtual());
5691 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5692 return false;
5693 }
5694
5695 // Must have a virtual method.
5696 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5697 ME = RD->method_end(); MI != ME; ++MI) {
5698 if (MI->isVirtual()) {
5699 SourceLocation MLoc = MI->getLocStart();
5700 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5701 return false;
5702 }
5703 }
5704
5705 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5706 }
5707
5708 // Looks like it's trivial!
5709 return true;
5710}
5711
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005712/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005713namespace {
5714 struct FindHiddenVirtualMethodData {
5715 Sema *S;
5716 CXXMethodDecl *Method;
5717 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005718 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005719 };
5720}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005721
David Blaikie5f750682012-10-19 00:53:08 +00005722/// \brief Check whether any most overriden method from MD in Methods
5723static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5724 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5725 if (MD->size_overridden_methods() == 0)
5726 return Methods.count(MD->getCanonicalDecl());
5727 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5728 E = MD->end_overridden_methods();
5729 I != E; ++I)
5730 if (CheckMostOverridenMethods(*I, Methods))
5731 return true;
5732 return false;
5733}
5734
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005735/// \brief Member lookup function that determines whether a given C++
5736/// method overloads virtual methods in a base class without overriding any,
5737/// to be used with CXXRecordDecl::lookupInBases().
5738static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5739 CXXBasePath &Path,
5740 void *UserData) {
5741 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5742
5743 FindHiddenVirtualMethodData &Data
5744 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5745
5746 DeclarationName Name = Data.Method->getDeclName();
5747 assert(Name.getNameKind() == DeclarationName::Identifier);
5748
5749 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005750 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005751 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005752 !Path.Decls.empty();
5753 Path.Decls = Path.Decls.slice(1)) {
5754 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005755 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005756 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005757 foundSameNameMethod = true;
5758 // Interested only in hidden virtual methods.
5759 if (!MD->isVirtual())
5760 continue;
5761 // If the method we are checking overrides a method from its base
5762 // don't warn about the other overloaded methods.
5763 if (!Data.S->IsOverload(Data.Method, MD, false))
5764 return true;
5765 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005766 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005767 overloadedMethods.push_back(MD);
5768 }
5769 }
5770
5771 if (foundSameNameMethod)
5772 Data.OverloadedMethods.append(overloadedMethods.begin(),
5773 overloadedMethods.end());
5774 return foundSameNameMethod;
5775}
5776
David Blaikie5f750682012-10-19 00:53:08 +00005777/// \brief Add the most overriden methods from MD to Methods
5778static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5779 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5780 if (MD->size_overridden_methods() == 0)
5781 Methods.insert(MD->getCanonicalDecl());
5782 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5783 E = MD->end_overridden_methods();
5784 I != E; ++I)
5785 AddMostOverridenMethods(*I, Methods);
5786}
5787
Eli Friedmandae92712013-09-05 23:51:03 +00005788/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005789/// overriding any.
Eli Friedmandae92712013-09-05 23:51:03 +00005790void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5791 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramerc4704422012-05-19 16:03:58 +00005792 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005793 return;
5794
5795 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5796 /*bool RecordPaths=*/false,
5797 /*bool DetectVirtual=*/false);
5798 FindHiddenVirtualMethodData Data;
5799 Data.Method = MD;
5800 Data.S = this;
5801
5802 // Keep the base methods that were overriden or introduced in the subclass
5803 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmandae92712013-09-05 23:51:03 +00005804 CXXRecordDecl *DC = MD->getParent();
David Blaikie3bc93e32012-12-19 00:45:41 +00005805 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5806 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5807 NamedDecl *ND = *I;
5808 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005809 ND = shad->getTargetDecl();
5810 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5811 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005812 }
5813
Eli Friedmandae92712013-09-05 23:51:03 +00005814 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5815 OverloadedMethods = Data.OverloadedMethods;
5816}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005817
Eli Friedmandae92712013-09-05 23:51:03 +00005818void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5819 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5820 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5821 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5822 PartialDiagnostic PD = PDiag(
5823 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5824 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5825 Diag(overloadedMD->getLocation(), PD);
5826 }
5827}
5828
5829/// \brief Diagnose methods which overload virtual methods in a base class
5830/// without overriding any.
5831void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5832 if (MD->isInvalidDecl())
5833 return;
5834
5835 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5836 MD->getLocation()) == DiagnosticsEngine::Ignored)
5837 return;
5838
5839 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5840 FindHiddenVirtualMethods(MD, OverloadedMethods);
5841 if (!OverloadedMethods.empty()) {
5842 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5843 << MD << (OverloadedMethods.size() > 1);
5844
5845 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005846 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005847}
5848
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005849void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005850 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005851 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005852 SourceLocation RBrac,
5853 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005854 if (!TagDecl)
5855 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005856
Douglas Gregor42af25f2009-05-11 19:58:34 +00005857 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005858
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005859 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5860 if (l->getKind() != AttributeList::AT_Visibility)
5861 continue;
5862 l->setInvalid();
5863 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5864 l->getName();
5865 }
5866
David Blaikie77b6de02011-09-22 02:58:26 +00005867 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005868 // strict aliasing violation!
5869 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005870 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005871
Douglas Gregor23c94db2010-07-02 17:43:08 +00005872 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005873 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005874}
5875
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005876/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5877/// special functions, such as the default constructor, copy
5878/// constructor, or destructor, to the given C++ class (C++
5879/// [special]p1). This routine can only be executed just before the
5880/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005881void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005882 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005883 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005884
Richard Smithbc2a35d2012-12-08 08:32:28 +00005885 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005886 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005887
Richard Smithbc2a35d2012-12-08 08:32:28 +00005888 // If the properties or semantics of the copy constructor couldn't be
5889 // determined while the class was being declared, force a declaration
5890 // of it now.
5891 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5892 DeclareImplicitCopyConstructor(ClassDecl);
5893 }
5894
Richard Smith80ad52f2013-01-02 11:42:31 +00005895 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005896 ++ASTContext::NumImplicitMoveConstructors;
5897
Richard Smithbc2a35d2012-12-08 08:32:28 +00005898 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5899 DeclareImplicitMoveConstructor(ClassDecl);
5900 }
5901
Douglas Gregora376d102010-07-02 21:50:04 +00005902 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5903 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005904
5905 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005906 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005907 // it shows up in the right place in the vtable and that we diagnose
5908 // problems with the implicit exception specification.
5909 if (ClassDecl->isDynamicClass() ||
5910 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005911 DeclareImplicitCopyAssignment(ClassDecl);
5912 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005913
Richard Smith80ad52f2013-01-02 11:42:31 +00005914 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005915 ++ASTContext::NumImplicitMoveAssignmentOperators;
5916
5917 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005918 if (ClassDecl->isDynamicClass() ||
5919 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005920 DeclareImplicitMoveAssignment(ClassDecl);
5921 }
5922
Douglas Gregor4923aa22010-07-02 20:37:36 +00005923 if (!ClassDecl->hasUserDeclaredDestructor()) {
5924 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005925
5926 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005927 // have to declare the destructor immediately. This ensures that, e.g., it
5928 // shows up in the right place in the vtable and that we diagnose problems
5929 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005930 if (ClassDecl->isDynamicClass() ||
5931 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005932 DeclareImplicitDestructor(ClassDecl);
5933 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005934}
5935
Francois Pichet8387e2a2011-04-22 22:18:13 +00005936void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5937 if (!D)
5938 return;
5939
5940 int NumParamList = D->getNumTemplateParameterLists();
5941 for (int i = 0; i < NumParamList; i++) {
5942 TemplateParameterList* Params = D->getTemplateParameterList(i);
5943 for (TemplateParameterList::iterator Param = Params->begin(),
5944 ParamEnd = Params->end();
5945 Param != ParamEnd; ++Param) {
5946 NamedDecl *Named = cast<NamedDecl>(*Param);
5947 if (Named->getDeclName()) {
5948 S->AddDecl(Named);
5949 IdResolver.AddDecl(Named);
5950 }
5951 }
5952 }
5953}
5954
John McCalld226f652010-08-21 09:40:31 +00005955void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005956 if (!D)
5957 return;
5958
5959 TemplateParameterList *Params = 0;
5960 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5961 Params = Template->getTemplateParameters();
5962 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5963 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5964 Params = PartialSpec->getTemplateParameters();
5965 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005966 return;
5967
Douglas Gregor6569d682009-05-27 23:11:45 +00005968 for (TemplateParameterList::iterator Param = Params->begin(),
5969 ParamEnd = Params->end();
5970 Param != ParamEnd; ++Param) {
5971 NamedDecl *Named = cast<NamedDecl>(*Param);
5972 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005973 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005974 IdResolver.AddDecl(Named);
5975 }
5976 }
5977}
5978
John McCalld226f652010-08-21 09:40:31 +00005979void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005980 if (!RecordD) return;
5981 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005982 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005983 PushDeclContext(S, Record);
5984}
5985
John McCalld226f652010-08-21 09:40:31 +00005986void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005987 if (!RecordD) return;
5988 PopDeclContext();
5989}
5990
Douglas Gregor72b505b2008-12-16 21:30:33 +00005991/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5992/// parsing a top-level (non-nested) C++ class, and we are now
5993/// parsing those parts of the given Method declaration that could
5994/// not be parsed earlier (C++ [class.mem]p2), such as default
5995/// arguments. This action should enter the scope of the given
5996/// Method declaration as if we had just parsed the qualified method
5997/// name. However, it should not bring the parameters into scope;
5998/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005999void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006000}
6001
6002/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6003/// C++ method declaration. We're (re-)introducing the given
6004/// function parameter into scope for use in parsing later parts of
6005/// the method declaration. For example, we could see an
6006/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00006007void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006008 if (!ParamD)
6009 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006010
John McCalld226f652010-08-21 09:40:31 +00006011 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00006012
6013 // If this parameter has an unparsed default argument, clear it out
6014 // to make way for the parsed default argument.
6015 if (Param->hasUnparsedDefaultArg())
6016 Param->setDefaultArg(0);
6017
John McCalld226f652010-08-21 09:40:31 +00006018 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006019 if (Param->getDeclName())
6020 IdResolver.AddDecl(Param);
6021}
6022
6023/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6024/// processing the delayed method declaration for Method. The method
6025/// declaration is now considered finished. There may be a separate
6026/// ActOnStartOfFunctionDef action later (not necessarily
6027/// immediately!) for this method, if it was also defined inside the
6028/// class body.
John McCalld226f652010-08-21 09:40:31 +00006029void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006030 if (!MethodD)
6031 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006032
Douglas Gregorefd5bda2009-08-24 11:57:43 +00006033 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00006034
John McCalld226f652010-08-21 09:40:31 +00006035 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006036
6037 // Now that we have our default arguments, check the constructor
6038 // again. It could produce additional diagnostics or affect whether
6039 // the class has implicitly-declared destructors, among other
6040 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00006041 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6042 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006043
6044 // Check the default arguments, which we may have added.
6045 if (!Method->isInvalidDecl())
6046 CheckCXXDefaultArguments(Method);
6047}
6048
Douglas Gregor42a552f2008-11-05 20:51:48 +00006049/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00006050/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00006051/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006052/// emit diagnostics and set the invalid bit to true. In any case, the type
6053/// will be updated to reflect a well-formed type for the constructor and
6054/// returned.
6055QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006056 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006057 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006058
6059 // C++ [class.ctor]p3:
6060 // A constructor shall not be virtual (10.3) or static (9.4). A
6061 // constructor can be invoked for a const, volatile or const
6062 // volatile object. A constructor shall not be declared const,
6063 // volatile, or const volatile (9.3.2).
6064 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00006065 if (!D.isInvalidType())
6066 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6067 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6068 << SourceRange(D.getIdentifierLoc());
6069 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006070 }
John McCalld931b082010-08-26 03:08:43 +00006071 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006072 if (!D.isInvalidType())
6073 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6074 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6075 << SourceRange(D.getIdentifierLoc());
6076 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006077 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006078 }
Mike Stump1eb44332009-09-09 15:08:12 +00006079
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006080 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006081 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00006082 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006083 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6084 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006085 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006086 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6087 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006088 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006089 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6090 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00006091 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006092 }
Mike Stump1eb44332009-09-09 15:08:12 +00006093
Douglas Gregorc938c162011-01-26 05:01:58 +00006094 // C++0x [class.ctor]p4:
6095 // A constructor shall not be declared with a ref-qualifier.
6096 if (FTI.hasRefQualifier()) {
6097 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6098 << FTI.RefQualifierIsLValueRef
6099 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6100 D.setInvalidType();
6101 }
6102
Douglas Gregor42a552f2008-11-05 20:51:48 +00006103 // Rebuild the function type "R" without any type qualifiers (in
6104 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00006105 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00006106 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006107 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6108 return R;
6109
6110 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6111 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006112 EPI.RefQualifier = RQ_None;
6113
Richard Smith07b0fdc2013-03-18 21:12:30 +00006114 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006115}
6116
Douglas Gregor72b505b2008-12-16 21:30:33 +00006117/// CheckConstructor - Checks a fully-formed constructor for
6118/// well-formedness, issuing any diagnostics required. Returns true if
6119/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00006120void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00006121 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00006122 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6123 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00006124 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006125
6126 // C++ [class.copy]p3:
6127 // A declaration of a constructor for a class X is ill-formed if
6128 // its first parameter is of type (optionally cv-qualified) X and
6129 // either there are no other parameters or else all other
6130 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00006131 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006132 ((Constructor->getNumParams() == 1) ||
6133 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00006134 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6135 Constructor->getTemplateSpecializationKind()
6136 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006137 QualType ParamType = Constructor->getParamDecl(0)->getType();
6138 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6139 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00006140 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006141 const char *ConstRef
6142 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6143 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00006144 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006145 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00006146
6147 // FIXME: Rather that making the constructor invalid, we should endeavor
6148 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00006149 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006150 }
6151 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00006152}
6153
John McCall15442822010-08-04 01:04:25 +00006154/// CheckDestructor - Checks a fully-formed destructor definition for
6155/// well-formedness, issuing any diagnostics required. Returns true
6156/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006157bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006158 CXXRecordDecl *RD = Destructor->getParent();
6159
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006160 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006161 SourceLocation Loc;
6162
6163 if (!Destructor->isImplicit())
6164 Loc = Destructor->getLocation();
6165 else
6166 Loc = RD->getLocation();
6167
6168 // If we have a virtual destructor, look up the deallocation function
6169 FunctionDecl *OperatorDelete = 0;
6170 DeclarationName Name =
6171 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006172 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00006173 return true;
John McCall5efd91a2010-07-03 18:33:00 +00006174
Eli Friedman5f2987c2012-02-02 03:46:19 +00006175 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00006176
6177 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00006178 }
Anders Carlsson37909802009-11-30 21:24:50 +00006179
6180 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00006181}
6182
Mike Stump1eb44332009-09-09 15:08:12 +00006183static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006184FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6185 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6186 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006187 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006188}
6189
Douglas Gregor42a552f2008-11-05 20:51:48 +00006190/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6191/// the well-formednes of the destructor declarator @p D with type @p
6192/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006193/// emit diagnostics and set the declarator to invalid. Even if this happens,
6194/// will be updated to reflect a well-formed type for the destructor and
6195/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00006196QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006197 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006198 // C++ [class.dtor]p1:
6199 // [...] A typedef-name that names a class is a class-name
6200 // (7.1.3); however, a typedef-name that names a class shall not
6201 // be used as the identifier in the declarator for a destructor
6202 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006203 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006204 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006205 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006206 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006207 else if (const TemplateSpecializationType *TST =
6208 DeclaratorType->getAs<TemplateSpecializationType>())
6209 if (TST->isTypeAlias())
6210 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6211 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006212
6213 // C++ [class.dtor]p2:
6214 // A destructor is used to destroy objects of its class type. A
6215 // destructor takes no parameters, and no return type can be
6216 // specified for it (not even void). The address of a destructor
6217 // shall not be taken. A destructor shall not be static. A
6218 // destructor can be invoked for a const, volatile or const
6219 // volatile object. A destructor shall not be declared const,
6220 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006221 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006222 if (!D.isInvalidType())
6223 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6224 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006225 << SourceRange(D.getIdentifierLoc())
6226 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6227
John McCalld931b082010-08-26 03:08:43 +00006228 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006229 }
Chris Lattner65401802009-04-25 08:28:21 +00006230 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006231 // Destructors don't have return types, but the parser will
6232 // happily parse something like:
6233 //
6234 // class X {
6235 // float ~X();
6236 // };
6237 //
6238 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006239 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6240 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6241 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006242 }
Mike Stump1eb44332009-09-09 15:08:12 +00006243
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006244 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006245 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006246 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006247 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6248 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006249 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006250 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6251 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006252 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006253 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6254 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006255 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006256 }
6257
Douglas Gregorc938c162011-01-26 05:01:58 +00006258 // C++0x [class.dtor]p2:
6259 // A destructor shall not be declared with a ref-qualifier.
6260 if (FTI.hasRefQualifier()) {
6261 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6262 << FTI.RefQualifierIsLValueRef
6263 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6264 D.setInvalidType();
6265 }
6266
Douglas Gregor42a552f2008-11-05 20:51:48 +00006267 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006268 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006269 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6270
6271 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006272 FTI.freeArgs();
6273 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006274 }
6275
Mike Stump1eb44332009-09-09 15:08:12 +00006276 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006277 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006278 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006279 D.setInvalidType();
6280 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006281
6282 // Rebuild the function type "R" without any type qualifiers or
6283 // parameters (in case any of the errors above fired) and with
6284 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006285 // types.
John McCalle23cf432010-12-14 08:05:40 +00006286 if (!D.isInvalidType())
6287 return R;
6288
Douglas Gregord92ec472010-07-01 05:10:53 +00006289 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006290 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6291 EPI.Variadic = false;
6292 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006293 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006294 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006295}
6296
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006297/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6298/// well-formednes of the conversion function declarator @p D with
6299/// type @p R. If there are any errors in the declarator, this routine
6300/// will emit diagnostics and return true. Otherwise, it will return
6301/// false. Either way, the type @p R will be updated to reflect a
6302/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006303void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006304 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006305 // C++ [class.conv.fct]p1:
6306 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006307 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006308 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006309 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006310 if (!D.isInvalidType())
6311 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006312 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6313 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006314 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006315 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006316 }
John McCalla3f81372010-04-13 00:04:31 +00006317
6318 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6319
Chris Lattner6e475012009-04-25 08:35:12 +00006320 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006321 // Conversion functions don't have return types, but the parser will
6322 // happily parse something like:
6323 //
6324 // class X {
6325 // float operator bool();
6326 // };
6327 //
6328 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006329 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6330 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6331 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006332 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006333 }
6334
John McCalla3f81372010-04-13 00:04:31 +00006335 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6336
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006337 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006338 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006339 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6340
6341 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006342 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006343 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006344 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006345 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006346 D.setInvalidType();
6347 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006348
John McCalla3f81372010-04-13 00:04:31 +00006349 // Diagnose "&operator bool()" and other such nonsense. This
6350 // is actually a gcc extension which we don't support.
6351 if (Proto->getResultType() != ConvType) {
6352 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6353 << Proto->getResultType();
6354 D.setInvalidType();
6355 ConvType = Proto->getResultType();
6356 }
6357
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006358 // C++ [class.conv.fct]p4:
6359 // The conversion-type-id shall not represent a function type nor
6360 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006361 if (ConvType->isArrayType()) {
6362 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6363 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006364 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006365 } else if (ConvType->isFunctionType()) {
6366 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6367 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006368 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006369 }
6370
6371 // Rebuild the function type "R" without any parameters (in case any
6372 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006373 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006374 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006375 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006376
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006377 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006378 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006379 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006380 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006381 diag::warn_cxx98_compat_explicit_conversion_functions :
6382 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006383 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006384}
6385
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006386/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6387/// the declaration of the given C++ conversion function. This routine
6388/// is responsible for recording the conversion function in the C++
6389/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006390Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006391 assert(Conversion && "Expected to receive a conversion function declaration");
6392
Douglas Gregor9d350972008-12-12 08:25:50 +00006393 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006394
6395 // Make sure we aren't redeclaring the conversion function.
6396 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006397
6398 // C++ [class.conv.fct]p1:
6399 // [...] A conversion function is never used to convert a
6400 // (possibly cv-qualified) object to the (possibly cv-qualified)
6401 // same object type (or a reference to it), to a (possibly
6402 // cv-qualified) base class of that type (or a reference to it),
6403 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006404 // FIXME: Suppress this warning if the conversion function ends up being a
6405 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006406 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006407 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006408 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006409 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006410 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6411 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006412 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006413 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006414 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6415 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006416 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006417 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006418 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006419 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006420 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006421 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006422 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006423 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006424 }
6425
Douglas Gregore80622f2010-09-29 04:25:11 +00006426 if (FunctionTemplateDecl *ConversionTemplate
6427 = Conversion->getDescribedFunctionTemplate())
6428 return ConversionTemplate;
6429
John McCalld226f652010-08-21 09:40:31 +00006430 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006431}
6432
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006433//===----------------------------------------------------------------------===//
6434// Namespace Handling
6435//===----------------------------------------------------------------------===//
6436
Richard Smithd1a55a62012-10-04 22:13:39 +00006437/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6438/// reopened.
6439static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6440 SourceLocation Loc,
6441 IdentifierInfo *II, bool *IsInline,
6442 NamespaceDecl *PrevNS) {
6443 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006444
Richard Smithc969e6a2012-10-05 01:46:25 +00006445 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6446 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6447 // inline namespaces, with the intention of bringing names into namespace std.
6448 //
6449 // We support this just well enough to get that case working; this is not
6450 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006451 if (*IsInline && II && II->getName().startswith("__atomic") &&
6452 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006453 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006454 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6455 NS = NS->getPreviousDecl())
6456 NS->setInline(*IsInline);
6457 // Patch up the lookup table for the containing namespace. This isn't really
6458 // correct, but it's good enough for this particular case.
6459 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6460 E = PrevNS->decls_end(); I != E; ++I)
6461 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6462 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6463 return;
6464 }
6465
6466 if (PrevNS->isInline())
6467 // The user probably just forgot the 'inline', so suggest that it
6468 // be added back.
6469 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6470 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6471 else
6472 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6473 << IsInline;
6474
6475 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6476 *IsInline = PrevNS->isInline();
6477}
John McCallea318642010-08-26 09:15:37 +00006478
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006479/// ActOnStartNamespaceDef - This is called at the start of a namespace
6480/// definition.
John McCalld226f652010-08-21 09:40:31 +00006481Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006482 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006483 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006484 SourceLocation IdentLoc,
6485 IdentifierInfo *II,
6486 SourceLocation LBrace,
6487 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006488 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6489 // For anonymous namespace, take the location of the left brace.
6490 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006491 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006492 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006493 bool IsStd = false;
6494 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006495 Scope *DeclRegionScope = NamespcScope->getParent();
6496
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006497 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006498 if (II) {
6499 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006500 // The identifier in an original-namespace-definition shall not
6501 // have been previously defined in the declarative region in
6502 // which the original-namespace-definition appears. The
6503 // identifier in an original-namespace-definition is the name of
6504 // the namespace. Subsequently in that declarative region, it is
6505 // treated as an original-namespace-name.
6506 //
6507 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006508 // look through using directives, just look for any ordinary names.
6509
6510 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006511 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6512 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006513 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006514 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6515 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6516 ++I) {
6517 if ((*I)->getIdentifierNamespace() & IDNS) {
6518 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006519 break;
6520 }
6521 }
6522
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006523 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6524
6525 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006526 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006527 if (IsInline != PrevNS->isInline())
6528 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6529 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006530 } else if (PrevDecl) {
6531 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006532 Diag(Loc, diag::err_redefinition_different_kind)
6533 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006534 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006535 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006536 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006537 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006538 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006539 // This is the first "real" definition of the namespace "std", so update
6540 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006541 PrevNS = getStdNamespace();
6542 IsStd = true;
6543 AddToKnown = !IsInline;
6544 } else {
6545 // We've seen this namespace for the first time.
6546 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006547 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006548 } else {
John McCall9aeed322009-10-01 00:25:31 +00006549 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006550
6551 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006552 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006553 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006554 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006555 } else {
6556 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006557 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006558 }
6559
Richard Smithd1a55a62012-10-04 22:13:39 +00006560 if (PrevNS && IsInline != PrevNS->isInline())
6561 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6562 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006563 }
6564
6565 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6566 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006567 if (IsInvalid)
6568 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006569
6570 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006571
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006572 // FIXME: Should we be merging attributes?
6573 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006574 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006575
6576 if (IsStd)
6577 StdNamespace = Namespc;
6578 if (AddToKnown)
6579 KnownNamespaces[Namespc] = false;
6580
6581 if (II) {
6582 PushOnScopeChains(Namespc, DeclRegionScope);
6583 } else {
6584 // Link the anonymous namespace into its parent.
6585 DeclContext *Parent = CurContext->getRedeclContext();
6586 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6587 TU->setAnonymousNamespace(Namespc);
6588 } else {
6589 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006590 }
John McCall9aeed322009-10-01 00:25:31 +00006591
Douglas Gregora4181472010-03-24 00:46:35 +00006592 CurContext->addDecl(Namespc);
6593
John McCall9aeed322009-10-01 00:25:31 +00006594 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6595 // behaves as if it were replaced by
6596 // namespace unique { /* empty body */ }
6597 // using namespace unique;
6598 // namespace unique { namespace-body }
6599 // where all occurrences of 'unique' in a translation unit are
6600 // replaced by the same identifier and this identifier differs
6601 // from all other identifiers in the entire program.
6602
6603 // We just create the namespace with an empty name and then add an
6604 // implicit using declaration, just like the standard suggests.
6605 //
6606 // CodeGen enforces the "universally unique" aspect by giving all
6607 // declarations semantically contained within an anonymous
6608 // namespace internal linkage.
6609
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006610 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006611 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006612 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006613 /* 'using' */ LBrace,
6614 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006615 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006616 /* identifier */ SourceLocation(),
6617 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006618 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006619 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006620 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006621 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006622 }
6623
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006624 ActOnDocumentableDecl(Namespc);
6625
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006626 // Although we could have an invalid decl (i.e. the namespace name is a
6627 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006628 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6629 // for the namespace has the declarations that showed up in that particular
6630 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006631 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006632 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006633}
6634
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006635/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6636/// is a namespace alias, returns the namespace it points to.
6637static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6638 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6639 return AD->getNamespace();
6640 return dyn_cast_or_null<NamespaceDecl>(D);
6641}
6642
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006643/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6644/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006645void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006646 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6647 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006648 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006649 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006650 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006651 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006652}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006653
John McCall384aff82010-08-25 07:42:41 +00006654CXXRecordDecl *Sema::getStdBadAlloc() const {
6655 return cast_or_null<CXXRecordDecl>(
6656 StdBadAlloc.get(Context.getExternalSource()));
6657}
6658
6659NamespaceDecl *Sema::getStdNamespace() const {
6660 return cast_or_null<NamespaceDecl>(
6661 StdNamespace.get(Context.getExternalSource()));
6662}
6663
Douglas Gregor66992202010-06-29 17:53:46 +00006664/// \brief Retrieve the special "std" namespace, which may require us to
6665/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006666NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006667 if (!StdNamespace) {
6668 // The "std" namespace has not yet been defined, so build one implicitly.
6669 StdNamespace = NamespaceDecl::Create(Context,
6670 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006671 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006672 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006673 &PP.getIdentifierTable().get("std"),
6674 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006675 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006676 }
6677
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006678 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006679}
6680
Sebastian Redl395e04d2012-01-17 22:49:33 +00006681bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006682 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006683 "Looking for std::initializer_list outside of C++.");
6684
6685 // We're looking for implicit instantiations of
6686 // template <typename E> class std::initializer_list.
6687
6688 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6689 return false;
6690
Sebastian Redl84760e32012-01-17 22:49:58 +00006691 ClassTemplateDecl *Template = 0;
6692 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006693
Sebastian Redl84760e32012-01-17 22:49:58 +00006694 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006695
Sebastian Redl84760e32012-01-17 22:49:58 +00006696 ClassTemplateSpecializationDecl *Specialization =
6697 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6698 if (!Specialization)
6699 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006700
Sebastian Redl84760e32012-01-17 22:49:58 +00006701 Template = Specialization->getSpecializedTemplate();
6702 Arguments = Specialization->getTemplateArgs().data();
6703 } else if (const TemplateSpecializationType *TST =
6704 Ty->getAs<TemplateSpecializationType>()) {
6705 Template = dyn_cast_or_null<ClassTemplateDecl>(
6706 TST->getTemplateName().getAsTemplateDecl());
6707 Arguments = TST->getArgs();
6708 }
6709 if (!Template)
6710 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006711
6712 if (!StdInitializerList) {
6713 // Haven't recognized std::initializer_list yet, maybe this is it.
6714 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6715 if (TemplateClass->getIdentifier() !=
6716 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006717 !getStdNamespace()->InEnclosingNamespaceSetOf(
6718 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006719 return false;
6720 // This is a template called std::initializer_list, but is it the right
6721 // template?
6722 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006723 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006724 return false;
6725 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6726 return false;
6727
6728 // It's the right template.
6729 StdInitializerList = Template;
6730 }
6731
6732 if (Template != StdInitializerList)
6733 return false;
6734
6735 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006736 if (Element)
6737 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006738 return true;
6739}
6740
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006741static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6742 NamespaceDecl *Std = S.getStdNamespace();
6743 if (!Std) {
6744 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6745 return 0;
6746 }
6747
6748 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6749 Loc, Sema::LookupOrdinaryName);
6750 if (!S.LookupQualifiedName(Result, Std)) {
6751 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6752 return 0;
6753 }
6754 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6755 if (!Template) {
6756 Result.suppressDiagnostics();
6757 // We found something weird. Complain about the first thing we found.
6758 NamedDecl *Found = *Result.begin();
6759 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6760 return 0;
6761 }
6762
6763 // We found some template called std::initializer_list. Now verify that it's
6764 // correct.
6765 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006766 if (Params->getMinRequiredArguments() != 1 ||
6767 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006768 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6769 return 0;
6770 }
6771
6772 return Template;
6773}
6774
6775QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6776 if (!StdInitializerList) {
6777 StdInitializerList = LookupStdInitializerList(*this, Loc);
6778 if (!StdInitializerList)
6779 return QualType();
6780 }
6781
6782 TemplateArgumentListInfo Args(Loc, Loc);
6783 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6784 Context.getTrivialTypeSourceInfo(Element,
6785 Loc)));
6786 return Context.getCanonicalType(
6787 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6788}
6789
Sebastian Redl98d36062012-01-17 22:50:14 +00006790bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6791 // C++ [dcl.init.list]p2:
6792 // A constructor is an initializer-list constructor if its first parameter
6793 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6794 // std::initializer_list<E> for some type E, and either there are no other
6795 // parameters or else all other parameters have default arguments.
6796 if (Ctor->getNumParams() < 1 ||
6797 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6798 return false;
6799
6800 QualType ArgType = Ctor->getParamDecl(0)->getType();
6801 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6802 ArgType = RT->getPointeeType().getUnqualifiedType();
6803
6804 return isStdInitializerList(ArgType, 0);
6805}
6806
Douglas Gregor9172aa62011-03-26 22:25:30 +00006807/// \brief Determine whether a using statement is in a context where it will be
6808/// apply in all contexts.
6809static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6810 switch (CurContext->getDeclKind()) {
6811 case Decl::TranslationUnit:
6812 return true;
6813 case Decl::LinkageSpec:
6814 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6815 default:
6816 return false;
6817 }
6818}
6819
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006820namespace {
6821
6822// Callback to only accept typo corrections that are namespaces.
6823class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006824public:
6825 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6826 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006827 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006828 return false;
6829 }
6830};
6831
6832}
6833
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006834static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6835 CXXScopeSpec &SS,
6836 SourceLocation IdentLoc,
6837 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006838 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006839 R.clear();
6840 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006841 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006842 Validator)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006843 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00006844 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6845 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006846 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00006847 S.diagnoseTypo(Corrected,
6848 S.PDiag(diag::err_using_directive_member_suggest)
6849 << Ident << DC << DroppedSpecifier << SS.getRange(),
6850 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006851 } else {
Richard Smith2d670972013-08-17 00:46:16 +00006852 S.diagnoseTypo(Corrected,
6853 S.PDiag(diag::err_using_directive_suggest) << Ident,
6854 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006855 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006856 R.addDecl(Corrected.getCorrectionDecl());
6857 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006858 }
6859 return false;
6860}
6861
John McCalld226f652010-08-21 09:40:31 +00006862Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006863 SourceLocation UsingLoc,
6864 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006865 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006866 SourceLocation IdentLoc,
6867 IdentifierInfo *NamespcName,
6868 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006869 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6870 assert(NamespcName && "Invalid NamespcName.");
6871 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006872
6873 // This can only happen along a recovery path.
6874 while (S->getFlags() & Scope::TemplateParamScope)
6875 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006876 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006877
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006878 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006879 NestedNameSpecifier *Qualifier = 0;
6880 if (SS.isSet())
6881 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6882
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006883 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006884 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6885 LookupParsedName(R, S, &SS);
6886 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006887 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006888
Douglas Gregor66992202010-06-29 17:53:46 +00006889 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006890 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006891 // Allow "using namespace std;" or "using namespace ::std;" even if
6892 // "std" hasn't been defined yet, for GCC compatibility.
6893 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6894 NamespcName->isStr("std")) {
6895 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006896 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006897 R.resolveKind();
6898 }
6899 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006900 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006901 }
6902
John McCallf36e02d2009-10-09 21:13:30 +00006903 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006904 NamedDecl *Named = R.getFoundDecl();
6905 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6906 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006907 // C++ [namespace.udir]p1:
6908 // A using-directive specifies that the names in the nominated
6909 // namespace can be used in the scope in which the
6910 // using-directive appears after the using-directive. During
6911 // unqualified name lookup (3.4.1), the names appear as if they
6912 // were declared in the nearest enclosing namespace which
6913 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006914 // namespace. [Note: in this context, "contains" means "contains
6915 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006916
6917 // Find enclosing context containing both using-directive and
6918 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006919 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006920 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6921 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6922 CommonAncestor = CommonAncestor->getParent();
6923
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006924 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006925 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006926 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006927
Douglas Gregor9172aa62011-03-26 22:25:30 +00006928 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00006929 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006930 Diag(IdentLoc, diag::warn_using_directive_in_header);
6931 }
6932
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006933 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006934 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006935 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006936 }
6937
Richard Smith6b3d3e52013-02-20 19:22:51 +00006938 if (UDir)
6939 ProcessDeclAttributeList(S, UDir, AttrList);
6940
John McCalld226f652010-08-21 09:40:31 +00006941 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006942}
6943
6944void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006945 // If the scope has an associated entity and the using directive is at
6946 // namespace or translation unit scope, add the UsingDirectiveDecl into
6947 // its lookup structure so qualified name lookup can find it.
Ted Kremenekf0d58612013-10-08 17:08:03 +00006948 DeclContext *Ctx = S->getEntity();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006949 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006950 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006951 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006952 // Otherwise, it is at block sope. The using-directives will affect lookup
6953 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006954 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006955}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006956
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006957
John McCalld226f652010-08-21 09:40:31 +00006958Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006959 AccessSpecifier AS,
6960 bool HasUsingKeyword,
6961 SourceLocation UsingLoc,
6962 CXXScopeSpec &SS,
6963 UnqualifiedId &Name,
6964 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006965 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00006966 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006967 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006968
Douglas Gregor12c118a2009-11-04 16:30:06 +00006969 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006970 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006971 case UnqualifiedId::IK_Identifier:
6972 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006973 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006974 case UnqualifiedId::IK_ConversionFunctionId:
6975 break;
6976
6977 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006978 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006979 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006980 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006981 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006982 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006983 diag::err_using_decl_constructor)
6984 << SS.getRange();
6985
Richard Smith80ad52f2013-01-02 11:42:31 +00006986 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006987
John McCalld226f652010-08-21 09:40:31 +00006988 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006989
6990 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006991 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006992 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006993 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006994
6995 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006996 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006997 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006998 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006999 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007000
7001 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7002 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00007003 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00007004 return 0;
John McCall604e7f12009-12-08 07:46:18 +00007005
Richard Smith07b0fdc2013-03-18 21:12:30 +00007006 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00007007 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00007008 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00007009 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7010 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00007011 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00007012 }
7013
Douglas Gregor56c04582010-12-16 00:46:58 +00007014 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7015 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7016 return 0;
7017
John McCall9488ea12009-11-17 05:59:44 +00007018 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007019 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007020 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007021 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00007022 if (UD)
7023 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00007024
John McCalld226f652010-08-21 09:40:31 +00007025 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00007026}
7027
Douglas Gregor09acc982010-07-07 23:08:52 +00007028/// \brief Determine whether a using declaration considers the given
7029/// declarations as "equivalent", e.g., if they are redeclarations of
7030/// the same entity or are both typedefs of the same type.
Richard Smithf06a28932013-10-23 02:17:46 +00007031static bool
7032IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7033 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
Douglas Gregor09acc982010-07-07 23:08:52 +00007034 return true;
Douglas Gregor09acc982010-07-07 23:08:52 +00007035
Richard Smith162e1c12011-04-15 14:24:37 +00007036 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
Richard Smithf06a28932013-10-23 02:17:46 +00007037 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
Douglas Gregor09acc982010-07-07 23:08:52 +00007038 return Context.hasSameType(TD1->getUnderlyingType(),
7039 TD2->getUnderlyingType());
Douglas Gregor09acc982010-07-07 23:08:52 +00007040
7041 return false;
7042}
7043
7044
John McCall9f54ad42009-12-10 09:41:52 +00007045/// Determines whether to create a using shadow decl for a particular
7046/// decl, given the set of decls existing prior to this using lookup.
7047bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
Richard Smithf06a28932013-10-23 02:17:46 +00007048 const LookupResult &Previous,
7049 UsingShadowDecl *&PrevShadow) {
John McCall9f54ad42009-12-10 09:41:52 +00007050 // Diagnose finding a decl which is not from a base class of the
7051 // current class. We do this now because there are cases where this
7052 // function will silently decide not to build a shadow decl, which
7053 // will pre-empt further diagnostics.
7054 //
7055 // We don't need to do this in C++0x because we do the check once on
7056 // the qualifier.
7057 //
7058 // FIXME: diagnose the following if we care enough:
7059 // struct A { int foo; };
7060 // struct B : A { using A::foo; };
7061 // template <class T> struct C : A {};
7062 // template <class T> struct D : C<T> { using B::foo; } // <---
7063 // This is invalid (during instantiation) in C++03 because B::foo
7064 // resolves to the using decl in B, which is not a base class of D<T>.
7065 // We can't diagnose it immediately because C<T> is an unknown
7066 // specialization. The UsingShadowDecl in D<T> then points directly
7067 // to A::foo, which will look well-formed when we instantiate.
7068 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00007069 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00007070 DeclContext *OrigDC = Orig->getDeclContext();
7071
7072 // Handle enums and anonymous structs.
7073 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7074 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7075 while (OrigRec->isAnonymousStructOrUnion())
7076 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7077
7078 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7079 if (OrigDC == CurContext) {
7080 Diag(Using->getLocation(),
7081 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007082 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007083 Diag(Orig->getLocation(), diag::note_using_decl_target);
7084 return true;
7085 }
7086
Douglas Gregordc355712011-02-25 00:36:19 +00007087 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00007088 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007089 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00007090 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00007091 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007092 Diag(Orig->getLocation(), diag::note_using_decl_target);
7093 return true;
7094 }
7095 }
7096
7097 if (Previous.empty()) return false;
7098
7099 NamedDecl *Target = Orig;
7100 if (isa<UsingShadowDecl>(Target))
7101 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7102
John McCalld7533ec2009-12-11 02:33:26 +00007103 // If the target happens to be one of the previous declarations, we
7104 // don't have a conflict.
7105 //
7106 // FIXME: but we might be increasing its access, in which case we
7107 // should redeclare it.
7108 NamedDecl *NonTag = 0, *Tag = 0;
Richard Smithf06a28932013-10-23 02:17:46 +00007109 bool FoundEquivalentDecl = false;
John McCalld7533ec2009-12-11 02:33:26 +00007110 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7111 I != E; ++I) {
7112 NamedDecl *D = (*I)->getUnderlyingDecl();
Richard Smithf06a28932013-10-23 02:17:46 +00007113 if (IsEquivalentForUsingDecl(Context, D, Target)) {
7114 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7115 PrevShadow = Shadow;
7116 FoundEquivalentDecl = true;
7117 }
John McCalld7533ec2009-12-11 02:33:26 +00007118
7119 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7120 }
7121
Richard Smithf06a28932013-10-23 02:17:46 +00007122 if (FoundEquivalentDecl)
7123 return false;
7124
John McCall9f54ad42009-12-10 09:41:52 +00007125 if (Target->isFunctionOrFunctionTemplate()) {
7126 FunctionDecl *FD;
7127 if (isa<FunctionTemplateDecl>(Target))
7128 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7129 else
7130 FD = cast<FunctionDecl>(Target);
7131
7132 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00007133 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00007134 case Ovl_Overload:
7135 return false;
7136
7137 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00007138 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007139 break;
7140
7141 // We found a decl with the exact signature.
7142 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007143 // If we're in a record, we want to hide the target, so we
7144 // return true (without a diagnostic) to tell the caller not to
7145 // build a shadow decl.
7146 if (CurContext->isRecord())
7147 return true;
7148
7149 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00007150 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007151 break;
7152 }
7153
7154 Diag(Target->getLocation(), diag::note_using_decl_target);
7155 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7156 return true;
7157 }
7158
7159 // Target is not a function.
7160
John McCall9f54ad42009-12-10 09:41:52 +00007161 if (isa<TagDecl>(Target)) {
7162 // No conflict between a tag and a non-tag.
7163 if (!Tag) return false;
7164
John McCall41ce66f2009-12-10 19:51:03 +00007165 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007166 Diag(Target->getLocation(), diag::note_using_decl_target);
7167 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7168 return true;
7169 }
7170
7171 // No conflict between a tag and a non-tag.
7172 if (!NonTag) return false;
7173
John McCall41ce66f2009-12-10 19:51:03 +00007174 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007175 Diag(Target->getLocation(), diag::note_using_decl_target);
7176 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7177 return true;
7178}
7179
John McCall9488ea12009-11-17 05:59:44 +00007180/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00007181UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00007182 UsingDecl *UD,
Richard Smithf06a28932013-10-23 02:17:46 +00007183 NamedDecl *Orig,
7184 UsingShadowDecl *PrevDecl) {
John McCall9488ea12009-11-17 05:59:44 +00007185
7186 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00007187 NamedDecl *Target = Orig;
7188 if (isa<UsingShadowDecl>(Target)) {
7189 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7190 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00007191 }
Richard Smithf06a28932013-10-23 02:17:46 +00007192
John McCall9488ea12009-11-17 05:59:44 +00007193 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00007194 = UsingShadowDecl::Create(Context, CurContext,
7195 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00007196 UD->addShadowDecl(Shadow);
Richard Smithf06a28932013-10-23 02:17:46 +00007197
Douglas Gregore80622f2010-09-29 04:25:11 +00007198 Shadow->setAccess(UD->getAccess());
7199 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7200 Shadow->setInvalidDecl();
Richard Smithf06a28932013-10-23 02:17:46 +00007201
7202 Shadow->setPreviousDecl(PrevDecl);
7203
John McCall9488ea12009-11-17 05:59:44 +00007204 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007205 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007206 else
John McCall604e7f12009-12-08 07:46:18 +00007207 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007208
John McCall604e7f12009-12-08 07:46:18 +00007209
John McCall9f54ad42009-12-10 09:41:52 +00007210 return Shadow;
7211}
John McCall604e7f12009-12-08 07:46:18 +00007212
John McCall9f54ad42009-12-10 09:41:52 +00007213/// Hides a using shadow declaration. This is required by the current
7214/// using-decl implementation when a resolvable using declaration in a
7215/// class is followed by a declaration which would hide or override
7216/// one or more of the using decl's targets; for example:
7217///
7218/// struct Base { void foo(int); };
7219/// struct Derived : Base {
7220/// using Base::foo;
7221/// void foo(int);
7222/// };
7223///
7224/// The governing language is C++03 [namespace.udecl]p12:
7225///
7226/// When a using-declaration brings names from a base class into a
7227/// derived class scope, member functions in the derived class
7228/// override and/or hide member functions with the same name and
7229/// parameter types in a base class (rather than conflicting).
7230///
7231/// There are two ways to implement this:
7232/// (1) optimistically create shadow decls when they're not hidden
7233/// by existing declarations, or
7234/// (2) don't create any shadow decls (or at least don't make them
7235/// visible) until we've fully parsed/instantiated the class.
7236/// The problem with (1) is that we might have to retroactively remove
7237/// a shadow decl, which requires several O(n) operations because the
7238/// decl structures are (very reasonably) not designed for removal.
7239/// (2) avoids this but is very fiddly and phase-dependent.
7240void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007241 if (Shadow->getDeclName().getNameKind() ==
7242 DeclarationName::CXXConversionFunctionName)
7243 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7244
John McCall9f54ad42009-12-10 09:41:52 +00007245 // Remove it from the DeclContext...
7246 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007247
John McCall9f54ad42009-12-10 09:41:52 +00007248 // ...and the scope, if applicable...
7249 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007250 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007251 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007252 }
7253
John McCall9f54ad42009-12-10 09:41:52 +00007254 // ...and the using decl.
7255 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7256
7257 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007258 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007259}
7260
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007261namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007262class UsingValidatorCCC : public CorrectionCandidateCallback {
7263public:
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007264 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7265 bool RequireMember)
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007266 : HasTypenameKeyword(HasTypenameKeyword),
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007267 IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007268
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007269 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7270 NamedDecl *ND = Candidate.getCorrectionDecl();
7271
7272 // Keywords are not valid here.
7273 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007274 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007275
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007276 if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7277 !isa<TypeDecl>(ND))
7278 return false;
7279
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007280 // Completely unqualified names are invalid for a 'using' declaration.
7281 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7282 return false;
7283
7284 if (isa<TypeDecl>(ND))
7285 return HasTypenameKeyword || !IsInstantiation;
7286
7287 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007288 }
7289
7290private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007291 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007292 bool IsInstantiation;
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007293 bool RequireMember;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007294};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007295} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007296
John McCall7ba107a2009-11-18 02:36:19 +00007297/// Builds a using declaration.
7298///
7299/// \param IsInstantiation - Whether this call arises from an
7300/// instantiation of an unresolved using declaration. We treat
7301/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007302NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7303 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007304 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007305 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007306 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007307 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007308 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007309 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007310 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007311 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007312 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007313
Anders Carlsson550b14b2009-08-28 05:49:21 +00007314 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007315
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007316 if (SS.isEmpty()) {
7317 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007318 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007319 }
Mike Stump1eb44332009-09-09 15:08:12 +00007320
John McCall9f54ad42009-12-10 09:41:52 +00007321 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007322 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007323 ForRedeclaration);
7324 Previous.setHideTags(false);
7325 if (S) {
7326 LookupName(Previous, S);
7327
7328 // It is really dumb that we have to do this.
7329 LookupResult::Filter F = Previous.makeFilter();
7330 while (F.hasNext()) {
7331 NamedDecl *D = F.next();
7332 if (!isDeclInScope(D, CurContext, S))
7333 F.erase();
7334 }
7335 F.done();
7336 } else {
7337 assert(IsInstantiation && "no scope in non-instantiation");
7338 assert(CurContext->isRecord() && "scope not record in instantiation");
7339 LookupQualifiedName(Previous, CurContext);
7340 }
7341
John McCall9f54ad42009-12-10 09:41:52 +00007342 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007343 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7344 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007345 return 0;
7346
7347 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007348 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7349 return 0;
7350
John McCallaf8e6ed2009-11-12 03:15:40 +00007351 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007352 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007353 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007354 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007355 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007356 // FIXME: not all declaration name kinds are legal here
7357 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7358 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007359 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007360 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007361 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007362 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7363 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007364 }
John McCalled976492009-12-04 22:46:56 +00007365 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007366 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007367 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007368 }
John McCalled976492009-12-04 22:46:56 +00007369 D->setAccess(AS);
7370 CurContext->addDecl(D);
7371
7372 if (!LookupContext) return D;
7373 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007374
John McCall77bb1aa2010-05-01 00:40:08 +00007375 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007376 UD->setInvalidDecl();
7377 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007378 }
7379
Richard Smithc5a89a12012-04-02 01:30:27 +00007380 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007381 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007382 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007383 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007384 return UD;
7385 }
7386
7387 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007388
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007389 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007390
John McCall604e7f12009-12-08 07:46:18 +00007391 // Unlike most lookups, we don't always want to hide tag
7392 // declarations: tag names are visible through the using declaration
7393 // even if hidden by ordinary names, *except* in a dependent context
7394 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007395 if (!IsInstantiation)
7396 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007397
John McCallb9abd8722012-04-07 03:04:20 +00007398 // For the purposes of this lookup, we have a base object type
7399 // equal to that of the current context.
7400 if (CurContext->isRecord()) {
7401 R.setBaseObjectType(
7402 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7403 }
7404
John McCalla24dc2e2009-11-17 02:14:36 +00007405 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007406
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007407 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007408 if (R.empty()) {
Kaelyn Uhrainb5c77682013-10-19 00:05:00 +00007409 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7410 CurContext->isRecord());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007411 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7412 R.getLookupKind(), S, &SS, CCC)){
7413 // We reject any correction for which ND would be NULL.
7414 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007415 R.setLookupName(Corrected.getCorrection());
7416 R.addDecl(ND);
Richard Smith2d670972013-08-17 00:46:16 +00007417 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007418 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007419 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7420 << NameInfo.getName() << LookupContext << 0
7421 << SS.getRange());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007422 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007423 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007424 << NameInfo.getName() << LookupContext << SS.getRange();
7425 UD->setInvalidDecl();
7426 return UD;
7427 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007428 }
7429
John McCalled976492009-12-04 22:46:56 +00007430 if (R.isAmbiguous()) {
7431 UD->setInvalidDecl();
7432 return UD;
7433 }
Mike Stump1eb44332009-09-09 15:08:12 +00007434
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007435 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007436 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007437 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007438 Diag(IdentLoc, diag::err_using_typename_non_type);
7439 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7440 Diag((*I)->getUnderlyingDecl()->getLocation(),
7441 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007442 UD->setInvalidDecl();
7443 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007444 }
7445 } else {
7446 // If we asked for a non-typename and we got a type, error out,
7447 // but only if this is an instantiation of an unresolved using
7448 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007449 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007450 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7451 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007452 UD->setInvalidDecl();
7453 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007454 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007455 }
7456
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007457 // C++0x N2914 [namespace.udecl]p6:
7458 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007459 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007460 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7461 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007462 UD->setInvalidDecl();
7463 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007464 }
Mike Stump1eb44332009-09-09 15:08:12 +00007465
John McCall9f54ad42009-12-10 09:41:52 +00007466 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf06a28932013-10-23 02:17:46 +00007467 UsingShadowDecl *PrevDecl = 0;
7468 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7469 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
John McCall9f54ad42009-12-10 09:41:52 +00007470 }
John McCall9488ea12009-11-17 05:59:44 +00007471
7472 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007473}
7474
Sebastian Redlf677ea32011-02-05 19:23:19 +00007475/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007476bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007477 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007478
Douglas Gregordc355712011-02-25 00:36:19 +00007479 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007480 assert(SourceType &&
7481 "Using decl naming constructor doesn't have type in scope spec.");
7482 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7483
7484 // Check whether the named type is a direct base class.
7485 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7486 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7487 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7488 BaseIt != BaseE; ++BaseIt) {
7489 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7490 if (CanonicalSourceType == BaseType)
7491 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007492 if (BaseIt->getType()->isDependentType())
7493 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007494 }
7495
7496 if (BaseIt == BaseE) {
7497 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007498 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007499 diag::err_using_decl_constructor_not_in_direct_base)
7500 << UD->getNameInfo().getSourceRange()
7501 << QualType(SourceType, 0) << TargetClass;
7502 return true;
7503 }
7504
Richard Smithc5a89a12012-04-02 01:30:27 +00007505 if (!CurContext->isDependentContext())
7506 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007507
7508 return false;
7509}
7510
John McCall9f54ad42009-12-10 09:41:52 +00007511/// Checks that the given using declaration is not an invalid
7512/// redeclaration. Note that this is checking only for the using decl
7513/// itself, not for any ill-formedness among the UsingShadowDecls.
7514bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007515 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007516 const CXXScopeSpec &SS,
7517 SourceLocation NameLoc,
7518 const LookupResult &Prev) {
7519 // C++03 [namespace.udecl]p8:
7520 // C++0x [namespace.udecl]p10:
7521 // A using-declaration is a declaration and can therefore be used
7522 // repeatedly where (and only where) multiple declarations are
7523 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007524 //
John McCall8a726212010-11-29 18:01:58 +00007525 // That's in non-member contexts.
7526 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007527 return false;
7528
7529 NestedNameSpecifier *Qual
7530 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7531
7532 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7533 NamedDecl *D = *I;
7534
7535 bool DTypename;
7536 NestedNameSpecifier *DQual;
7537 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007538 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007539 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007540 } else if (UnresolvedUsingValueDecl *UD
7541 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7542 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007543 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007544 } else if (UnresolvedUsingTypenameDecl *UD
7545 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7546 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007547 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007548 } else continue;
7549
7550 // using decls differ if one says 'typename' and the other doesn't.
7551 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007552 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007553
7554 // using decls differ if they name different scopes (but note that
7555 // template instantiation can cause this check to trigger when it
7556 // didn't before instantiation).
7557 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7558 Context.getCanonicalNestedNameSpecifier(DQual))
7559 continue;
7560
7561 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007562 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007563 return true;
7564 }
7565
7566 return false;
7567}
7568
John McCall604e7f12009-12-08 07:46:18 +00007569
John McCalled976492009-12-04 22:46:56 +00007570/// Checks that the given nested-name qualifier used in a using decl
7571/// in the current context is appropriately related to the current
7572/// scope. If an error is found, diagnoses it and returns true.
7573bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7574 const CXXScopeSpec &SS,
7575 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007576 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007577
John McCall604e7f12009-12-08 07:46:18 +00007578 if (!CurContext->isRecord()) {
7579 // C++03 [namespace.udecl]p3:
7580 // C++0x [namespace.udecl]p8:
7581 // A using-declaration for a class member shall be a member-declaration.
7582
7583 // If we weren't able to compute a valid scope, it must be a
7584 // dependent class scope.
7585 if (!NamedContext || NamedContext->isRecord()) {
7586 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7587 << SS.getRange();
7588 return true;
7589 }
7590
7591 // Otherwise, everything is known to be fine.
7592 return false;
7593 }
7594
7595 // The current scope is a record.
7596
7597 // If the named context is dependent, we can't decide much.
7598 if (!NamedContext) {
7599 // FIXME: in C++0x, we can diagnose if we can prove that the
7600 // nested-name-specifier does not refer to a base class, which is
7601 // still possible in some cases.
7602
7603 // Otherwise we have to conservatively report that things might be
7604 // okay.
7605 return false;
7606 }
7607
7608 if (!NamedContext->isRecord()) {
7609 // Ideally this would point at the last name in the specifier,
7610 // but we don't have that level of source info.
7611 Diag(SS.getRange().getBegin(),
7612 diag::err_using_decl_nested_name_specifier_is_not_class)
7613 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7614 return true;
7615 }
7616
Douglas Gregor6fb07292010-12-21 07:41:49 +00007617 if (!NamedContext->isDependentContext() &&
7618 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7619 return true;
7620
Richard Smith80ad52f2013-01-02 11:42:31 +00007621 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007622 // C++0x [namespace.udecl]p3:
7623 // In a using-declaration used as a member-declaration, the
7624 // nested-name-specifier shall name a base class of the class
7625 // being defined.
7626
7627 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7628 cast<CXXRecordDecl>(NamedContext))) {
7629 if (CurContext == NamedContext) {
7630 Diag(NameLoc,
7631 diag::err_using_decl_nested_name_specifier_is_current_class)
7632 << SS.getRange();
7633 return true;
7634 }
7635
7636 Diag(SS.getRange().getBegin(),
7637 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7638 << (NestedNameSpecifier*) SS.getScopeRep()
7639 << cast<CXXRecordDecl>(CurContext)
7640 << SS.getRange();
7641 return true;
7642 }
7643
7644 return false;
7645 }
7646
7647 // C++03 [namespace.udecl]p4:
7648 // A using-declaration used as a member-declaration shall refer
7649 // to a member of a base class of the class being defined [etc.].
7650
7651 // Salient point: SS doesn't have to name a base class as long as
7652 // lookup only finds members from base classes. Therefore we can
7653 // diagnose here only if we can prove that that can't happen,
7654 // i.e. if the class hierarchies provably don't intersect.
7655
7656 // TODO: it would be nice if "definitely valid" results were cached
7657 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7658 // need to be repeated.
7659
7660 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007661 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007662
7663 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7664 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7665 Data->Bases.insert(Base);
7666 return true;
7667 }
7668
7669 bool hasDependentBases(const CXXRecordDecl *Class) {
7670 return !Class->forallBases(collect, this);
7671 }
7672
7673 /// Returns true if the base is dependent or is one of the
7674 /// accumulated base classes.
7675 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7676 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7677 return !Data->Bases.count(Base);
7678 }
7679
7680 bool mightShareBases(const CXXRecordDecl *Class) {
7681 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7682 }
7683 };
7684
7685 UserData Data;
7686
7687 // Returns false if we find a dependent base.
7688 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7689 return false;
7690
7691 // Returns false if the class has a dependent base or if it or one
7692 // of its bases is present in the base set of the current context.
7693 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7694 return false;
7695
7696 Diag(SS.getRange().getBegin(),
7697 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7698 << (NestedNameSpecifier*) SS.getScopeRep()
7699 << cast<CXXRecordDecl>(CurContext)
7700 << SS.getRange();
7701
7702 return true;
John McCalled976492009-12-04 22:46:56 +00007703}
7704
Richard Smith162e1c12011-04-15 14:24:37 +00007705Decl *Sema::ActOnAliasDeclaration(Scope *S,
7706 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007707 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007708 SourceLocation UsingLoc,
7709 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007710 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007711 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007712 // Skip up to the relevant declaration scope.
7713 while (S->getFlags() & Scope::TemplateParamScope)
7714 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007715 assert((S->getFlags() & Scope::DeclScope) &&
7716 "got alias-declaration outside of declaration scope");
7717
7718 if (Type.isInvalid())
7719 return 0;
7720
7721 bool Invalid = false;
7722 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7723 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007724 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007725
7726 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7727 return 0;
7728
7729 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007730 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007731 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007732 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7733 TInfo->getTypeLoc().getBeginLoc());
7734 }
Richard Smith162e1c12011-04-15 14:24:37 +00007735
7736 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7737 LookupName(Previous, S);
7738
7739 // Warn about shadowing the name of a template parameter.
7740 if (Previous.isSingleResult() &&
7741 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007742 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007743 Previous.clear();
7744 }
7745
7746 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7747 "name in alias declaration must be an identifier");
7748 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7749 Name.StartLocation,
7750 Name.Identifier, TInfo);
7751
7752 NewTD->setAccess(AS);
7753
7754 if (Invalid)
7755 NewTD->setInvalidDecl();
7756
Richard Smith6b3d3e52013-02-20 19:22:51 +00007757 ProcessDeclAttributeList(S, NewTD, AttrList);
7758
Richard Smith3e4c6c42011-05-05 21:57:07 +00007759 CheckTypedefForVariablyModifiedType(S, NewTD);
7760 Invalid |= NewTD->isInvalidDecl();
7761
Richard Smith162e1c12011-04-15 14:24:37 +00007762 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007763
7764 NamedDecl *NewND;
7765 if (TemplateParamLists.size()) {
7766 TypeAliasTemplateDecl *OldDecl = 0;
7767 TemplateParameterList *OldTemplateParams = 0;
7768
7769 if (TemplateParamLists.size() != 1) {
7770 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007771 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7772 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007773 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007774 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007775
7776 // Only consider previous declarations in the same scope.
7777 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7778 /*ExplicitInstantiationOrSpecialization*/false);
7779 if (!Previous.empty()) {
7780 Redeclaration = true;
7781
7782 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7783 if (!OldDecl && !Invalid) {
7784 Diag(UsingLoc, diag::err_redefinition_different_kind)
7785 << Name.Identifier;
7786
7787 NamedDecl *OldD = Previous.getRepresentativeDecl();
7788 if (OldD->getLocation().isValid())
7789 Diag(OldD->getLocation(), diag::note_previous_definition);
7790
7791 Invalid = true;
7792 }
7793
7794 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7795 if (TemplateParameterListsAreEqual(TemplateParams,
7796 OldDecl->getTemplateParameters(),
7797 /*Complain=*/true,
7798 TPL_TemplateMatch))
7799 OldTemplateParams = OldDecl->getTemplateParameters();
7800 else
7801 Invalid = true;
7802
7803 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7804 if (!Invalid &&
7805 !Context.hasSameType(OldTD->getUnderlyingType(),
7806 NewTD->getUnderlyingType())) {
7807 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7808 // but we can't reasonably accept it.
7809 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7810 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7811 if (OldTD->getLocation().isValid())
7812 Diag(OldTD->getLocation(), diag::note_previous_definition);
7813 Invalid = true;
7814 }
7815 }
7816 }
7817
7818 // Merge any previous default template arguments into our parameters,
7819 // and check the parameter list.
7820 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7821 TPC_TypeAliasTemplate))
7822 return 0;
7823
7824 TypeAliasTemplateDecl *NewDecl =
7825 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7826 Name.Identifier, TemplateParams,
7827 NewTD);
7828
7829 NewDecl->setAccess(AS);
7830
7831 if (Invalid)
7832 NewDecl->setInvalidDecl();
7833 else if (OldDecl)
Rafael Espindolabc650912013-10-17 15:37:26 +00007834 NewDecl->setPreviousDecl(OldDecl);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007835
7836 NewND = NewDecl;
7837 } else {
7838 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7839 NewND = NewTD;
7840 }
Richard Smith162e1c12011-04-15 14:24:37 +00007841
7842 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007843 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007844
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007845 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007846 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007847}
7848
John McCalld226f652010-08-21 09:40:31 +00007849Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007850 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007851 SourceLocation AliasLoc,
7852 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007853 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007854 SourceLocation IdentLoc,
7855 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007856
Anders Carlsson81c85c42009-03-28 23:53:49 +00007857 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007858 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7859 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007860
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007861 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007862 NamedDecl *PrevDecl
7863 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7864 ForRedeclaration);
7865 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7866 PrevDecl = 0;
7867
7868 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007869 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007870 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007871 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007872 // FIXME: At some point, we'll want to create the (redundant)
7873 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007874 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007875 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007876 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007877 }
Mike Stump1eb44332009-09-09 15:08:12 +00007878
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007879 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7880 diag::err_redefinition_different_kind;
7881 Diag(AliasLoc, DiagID) << Alias;
7882 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007883 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007884 }
7885
John McCalla24dc2e2009-11-17 02:14:36 +00007886 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007887 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007888
John McCallf36e02d2009-10-09 21:13:30 +00007889 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007890 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007891 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007892 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007893 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007894 }
Mike Stump1eb44332009-09-09 15:08:12 +00007895
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007896 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007897 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007898 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007899 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007900
John McCall3dbd3d52010-02-16 06:53:13 +00007901 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007902 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007903}
7904
Sean Hunt001cad92011-05-10 00:49:42 +00007905Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007906Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7907 CXXMethodDecl *MD) {
7908 CXXRecordDecl *ClassDecl = MD->getParent();
7909
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007910 // C++ [except.spec]p14:
7911 // An implicitly declared special member function (Clause 12) shall have an
7912 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007913 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007914 if (ClassDecl->isInvalidDecl())
7915 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007916
Sebastian Redl60618fa2011-03-12 11:50:43 +00007917 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007918 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7919 BEnd = ClassDecl->bases_end();
7920 B != BEnd; ++B) {
7921 if (B->isVirtual()) // Handled below.
7922 continue;
7923
Douglas Gregor18274032010-07-03 00:47:00 +00007924 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7925 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007926 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7927 // If this is a deleted function, add it anyway. This might be conformant
7928 // with the standard. This might not. I'm not sure. It might not matter.
7929 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007930 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007931 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007932 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007933
7934 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007935 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7936 BEnd = ClassDecl->vbases_end();
7937 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007938 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7939 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007940 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7941 // If this is a deleted function, add it anyway. This might be conformant
7942 // with the standard. This might not. I'm not sure. It might not matter.
7943 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007944 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007945 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007946 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007947
7948 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007949 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7950 FEnd = ClassDecl->field_end();
7951 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007952 if (F->hasInClassInitializer()) {
7953 if (Expr *E = F->getInClassInitializer())
7954 ExceptSpec.CalledExpr(E);
7955 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007956 // DR1351:
7957 // If the brace-or-equal-initializer of a non-static data member
7958 // invokes a defaulted default constructor of its class or of an
7959 // enclosing class in a potentially evaluated subexpression, the
7960 // program is ill-formed.
7961 //
7962 // This resolution is unworkable: the exception specification of the
7963 // default constructor can be needed in an unevaluated context, in
7964 // particular, in the operand of a noexcept-expression, and we can be
7965 // unable to compute an exception specification for an enclosed class.
7966 //
7967 // We do not allow an in-class initializer to require the evaluation
7968 // of the exception specification for any in-class initializer whose
7969 // definition is not lexically complete.
7970 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007971 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007972 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007973 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7974 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7975 // If this is a deleted function, add it anyway. This might be conformant
7976 // with the standard. This might not. I'm not sure. It might not matter.
7977 // In particular, the problem is that this function never gets called. It
7978 // might just be ill-formed because this function attempts to refer to
7979 // a deleted function here.
7980 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007981 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007982 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007983 }
John McCalle23cf432010-12-14 08:05:40 +00007984
Sean Hunt001cad92011-05-10 00:49:42 +00007985 return ExceptSpec;
7986}
7987
Richard Smith07b0fdc2013-03-18 21:12:30 +00007988Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007989Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7990 CXXRecordDecl *ClassDecl = CD->getParent();
7991
7992 // C++ [except.spec]p14:
7993 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007994 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007995 if (ClassDecl->isInvalidDecl())
7996 return ExceptSpec;
7997
7998 // Inherited constructor.
7999 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8000 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8001 // FIXME: Copying or moving the parameters could add extra exceptions to the
8002 // set, as could the default arguments for the inherited constructor. This
8003 // will be addressed when we implement the resolution of core issue 1351.
8004 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8005
8006 // Direct base-class constructors.
8007 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8008 BEnd = ClassDecl->bases_end();
8009 B != BEnd; ++B) {
8010 if (B->isVirtual()) // Handled below.
8011 continue;
8012
8013 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8014 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8015 if (BaseClassDecl == InheritedDecl)
8016 continue;
8017 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8018 if (Constructor)
8019 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8020 }
8021 }
8022
8023 // Virtual base-class constructors.
8024 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8025 BEnd = ClassDecl->vbases_end();
8026 B != BEnd; ++B) {
8027 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8028 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8029 if (BaseClassDecl == InheritedDecl)
8030 continue;
8031 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8032 if (Constructor)
8033 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8034 }
8035 }
8036
8037 // Field constructors.
8038 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8039 FEnd = ClassDecl->field_end();
8040 F != FEnd; ++F) {
8041 if (F->hasInClassInitializer()) {
8042 if (Expr *E = F->getInClassInitializer())
8043 ExceptSpec.CalledExpr(E);
8044 else if (!F->isInvalidDecl())
8045 Diag(CD->getLocation(),
8046 diag::err_in_class_initializer_references_def_ctor) << CD;
8047 } else if (const RecordType *RecordTy
8048 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8049 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8050 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8051 if (Constructor)
8052 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8053 }
8054 }
8055
Richard Smith07b0fdc2013-03-18 21:12:30 +00008056 return ExceptSpec;
8057}
8058
Richard Smithafb49182012-11-29 01:34:07 +00008059namespace {
8060/// RAII object to register a special member as being currently declared.
8061struct DeclaringSpecialMember {
8062 Sema &S;
8063 Sema::SpecialMemberDecl D;
8064 bool WasAlreadyBeingDeclared;
8065
8066 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8067 : S(S), D(RD, CSM) {
8068 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8069 if (WasAlreadyBeingDeclared)
8070 // This almost never happens, but if it does, ensure that our cache
8071 // doesn't contain a stale result.
8072 S.SpecialMemberCache.clear();
8073
8074 // FIXME: Register a note to be produced if we encounter an error while
8075 // declaring the special member.
8076 }
8077 ~DeclaringSpecialMember() {
8078 if (!WasAlreadyBeingDeclared)
8079 S.SpecialMembersBeingDeclared.erase(D);
8080 }
8081
8082 /// \brief Are we already trying to declare this special member?
8083 bool isAlreadyBeingDeclared() const {
8084 return WasAlreadyBeingDeclared;
8085 }
8086};
8087}
8088
Sean Hunt001cad92011-05-10 00:49:42 +00008089CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8090 CXXRecordDecl *ClassDecl) {
8091 // C++ [class.ctor]p5:
8092 // A default constructor for a class X is a constructor of class X
8093 // that can be called without an argument. If there is no
8094 // user-declared constructor for class X, a default constructor is
8095 // implicitly declared. An implicitly-declared default constructor
8096 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00008097 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00008098 "Should not build implicit default constructor!");
8099
Richard Smithafb49182012-11-29 01:34:07 +00008100 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8101 if (DSM.isAlreadyBeingDeclared())
8102 return 0;
8103
Richard Smith7756afa2012-06-10 05:43:50 +00008104 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8105 CXXDefaultConstructor,
8106 false);
8107
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008108 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00008109 CanQualType ClassType
8110 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008111 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008112 DeclarationName Name
8113 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008114 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00008115 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008116 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008117 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008118 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00008119 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00008120 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008121 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008122
8123 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008124 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008125 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008126
Richard Smithbc2a35d2012-12-08 08:32:28 +00008127 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8128 // constructors is easy to compute.
8129 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8130
8131 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008132 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008133
Douglas Gregor18274032010-07-03 00:47:00 +00008134 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00008135 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00008136
Douglas Gregor23c94db2010-07-02 17:43:08 +00008137 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00008138 PushOnScopeChains(DefaultCon, S, false);
8139 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00008140
Douglas Gregor32df23e2010-07-01 22:02:46 +00008141 return DefaultCon;
8142}
8143
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008144void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8145 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00008146 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008147 !Constructor->doesThisDeclarationHaveABody() &&
8148 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00008149 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008150
Anders Carlssonf6513ed2010-04-23 16:04:08 +00008151 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00008152 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00008153
Eli Friedman9a14db32012-10-18 20:14:08 +00008154 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008155 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00008156 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008157 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008158 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00008159 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00008160 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008161 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00008162 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008163
8164 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008165 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008166
Eli Friedman86164e82013-09-05 00:02:25 +00008167 Constructor->markUsed(Context);
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008168 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008169
8170 if (ASTMutationListener *L = getASTMutationListener()) {
8171 L->CompletedImplicitDefinition(Constructor);
8172 }
Richard Trieu858d2ba2013-10-25 00:56:00 +00008173
8174 DiagnoseUninitializedFields(*this, Constructor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008175}
8176
Richard Smith7a614d82011-06-11 17:19:42 +00008177void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Alp Toker08235662013-10-18 05:54:19 +00008178 // Perform any delayed checks on exception specifications.
8179 CheckDelayedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00008180}
8181
Richard Smith4841ca52013-04-10 05:48:59 +00008182namespace {
8183/// Information on inheriting constructors to declare.
8184class InheritingConstructorInfo {
8185public:
8186 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8187 : SemaRef(SemaRef), Derived(Derived) {
8188 // Mark the constructors that we already have in the derived class.
8189 //
8190 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8191 // unless there is a user-declared constructor with the same signature in
8192 // the class where the using-declaration appears.
8193 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8194 }
8195
8196 void inheritAll(CXXRecordDecl *RD) {
8197 visitAll(RD, &InheritingConstructorInfo::inherit);
8198 }
8199
8200private:
8201 /// Information about an inheriting constructor.
8202 struct InheritingConstructor {
8203 InheritingConstructor()
8204 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8205
8206 /// If \c true, a constructor with this signature is already declared
8207 /// in the derived class.
8208 bool DeclaredInDerived;
8209
8210 /// The constructor which is inherited.
8211 const CXXConstructorDecl *BaseCtor;
8212
8213 /// The derived constructor we declared.
8214 CXXConstructorDecl *DerivedCtor;
8215 };
8216
8217 /// Inheriting constructors with a given canonical type. There can be at
8218 /// most one such non-template constructor, and any number of templated
8219 /// constructors.
8220 struct InheritingConstructorsForType {
8221 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008222 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8223 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008224
8225 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8226 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8227 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8228 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8229 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8230 false, S.TPL_TemplateMatch))
8231 return Templates[I].second;
8232 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8233 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008234 }
Richard Smith4841ca52013-04-10 05:48:59 +00008235
8236 return NonTemplate;
8237 }
8238 };
8239
8240 /// Get or create the inheriting constructor record for a constructor.
8241 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8242 QualType CtorType) {
8243 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8244 .getEntry(SemaRef, Ctor);
8245 }
8246
8247 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8248
8249 /// Process all constructors for a class.
8250 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8251 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8252 CtorE = RD->ctor_end();
8253 CtorIt != CtorE; ++CtorIt)
8254 (this->*Callback)(*CtorIt);
8255 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8256 I(RD->decls_begin()), E(RD->decls_end());
8257 I != E; ++I) {
8258 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8259 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8260 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008261 }
8262 }
Richard Smith4841ca52013-04-10 05:48:59 +00008263
8264 /// Note that a constructor (or constructor template) was declared in Derived.
8265 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8266 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8267 }
8268
8269 /// Inherit a single constructor.
8270 void inherit(const CXXConstructorDecl *Ctor) {
8271 const FunctionProtoType *CtorType =
8272 Ctor->getType()->castAs<FunctionProtoType>();
8273 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8274 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8275
8276 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8277
8278 // Core issue (no number yet): the ellipsis is always discarded.
8279 if (EPI.Variadic) {
8280 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8281 SemaRef.Diag(Ctor->getLocation(),
8282 diag::note_using_decl_constructor_ellipsis);
8283 EPI.Variadic = false;
8284 }
8285
8286 // Declare a constructor for each number of parameters.
8287 //
8288 // C++11 [class.inhctor]p1:
8289 // The candidate set of inherited constructors from the class X named in
8290 // the using-declaration consists of [... modulo defects ...] for each
8291 // constructor or constructor template of X, the set of constructors or
8292 // constructor templates that results from omitting any ellipsis parameter
8293 // specification and successively omitting parameters with a default
8294 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008295 unsigned MinParams = minParamsToInherit(Ctor);
8296 unsigned Params = Ctor->getNumParams();
8297 if (Params >= MinParams) {
8298 do
8299 declareCtor(UsingLoc, Ctor,
8300 SemaRef.Context.getFunctionType(
8301 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8302 while (Params > MinParams &&
8303 Ctor->getParamDecl(--Params)->hasDefaultArg());
8304 }
Richard Smith4841ca52013-04-10 05:48:59 +00008305 }
8306
8307 /// Find the using-declaration which specified that we should inherit the
8308 /// constructors of \p Base.
8309 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8310 // No fancy lookup required; just look for the base constructor name
8311 // directly within the derived class.
8312 ASTContext &Context = SemaRef.Context;
8313 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8314 Context.getCanonicalType(Context.getRecordType(Base)));
8315 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8316 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8317 }
8318
8319 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8320 // C++11 [class.inhctor]p3:
8321 // [F]or each constructor template in the candidate set of inherited
8322 // constructors, a constructor template is implicitly declared
8323 if (Ctor->getDescribedFunctionTemplate())
8324 return 0;
8325
8326 // For each non-template constructor in the candidate set of inherited
8327 // constructors other than a constructor having no parameters or a
8328 // copy/move constructor having a single parameter, a constructor is
8329 // implicitly declared [...]
8330 if (Ctor->getNumParams() == 0)
8331 return 1;
8332 if (Ctor->isCopyOrMoveConstructor())
8333 return 2;
8334
8335 // Per discussion on core reflector, never inherit a constructor which
8336 // would become a default, copy, or move constructor of Derived either.
8337 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8338 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8339 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8340 }
8341
8342 /// Declare a single inheriting constructor, inheriting the specified
8343 /// constructor, with the given type.
8344 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8345 QualType DerivedType) {
8346 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8347
8348 // C++11 [class.inhctor]p3:
8349 // ... a constructor is implicitly declared with the same constructor
8350 // characteristics unless there is a user-declared constructor with
8351 // the same signature in the class where the using-declaration appears
8352 if (Entry.DeclaredInDerived)
8353 return;
8354
8355 // C++11 [class.inhctor]p7:
8356 // If two using-declarations declare inheriting constructors with the
8357 // same signature, the program is ill-formed
8358 if (Entry.DerivedCtor) {
8359 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8360 // Only diagnose this once per constructor.
8361 if (Entry.DerivedCtor->isInvalidDecl())
8362 return;
8363 Entry.DerivedCtor->setInvalidDecl();
8364
8365 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8366 SemaRef.Diag(BaseCtor->getLocation(),
8367 diag::note_using_decl_constructor_conflict_current_ctor);
8368 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8369 diag::note_using_decl_constructor_conflict_previous_ctor);
8370 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8371 diag::note_using_decl_constructor_conflict_previous_using);
8372 } else {
8373 // Core issue (no number): if the same inheriting constructor is
8374 // produced by multiple base class constructors from the same base
8375 // class, the inheriting constructor is defined as deleted.
8376 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8377 }
8378
8379 return;
8380 }
8381
8382 ASTContext &Context = SemaRef.Context;
8383 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8384 Context.getCanonicalType(Context.getRecordType(Derived)));
8385 DeclarationNameInfo NameInfo(Name, UsingLoc);
8386
8387 TemplateParameterList *TemplateParams = 0;
8388 if (const FunctionTemplateDecl *FTD =
8389 BaseCtor->getDescribedFunctionTemplate()) {
8390 TemplateParams = FTD->getTemplateParameters();
8391 // We're reusing template parameters from a different DeclContext. This
8392 // is questionable at best, but works out because the template depth in
8393 // both places is guaranteed to be 0.
8394 // FIXME: Rebuild the template parameters in the new context, and
8395 // transform the function type to refer to them.
8396 }
8397
8398 // Build type source info pointing at the using-declaration. This is
8399 // required by template instantiation.
8400 TypeSourceInfo *TInfo =
8401 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8402 FunctionProtoTypeLoc ProtoLoc =
8403 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8404
8405 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8406 Context, Derived, UsingLoc, NameInfo, DerivedType,
8407 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8408 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8409
8410 // Build an unevaluated exception specification for this constructor.
8411 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8412 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8413 EPI.ExceptionSpecType = EST_Unevaluated;
8414 EPI.ExceptionSpecDecl = DerivedCtor;
8415 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8416 FPT->getArgTypes(), EPI));
8417
8418 // Build the parameter declarations.
8419 SmallVector<ParmVarDecl *, 16> ParamDecls;
8420 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8421 TypeSourceInfo *TInfo =
8422 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8423 ParmVarDecl *PD = ParmVarDecl::Create(
8424 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8425 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8426 PD->setScopeInfo(0, I);
8427 PD->setImplicit();
8428 ParamDecls.push_back(PD);
8429 ProtoLoc.setArg(I, PD);
8430 }
8431
8432 // Set up the new constructor.
8433 DerivedCtor->setAccess(BaseCtor->getAccess());
8434 DerivedCtor->setParams(ParamDecls);
8435 DerivedCtor->setInheritedConstructor(BaseCtor);
8436 if (BaseCtor->isDeleted())
8437 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8438
8439 // If this is a constructor template, build the template declaration.
8440 if (TemplateParams) {
8441 FunctionTemplateDecl *DerivedTemplate =
8442 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8443 TemplateParams, DerivedCtor);
8444 DerivedTemplate->setAccess(BaseCtor->getAccess());
8445 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8446 Derived->addDecl(DerivedTemplate);
8447 } else {
8448 Derived->addDecl(DerivedCtor);
8449 }
8450
8451 Entry.BaseCtor = BaseCtor;
8452 Entry.DerivedCtor = DerivedCtor;
8453 }
8454
8455 Sema &SemaRef;
8456 CXXRecordDecl *Derived;
8457 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8458 MapType Map;
8459};
8460}
8461
8462void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8463 // Defer declaring the inheriting constructors until the class is
8464 // instantiated.
8465 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008466 return;
8467
Richard Smith4841ca52013-04-10 05:48:59 +00008468 // Find base classes from which we might inherit constructors.
8469 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8470 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8471 BaseE = ClassDecl->bases_end();
8472 BaseIt != BaseE; ++BaseIt)
8473 if (BaseIt->getInheritConstructors())
8474 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008475
Richard Smith4841ca52013-04-10 05:48:59 +00008476 // Go no further if we're not inheriting any constructors.
8477 if (InheritedBases.empty())
8478 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008479
Richard Smith4841ca52013-04-10 05:48:59 +00008480 // Declare the inherited constructors.
8481 InheritingConstructorInfo ICI(*this, ClassDecl);
8482 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8483 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008484}
8485
Richard Smith07b0fdc2013-03-18 21:12:30 +00008486void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8487 CXXConstructorDecl *Constructor) {
8488 CXXRecordDecl *ClassDecl = Constructor->getParent();
8489 assert(Constructor->getInheritedConstructor() &&
8490 !Constructor->doesThisDeclarationHaveABody() &&
8491 !Constructor->isDeleted());
8492
8493 SynthesizedFunctionScope Scope(*this, Constructor);
8494 DiagnosticErrorTrap Trap(Diags);
8495 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8496 Trap.hasErrorOccurred()) {
8497 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8498 << Context.getTagDeclType(ClassDecl);
8499 Constructor->setInvalidDecl();
8500 return;
8501 }
8502
8503 SourceLocation Loc = Constructor->getLocation();
8504 Constructor->setBody(new (Context) CompoundStmt(Loc));
8505
Eli Friedman86164e82013-09-05 00:02:25 +00008506 Constructor->markUsed(Context);
Richard Smith07b0fdc2013-03-18 21:12:30 +00008507 MarkVTableUsed(CurrentLocation, ClassDecl);
8508
8509 if (ASTMutationListener *L = getASTMutationListener()) {
8510 L->CompletedImplicitDefinition(Constructor);
8511 }
8512}
8513
8514
Sean Huntcb45a0f2011-05-12 22:46:25 +00008515Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008516Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8517 CXXRecordDecl *ClassDecl = MD->getParent();
8518
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008519 // C++ [except.spec]p14:
8520 // An implicitly declared special member function (Clause 12) shall have
8521 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008522 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008523 if (ClassDecl->isInvalidDecl())
8524 return ExceptSpec;
8525
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008526 // Direct base-class destructors.
8527 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8528 BEnd = ClassDecl->bases_end();
8529 B != BEnd; ++B) {
8530 if (B->isVirtual()) // Handled below.
8531 continue;
8532
8533 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008534 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008535 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008536 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008537
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008538 // Virtual base-class destructors.
8539 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8540 BEnd = ClassDecl->vbases_end();
8541 B != BEnd; ++B) {
8542 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008543 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008544 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008545 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008546
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008547 // Field destructors.
8548 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8549 FEnd = ClassDecl->field_end();
8550 F != FEnd; ++F) {
8551 if (const RecordType *RecordTy
8552 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008553 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008554 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008555 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008556
Sean Huntcb45a0f2011-05-12 22:46:25 +00008557 return ExceptSpec;
8558}
8559
8560CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8561 // C++ [class.dtor]p2:
8562 // If a class has no user-declared destructor, a destructor is
8563 // declared implicitly. An implicitly-declared destructor is an
8564 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008565 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008566
Richard Smithafb49182012-11-29 01:34:07 +00008567 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8568 if (DSM.isAlreadyBeingDeclared())
8569 return 0;
8570
Douglas Gregor4923aa22010-07-02 20:37:36 +00008571 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008572 CanQualType ClassType
8573 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008574 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008575 DeclarationName Name
8576 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008577 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008578 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008579 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8580 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008581 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008582 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008583 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008584 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008585
8586 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008587 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008588 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008589
Richard Smithbc2a35d2012-12-08 08:32:28 +00008590 AddOverriddenMethods(ClassDecl, Destructor);
8591
8592 // We don't need to use SpecialMemberIsTrivial here; triviality for
8593 // destructors is easy to compute.
8594 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8595
8596 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008597 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008598
Douglas Gregor4923aa22010-07-02 20:37:36 +00008599 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008600 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008601
Douglas Gregor4923aa22010-07-02 20:37:36 +00008602 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008603 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008604 PushOnScopeChains(Destructor, S, false);
8605 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008606
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008607 return Destructor;
8608}
8609
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008610void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008611 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008612 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008613 !Destructor->doesThisDeclarationHaveABody() &&
8614 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008615 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008616 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008617 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008618
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008619 if (Destructor->isInvalidDecl())
8620 return;
8621
Eli Friedman9a14db32012-10-18 20:14:08 +00008622 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008623
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008624 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008625 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8626 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008627
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008628 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008629 Diag(CurrentLocation, diag::note_member_synthesized_at)
8630 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8631
8632 Destructor->setInvalidDecl();
8633 return;
8634 }
8635
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008636 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008637 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman86164e82013-09-05 00:02:25 +00008638 Destructor->markUsed(Context);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008639 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008640
8641 if (ASTMutationListener *L = getASTMutationListener()) {
8642 L->CompletedImplicitDefinition(Destructor);
8643 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008644}
8645
Richard Smitha4156b82012-04-21 18:42:51 +00008646/// \brief Perform any semantic analysis which needs to be delayed until all
8647/// pending class member declarations have been parsed.
8648void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008649 // If the context is an invalid C++ class, just suppress these checks.
8650 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8651 if (Record->isInvalidDecl()) {
Alp Toker08235662013-10-18 05:54:19 +00008652 DelayedDefaultedMemberExceptionSpecs.clear();
Douglas Gregor10318842013-02-01 04:49:10 +00008653 DelayedDestructorExceptionSpecChecks.clear();
8654 return;
8655 }
8656 }
Richard Smitha4156b82012-04-21 18:42:51 +00008657}
8658
Richard Smithb9d0b762012-07-27 04:22:15 +00008659void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8660 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008661 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008662 "adjusting dtor exception specs was introduced in c++11");
8663
Sebastian Redl0ee33912011-05-19 05:13:44 +00008664 // C++11 [class.dtor]p3:
8665 // A declaration of a destructor that does not have an exception-
8666 // specification is implicitly considered to have the same exception-
8667 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008668 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008669 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008670 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008671 return;
8672
Chandler Carruth3f224b22011-09-20 04:55:26 +00008673 // Replace the destructor's type, building off the existing one. Fortunately,
8674 // the only thing of interest in the destructor type is its extended info.
8675 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008676 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8677 EPI.ExceptionSpecType = EST_Unevaluated;
8678 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008679 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008680
Sebastian Redl0ee33912011-05-19 05:13:44 +00008681 // FIXME: If the destructor has a body that could throw, and the newly created
8682 // spec doesn't allow exceptions, we should emit a warning, because this
8683 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008684 // However, we don't have a body or an exception specification yet, so it
8685 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008686}
8687
Pavel Labath66ea35d2013-08-30 08:52:28 +00008688namespace {
8689/// \brief An abstract base class for all helper classes used in building the
8690// copy/move operators. These classes serve as factory functions and help us
8691// avoid using the same Expr* in the AST twice.
8692class ExprBuilder {
8693 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8694 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8695
8696protected:
8697 static Expr *assertNotNull(Expr *E) {
8698 assert(E && "Expression construction must not fail.");
8699 return E;
8700 }
8701
8702public:
8703 ExprBuilder() {}
8704 virtual ~ExprBuilder() {}
8705
8706 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8707};
8708
8709class RefBuilder: public ExprBuilder {
8710 VarDecl *Var;
8711 QualType VarType;
8712
8713public:
8714 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8715 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8716 }
8717
8718 RefBuilder(VarDecl *Var, QualType VarType)
8719 : Var(Var), VarType(VarType) {}
8720};
8721
8722class ThisBuilder: public ExprBuilder {
8723public:
8724 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8725 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8726 }
8727};
8728
8729class CastBuilder: public ExprBuilder {
8730 const ExprBuilder &Builder;
8731 QualType Type;
8732 ExprValueKind Kind;
8733 const CXXCastPath &Path;
8734
8735public:
8736 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8737 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8738 CK_UncheckedDerivedToBase, Kind,
8739 &Path).take());
8740 }
8741
8742 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8743 const CXXCastPath &Path)
8744 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8745};
8746
8747class DerefBuilder: public ExprBuilder {
8748 const ExprBuilder &Builder;
8749
8750public:
8751 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8752 return assertNotNull(
8753 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8754 }
8755
8756 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8757};
8758
8759class MemberBuilder: public ExprBuilder {
8760 const ExprBuilder &Builder;
8761 QualType Type;
8762 CXXScopeSpec SS;
8763 bool IsArrow;
8764 LookupResult &MemberLookup;
8765
8766public:
8767 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8768 return assertNotNull(S.BuildMemberReferenceExpr(
8769 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8770 MemberLookup, 0).take());
8771 }
8772
8773 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8774 LookupResult &MemberLookup)
8775 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8776 MemberLookup(MemberLookup) {}
8777};
8778
8779class MoveCastBuilder: public ExprBuilder {
8780 const ExprBuilder &Builder;
8781
8782public:
8783 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8784 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8785 }
8786
8787 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8788};
8789
8790class LvalueConvBuilder: public ExprBuilder {
8791 const ExprBuilder &Builder;
8792
8793public:
8794 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8795 return assertNotNull(
8796 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8797 }
8798
8799 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8800};
8801
8802class SubscriptBuilder: public ExprBuilder {
8803 const ExprBuilder &Base;
8804 const ExprBuilder &Index;
8805
8806public:
8807 virtual Expr *build(Sema &S, SourceLocation Loc) const
8808 LLVM_OVERRIDE {
8809 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8810 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8811 }
8812
8813 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8814 : Base(Base), Index(Index) {}
8815};
8816
8817} // end anonymous namespace
8818
Richard Smith8c889532012-11-14 00:50:40 +00008819/// When generating a defaulted copy or move assignment operator, if a field
8820/// should be copied with __builtin_memcpy rather than via explicit assignments,
8821/// do so. This optimization only applies for arrays of scalars, and for arrays
8822/// of class type where the selected copy/move-assignment operator is trivial.
8823static StmtResult
8824buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008825 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00008826 // Compute the size of the memory buffer to be copied.
8827 QualType SizeType = S.Context.getSizeType();
8828 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8829 S.Context.getTypeSizeInChars(T).getQuantity());
8830
8831 // Take the address of the field references for "from" and "to". We
8832 // directly construct UnaryOperators here because semantic analysis
8833 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008834 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008835 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8836 S.Context.getPointerType(From->getType()),
8837 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00008838 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008839 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8840 S.Context.getPointerType(To->getType()),
8841 VK_RValue, OK_Ordinary, Loc);
8842
8843 const Type *E = T->getBaseElementTypeUnsafe();
8844 bool NeedsCollectableMemCpy =
8845 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8846
8847 // Create a reference to the __builtin_objc_memmove_collectable function
8848 StringRef MemCpyName = NeedsCollectableMemCpy ?
8849 "__builtin_objc_memmove_collectable" :
8850 "__builtin_memcpy";
8851 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8852 Sema::LookupOrdinaryName);
8853 S.LookupName(R, S.TUScope, true);
8854
8855 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8856 if (!MemCpy)
8857 // Something went horribly wrong earlier, and we will have complained
8858 // about it.
8859 return StmtError();
8860
8861 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8862 VK_RValue, Loc, 0);
8863 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8864
8865 Expr *CallArgs[] = {
8866 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8867 };
8868 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8869 Loc, CallArgs, Loc);
8870
8871 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8872 return S.Owned(Call.takeAs<Stmt>());
8873}
8874
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008875/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008876/// \c To.
8877///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008878/// This routine is used to copy/move the members of a class with an
8879/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008880/// copied are arrays, this routine builds for loops to copy them.
8881///
8882/// \param S The Sema object used for type-checking.
8883///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008884/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008885///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008886/// \param T The type of the expressions being copied/moved. Both expressions
8887/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008888///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008889/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008890///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008891/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008892///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008893/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008894/// Otherwise, it's a non-static member subobject.
8895///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008896/// \param Copying Whether we're copying or moving.
8897///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008898/// \param Depth Internal parameter recording the depth of the recursion.
8899///
Richard Smith8c889532012-11-14 00:50:40 +00008900/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8901/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008902static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008903buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008904 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008905 bool CopyingBaseSubobject, bool Copying,
8906 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008907 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008908 // Each subobject is assigned in the manner appropriate to its type:
8909 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008910 // - if the subobject is of class type, as if by a call to operator= with
8911 // the subobject as the object expression and the corresponding
8912 // subobject of x as a single function argument (as if by explicit
8913 // qualification; that is, ignoring any possible virtual overriding
8914 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008915 //
8916 // C++03 [class.copy]p13:
8917 // - if the subobject is of class type, the copy assignment operator for
8918 // the class is used (as if by explicit qualification; that is,
8919 // ignoring any possible virtual overriding functions in more derived
8920 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008921 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8922 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008923
Douglas Gregor06a9f362010-05-01 20:49:11 +00008924 // Look for operator=.
8925 DeclarationName Name
8926 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8927 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8928 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008929
Richard Smith044c8aa2012-11-13 00:54:12 +00008930 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8931 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008932 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008933 LookupResult::Filter F = OpLookup.makeFilter();
8934 while (F.hasNext()) {
8935 NamedDecl *D = F.next();
8936 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8937 if (Method->isCopyAssignmentOperator() ||
8938 (!Copying && Method->isMoveAssignmentOperator()))
8939 continue;
8940
8941 F.erase();
8942 }
8943 F.done();
John McCallb0207482010-03-16 06:11:48 +00008944 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008945
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008946 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008947 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008948 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008949 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008950 // ambiguities), we need to cast "this" to that subobject type; to
8951 // ensure that we don't go through the virtual call mechanism, we need
8952 // to qualify the operator= name with the base class (see below). However,
8953 // this means that if the base class has a protected copy assignment
8954 // operator, the protected member access check will fail. So, we
8955 // rewrite "protected" access to "public" access in this case, since we
8956 // know by construction that we're calling from a derived class.
8957 if (CopyingBaseSubobject) {
8958 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8959 L != LEnd; ++L) {
8960 if (L.getAccess() == AS_protected)
8961 L.setAccess(AS_public);
8962 }
8963 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008964
Douglas Gregor06a9f362010-05-01 20:49:11 +00008965 // Create the nested-name-specifier that will be used to qualify the
8966 // reference to operator=; this is required to suppress the virtual
8967 // call mechanism.
8968 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008969 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008970 SS.MakeTrivial(S.Context,
8971 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008972 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008973 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008974
Douglas Gregor06a9f362010-05-01 20:49:11 +00008975 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008976 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00008977 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
8978 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008979 /*FirstQualifierInScope=*/0,
8980 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008981 /*TemplateArgs=*/0,
8982 /*SuppressQualifierCheck=*/true);
8983 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008984 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008985
Douglas Gregor06a9f362010-05-01 20:49:11 +00008986 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008987
Pavel Labath66ea35d2013-08-30 08:52:28 +00008988 Expr *FromInst = From.build(S, Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008989 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008990 OpEqualRef.takeAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00008991 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008992 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008993 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008994
Richard Smith8c889532012-11-14 00:50:40 +00008995 // If we built a call to a trivial 'operator=' while copying an array,
8996 // bail out. We'll replace the whole shebang with a memcpy.
8997 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8998 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8999 return StmtResult((Stmt*)0);
9000
Richard Smith044c8aa2012-11-13 00:54:12 +00009001 // Convert to an expression-statement, and clean up any produced
9002 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00009003 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009004 }
John McCallb0207482010-03-16 06:11:48 +00009005
Richard Smith044c8aa2012-11-13 00:54:12 +00009006 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00009007 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00009008 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009009 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009010 ExprResult Assignment = S.CreateBuiltinBinOp(
9011 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009012 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009013 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00009014 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009015 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009016
9017 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00009018 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00009019
Douglas Gregor06a9f362010-05-01 20:49:11 +00009020 // Construct a loop over the array bounds, e.g.,
9021 //
9022 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9023 //
9024 // that will copy each of the array elements.
9025 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00009026
Douglas Gregor06a9f362010-05-01 20:49:11 +00009027 // Create the iteration variable.
9028 IdentifierInfo *IterationVarName = 0;
9029 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009030 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009031 llvm::raw_svector_ostream OS(Str);
9032 OS << "__i" << Depth;
9033 IterationVarName = &S.Context.Idents.get(OS.str());
9034 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009035 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009036 IterationVarName, SizeType,
9037 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009038 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00009039
Douglas Gregor06a9f362010-05-01 20:49:11 +00009040 // Initialize the iteration variable to zero.
9041 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009042 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009043
Pavel Labath66ea35d2013-08-30 08:52:28 +00009044 // Creates a reference to the iteration variable.
9045 RefBuilder IterationVarRef(IterationVar, SizeType);
9046 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00009047
Douglas Gregor06a9f362010-05-01 20:49:11 +00009048 // Create the DeclStmt that holds the iteration variable.
9049 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009050
Douglas Gregor06a9f362010-05-01 20:49:11 +00009051 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009052 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9053 MoveCastBuilder FromIndexMove(FromIndexCopy);
9054 const ExprBuilder *FromIndex;
9055 if (Copying)
9056 FromIndex = &FromIndexCopy;
9057 else
9058 FromIndex = &FromIndexMove;
9059
9060 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009061
9062 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00009063 StmtResult Copy =
9064 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009065 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00009066 Copying, Depth + 1);
9067 // Bail out if copying fails or if we determined that we should use memcpy.
9068 if (Copy.isInvalid() || !Copy.get())
9069 return Copy;
9070
9071 // Create the comparison against the array bound.
9072 llvm::APInt Upper
9073 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9074 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00009075 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00009076 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9077 BO_NE, S.Context.BoolTy,
9078 VK_RValue, OK_Ordinary, Loc, false);
9079
9080 // Create the pre-increment of the iteration variable.
9081 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00009082 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9083 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009084
Douglas Gregor06a9f362010-05-01 20:49:11 +00009085 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00009086 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009087 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00009088 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00009089 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009090}
9091
Richard Smith8c889532012-11-14 00:50:40 +00009092static StmtResult
9093buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009094 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00009095 bool CopyingBaseSubobject, bool Copying) {
9096 // Maybe we should use a memcpy?
9097 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9098 T.isTriviallyCopyableType(S.Context))
9099 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9100
9101 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9102 CopyingBaseSubobject,
9103 Copying, 0));
9104
9105 // If we ended up picking a trivial assignment operator for an array of a
9106 // non-trivially-copyable class type, just emit a memcpy.
9107 if (!Result.isInvalid() && !Result.get())
9108 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9109
9110 return Result;
9111}
9112
Richard Smithb9d0b762012-07-27 04:22:15 +00009113Sema::ImplicitExceptionSpecification
9114Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9115 CXXRecordDecl *ClassDecl = MD->getParent();
9116
9117 ImplicitExceptionSpecification ExceptSpec(*this);
9118 if (ClassDecl->isInvalidDecl())
9119 return ExceptSpec;
9120
9121 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9122 assert(T->getNumArgs() == 1 && "not a copy assignment op");
9123 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9124
Douglas Gregorb87786f2010-07-01 17:48:08 +00009125 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00009126 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00009127 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00009128
9129 // It is unspecified whether or not an implicit copy assignment operator
9130 // attempts to deduplicate calls to assignment operators of virtual bases are
9131 // made. As such, this exception specification is effectively unspecified.
9132 // Based on a similar decision made for constness in C++0x, we're erring on
9133 // the side of assuming such calls to be made regardless of whether they
9134 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00009135 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9136 BaseEnd = ClassDecl->bases_end();
9137 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00009138 if (Base->isVirtual())
9139 continue;
9140
Douglas Gregora376d102010-07-02 21:50:04 +00009141 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00009142 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009143 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9144 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009145 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00009146 }
Sean Hunt661c67a2011-06-21 23:42:56 +00009147
9148 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9149 BaseEnd = ClassDecl->vbases_end();
9150 Base != BaseEnd; ++Base) {
9151 CXXRecordDecl *BaseClassDecl
9152 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9153 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9154 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009155 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00009156 }
9157
Douglas Gregorb87786f2010-07-01 17:48:08 +00009158 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9159 FieldEnd = ClassDecl->field_end();
9160 Field != FieldEnd;
9161 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009162 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00009163 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9164 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009165 LookupCopyingAssignment(FieldClassDecl,
9166 ArgQuals | FieldType.getCVRQualifiers(),
9167 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009168 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009169 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00009170 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009171
Richard Smithb9d0b762012-07-27 04:22:15 +00009172 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00009173}
9174
9175CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9176 // Note: The following rules are largely analoguous to the copy
9177 // constructor rules. Note that virtual bases are not taken into account
9178 // for determining the argument type of the operator. Note also that
9179 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00009180 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00009181
Richard Smithafb49182012-11-29 01:34:07 +00009182 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9183 if (DSM.isAlreadyBeingDeclared())
9184 return 0;
9185
Sean Hunt30de05c2011-05-14 05:23:20 +00009186 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9187 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00009188 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9189 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00009190 ArgType = ArgType.withConst();
9191 ArgType = Context.getLValueReferenceType(ArgType);
9192
Richard Smitha8942d72013-05-07 03:19:20 +00009193 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9194 CXXCopyAssignment,
9195 Const);
9196
Douglas Gregord3c35902010-07-01 16:36:15 +00009197 // An implicitly-declared copy assignment operator is an inline public
9198 // member of its class.
9199 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009200 SourceLocation ClassLoc = ClassDecl->getLocation();
9201 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009202 CXXMethodDecl *CopyAssignment =
9203 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9204 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9205 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00009206 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00009207 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00009208 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00009209
9210 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009211 FunctionProtoType::ExtProtoInfo EPI =
9212 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009213 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009214
Douglas Gregord3c35902010-07-01 16:36:15 +00009215 // Add the parameter to the operator.
9216 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009217 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00009218 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009219 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009220 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00009221
Richard Smithbc2a35d2012-12-08 08:32:28 +00009222 AddOverriddenMethods(ClassDecl, CopyAssignment);
9223
9224 CopyAssignment->setTrivial(
9225 ClassDecl->needsOverloadResolutionForCopyAssignment()
9226 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9227 : ClassDecl->hasTrivialCopyAssignment());
9228
Richard Smith6c4c36c2012-03-30 20:53:28 +00009229 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009230 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009231
Richard Smithbc2a35d2012-12-08 08:32:28 +00009232 // Note that we have added this copy-assignment operator.
9233 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9234
9235 if (Scope *S = getScopeForContext(ClassDecl))
9236 PushOnScopeChains(CopyAssignment, S, false);
9237 ClassDecl->addDecl(CopyAssignment);
9238
Douglas Gregord3c35902010-07-01 16:36:15 +00009239 return CopyAssignment;
9240}
9241
Richard Smith36155c12013-06-13 03:23:42 +00009242/// Diagnose an implicit copy operation for a class which is odr-used, but
9243/// which is deprecated because the class has a user-declared copy constructor,
9244/// copy assignment operator, or destructor.
9245static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9246 SourceLocation UseLoc) {
9247 assert(CopyOp->isImplicit());
9248
9249 CXXRecordDecl *RD = CopyOp->getParent();
9250 CXXMethodDecl *UserDeclaredOperation = 0;
9251
9252 // In Microsoft mode, assignment operations don't affect constructors and
9253 // vice versa.
9254 if (RD->hasUserDeclaredDestructor()) {
9255 UserDeclaredOperation = RD->getDestructor();
9256 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9257 RD->hasUserDeclaredCopyConstructor() &&
9258 !S.getLangOpts().MicrosoftMode) {
9259 // Find any user-declared copy constructor.
9260 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9261 E = RD->ctor_end(); I != E; ++I) {
9262 if (I->isCopyConstructor()) {
9263 UserDeclaredOperation = *I;
9264 break;
9265 }
9266 }
9267 assert(UserDeclaredOperation);
9268 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9269 RD->hasUserDeclaredCopyAssignment() &&
9270 !S.getLangOpts().MicrosoftMode) {
9271 // Find any user-declared move assignment operator.
9272 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9273 E = RD->method_end(); I != E; ++I) {
9274 if (I->isCopyAssignmentOperator()) {
9275 UserDeclaredOperation = *I;
9276 break;
9277 }
9278 }
9279 assert(UserDeclaredOperation);
9280 }
9281
9282 if (UserDeclaredOperation) {
9283 S.Diag(UserDeclaredOperation->getLocation(),
9284 diag::warn_deprecated_copy_operation)
9285 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9286 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9287 S.Diag(UseLoc, diag::note_member_synthesized_at)
9288 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9289 : Sema::CXXCopyAssignment)
9290 << RD;
9291 }
9292}
9293
Douglas Gregor06a9f362010-05-01 20:49:11 +00009294void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9295 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00009296 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009297 CopyAssignOperator->isOverloadedOperator() &&
9298 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009299 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9300 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009301 "DefineImplicitCopyAssignment called for wrong function");
9302
9303 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9304
9305 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9306 CopyAssignOperator->setInvalidDecl();
9307 return;
9308 }
Richard Smith36155c12013-06-13 03:23:42 +00009309
9310 // C++11 [class.copy]p18:
9311 // The [definition of an implicitly declared copy assignment operator] is
9312 // deprecated if the class has a user-declared copy constructor or a
9313 // user-declared destructor.
9314 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9315 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9316
Eli Friedman86164e82013-09-05 00:02:25 +00009317 CopyAssignOperator->markUsed(Context);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009318
Eli Friedman9a14db32012-10-18 20:14:08 +00009319 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009320 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009321
9322 // C++0x [class.copy]p30:
9323 // The implicitly-defined or explicitly-defaulted copy assignment operator
9324 // for a non-union class X performs memberwise copy assignment of its
9325 // subobjects. The direct base classes of X are assigned first, in the
9326 // order of their declaration in the base-specifier-list, and then the
9327 // immediate non-static data members of X are assigned, in the order in
9328 // which they were declared in the class definition.
9329
9330 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009331 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009332
9333 // The parameter for the "other" object, which we are copying from.
9334 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9335 Qualifiers OtherQuals = Other->getType().getQualifiers();
9336 QualType OtherRefType = Other->getType();
9337 if (const LValueReferenceType *OtherRef
9338 = OtherRefType->getAs<LValueReferenceType>()) {
9339 OtherRefType = OtherRef->getPointeeType();
9340 OtherQuals = OtherRefType.getQualifiers();
9341 }
9342
9343 // Our location for everything implicitly-generated.
9344 SourceLocation Loc = CopyAssignOperator->getLocation();
9345
Pavel Labath66ea35d2013-08-30 08:52:28 +00009346 // Builds a DeclRefExpr for the "other" object.
9347 RefBuilder OtherRef(Other, OtherRefType);
9348
9349 // Builds the "this" pointer.
9350 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009351
9352 // Assign base classes.
9353 bool Invalid = false;
9354 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9355 E = ClassDecl->bases_end(); Base != E; ++Base) {
9356 // Form the assignment:
9357 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9358 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009359 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009360 Invalid = true;
9361 continue;
9362 }
9363
John McCallf871d0c2010-08-07 06:22:56 +00009364 CXXCastPath BasePath;
9365 BasePath.push_back(Base);
9366
Douglas Gregor06a9f362010-05-01 20:49:11 +00009367 // Construct the "from" expression, which is an implicit cast to the
9368 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009369 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9370 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009371
9372 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009373 DerefBuilder DerefThis(This);
9374 CastBuilder To(DerefThis,
9375 Context.getCVRQualifiedType(
9376 BaseType, CopyAssignOperator->getTypeQualifiers()),
9377 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009378
9379 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009380 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009381 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009382 /*CopyingBaseSubobject=*/true,
9383 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009384 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009385 Diag(CurrentLocation, diag::note_member_synthesized_at)
9386 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9387 CopyAssignOperator->setInvalidDecl();
9388 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009389 }
9390
9391 // Success! Record the copy.
9392 Statements.push_back(Copy.takeAs<Expr>());
9393 }
9394
Douglas Gregor06a9f362010-05-01 20:49:11 +00009395 // Assign non-static members.
9396 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9397 FieldEnd = ClassDecl->field_end();
9398 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009399 if (Field->isUnnamedBitfield())
9400 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009401
9402 if (Field->isInvalidDecl()) {
9403 Invalid = true;
9404 continue;
9405 }
9406
Douglas Gregor06a9f362010-05-01 20:49:11 +00009407 // Check for members of reference type; we can't copy those.
9408 if (Field->getType()->isReferenceType()) {
9409 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9410 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9411 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009412 Diag(CurrentLocation, diag::note_member_synthesized_at)
9413 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009414 Invalid = true;
9415 continue;
9416 }
9417
9418 // Check for members of const-qualified, non-class type.
9419 QualType BaseType = Context.getBaseElementType(Field->getType());
9420 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9421 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9422 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9423 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009424 Diag(CurrentLocation, diag::note_member_synthesized_at)
9425 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009426 Invalid = true;
9427 continue;
9428 }
John McCallb77115d2011-06-17 00:18:42 +00009429
9430 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009431 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9432 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009433
9434 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009435 if (FieldType->isIncompleteArrayType()) {
9436 assert(ClassDecl->hasFlexibleArrayMember() &&
9437 "Incomplete array type is not valid");
9438 continue;
9439 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009440
9441 // Build references to the field in the object we're copying from and to.
9442 CXXScopeSpec SS; // Intentionally empty
9443 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9444 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009445 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009446 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009447
9448 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9449
9450 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009451
Douglas Gregor06a9f362010-05-01 20:49:11 +00009452 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009453 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009454 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009455 /*CopyingBaseSubobject=*/false,
9456 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009457 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009458 Diag(CurrentLocation, diag::note_member_synthesized_at)
9459 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9460 CopyAssignOperator->setInvalidDecl();
9461 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009462 }
9463
9464 // Success! Record the copy.
9465 Statements.push_back(Copy.takeAs<Stmt>());
9466 }
9467
9468 if (!Invalid) {
9469 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009470 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009471
John McCall60d7b3a2010-08-24 06:29:42 +00009472 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009473 if (Return.isInvalid())
9474 Invalid = true;
9475 else {
9476 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009477
9478 if (Trap.hasErrorOccurred()) {
9479 Diag(CurrentLocation, diag::note_member_synthesized_at)
9480 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9481 Invalid = true;
9482 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009483 }
9484 }
9485
9486 if (Invalid) {
9487 CopyAssignOperator->setInvalidDecl();
9488 return;
9489 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009490
9491 StmtResult Body;
9492 {
9493 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009494 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009495 /*isStmtExpr=*/false);
9496 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9497 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009498 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009499
9500 if (ASTMutationListener *L = getASTMutationListener()) {
9501 L->CompletedImplicitDefinition(CopyAssignOperator);
9502 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009503}
9504
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009505Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009506Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9507 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009508
Richard Smithb9d0b762012-07-27 04:22:15 +00009509 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009510 if (ClassDecl->isInvalidDecl())
9511 return ExceptSpec;
9512
9513 // C++0x [except.spec]p14:
9514 // An implicitly declared special member function (Clause 12) shall have an
9515 // exception-specification. [...]
9516
9517 // It is unspecified whether or not an implicit move assignment operator
9518 // attempts to deduplicate calls to assignment operators of virtual bases are
9519 // made. As such, this exception specification is effectively unspecified.
9520 // Based on a similar decision made for constness in C++0x, we're erring on
9521 // the side of assuming such calls to be made regardless of whether they
9522 // actually happen.
9523 // Note that a move constructor is not implicitly declared when there are
9524 // virtual bases, but it can still be user-declared and explicitly defaulted.
9525 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9526 BaseEnd = ClassDecl->bases_end();
9527 Base != BaseEnd; ++Base) {
9528 if (Base->isVirtual())
9529 continue;
9530
9531 CXXRecordDecl *BaseClassDecl
9532 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9533 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009534 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009535 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009536 }
9537
9538 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9539 BaseEnd = ClassDecl->vbases_end();
9540 Base != BaseEnd; ++Base) {
9541 CXXRecordDecl *BaseClassDecl
9542 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9543 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009544 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009545 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009546 }
9547
9548 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9549 FieldEnd = ClassDecl->field_end();
9550 Field != FieldEnd;
9551 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009552 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009553 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009554 if (CXXMethodDecl *MoveAssign =
9555 LookupMovingAssignment(FieldClassDecl,
9556 FieldType.getCVRQualifiers(),
9557 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009558 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009559 }
9560 }
9561
9562 return ExceptSpec;
9563}
9564
9565CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009566 assert(ClassDecl->needsImplicitMoveAssignment());
9567
Richard Smithafb49182012-11-29 01:34:07 +00009568 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9569 if (DSM.isAlreadyBeingDeclared())
9570 return 0;
9571
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009572 // Note: The following rules are largely analoguous to the move
9573 // constructor rules.
9574
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009575 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9576 QualType RetType = Context.getLValueReferenceType(ArgType);
9577 ArgType = Context.getRValueReferenceType(ArgType);
9578
Richard Smitha8942d72013-05-07 03:19:20 +00009579 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9580 CXXMoveAssignment,
9581 false);
9582
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009583 // An implicitly-declared move assignment operator is an inline public
9584 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009585 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9586 SourceLocation ClassLoc = ClassDecl->getLocation();
9587 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009588 CXXMethodDecl *MoveAssignment =
9589 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9590 /*TInfo=*/0, /*StorageClass=*/SC_None,
9591 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009592 MoveAssignment->setAccess(AS_public);
9593 MoveAssignment->setDefaulted();
9594 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009595
Richard Smithb9d0b762012-07-27 04:22:15 +00009596 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009597 FunctionProtoType::ExtProtoInfo EPI =
9598 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009599 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009600
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009601 // Add the parameter to the operator.
9602 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9603 ClassLoc, ClassLoc, /*Id=*/0,
9604 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009605 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009606 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009607
Richard Smithbc2a35d2012-12-08 08:32:28 +00009608 AddOverriddenMethods(ClassDecl, MoveAssignment);
9609
9610 MoveAssignment->setTrivial(
9611 ClassDecl->needsOverloadResolutionForMoveAssignment()
9612 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9613 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009614
Richard Smith7d5088a2012-02-18 02:02:13 +00009615 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Richard Smith743cbb92013-11-04 01:48:18 +00009616 ClassDecl->setImplicitMoveAssignmentIsDeleted();
9617 SetDeclDeleted(MoveAssignment, ClassLoc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009618 }
9619
Richard Smithbc2a35d2012-12-08 08:32:28 +00009620 // Note that we have added this copy-assignment operator.
9621 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9622
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009623 if (Scope *S = getScopeForContext(ClassDecl))
9624 PushOnScopeChains(MoveAssignment, S, false);
9625 ClassDecl->addDecl(MoveAssignment);
9626
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009627 return MoveAssignment;
9628}
9629
9630void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9631 CXXMethodDecl *MoveAssignOperator) {
9632 assert((MoveAssignOperator->isDefaulted() &&
9633 MoveAssignOperator->isOverloadedOperator() &&
9634 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009635 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9636 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009637 "DefineImplicitMoveAssignment called for wrong function");
9638
9639 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9640
9641 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9642 MoveAssignOperator->setInvalidDecl();
9643 return;
9644 }
9645
Eli Friedman86164e82013-09-05 00:02:25 +00009646 MoveAssignOperator->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009647
Eli Friedman9a14db32012-10-18 20:14:08 +00009648 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009649 DiagnosticErrorTrap Trap(Diags);
9650
9651 // C++0x [class.copy]p28:
9652 // The implicitly-defined or move assignment operator for a non-union class
9653 // X performs memberwise move assignment of its subobjects. The direct base
9654 // classes of X are assigned first, in the order of their declaration in the
9655 // base-specifier-list, and then the immediate non-static data members of X
9656 // are assigned, in the order in which they were declared in the class
9657 // definition.
9658
Richard Smith743cbb92013-11-04 01:48:18 +00009659 // FIXME: Issue a warning if our implicit move assignment operator will move
9660 // from a virtual base more than once. For instance, given:
9661 //
9662 // struct A { A &operator=(A&&); };
9663 // struct B : virtual A {};
9664 // struct C : virtual A {};
9665 // struct D : B, C {};
9666 //
9667 // If the move assignment operator of D is synthesized, we should warn,
9668 // because the A vbase will be moved from multiple times.
9669
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009670 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009671 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009672
9673 // The parameter for the "other" object, which we are move from.
9674 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9675 QualType OtherRefType = Other->getType()->
9676 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009677 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009678 "Bad argument type of defaulted move assignment");
9679
9680 // Our location for everything implicitly-generated.
9681 SourceLocation Loc = MoveAssignOperator->getLocation();
9682
Pavel Labath66ea35d2013-08-30 08:52:28 +00009683 // Builds a reference to the "other" object.
9684 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009685 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009686 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009687
Pavel Labath66ea35d2013-08-30 08:52:28 +00009688 // Builds the "this" pointer.
9689 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +00009690
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009691 // Assign base classes.
9692 bool Invalid = false;
9693 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9694 E = ClassDecl->bases_end(); Base != E; ++Base) {
9695 // Form the assignment:
9696 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9697 QualType BaseType = Base->getType().getUnqualifiedType();
9698 if (!BaseType->isRecordType()) {
9699 Invalid = true;
9700 continue;
9701 }
9702
9703 CXXCastPath BasePath;
9704 BasePath.push_back(Base);
9705
9706 // Construct the "from" expression, which is an implicit cast to the
9707 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009708 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009709
9710 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009711 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009712
9713 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009714 CastBuilder To(DerefThis,
9715 Context.getCVRQualifiedType(
9716 BaseType, MoveAssignOperator->getTypeQualifiers()),
9717 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009718
9719 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009720 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009721 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009722 /*CopyingBaseSubobject=*/true,
9723 /*Copying=*/false);
9724 if (Move.isInvalid()) {
9725 Diag(CurrentLocation, diag::note_member_synthesized_at)
9726 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9727 MoveAssignOperator->setInvalidDecl();
9728 return;
9729 }
9730
9731 // Success! Record the move.
9732 Statements.push_back(Move.takeAs<Expr>());
9733 }
9734
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009735 // Assign non-static members.
9736 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9737 FieldEnd = ClassDecl->field_end();
9738 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009739 if (Field->isUnnamedBitfield())
9740 continue;
9741
Eli Friedman8150da32013-06-07 01:48:56 +00009742 if (Field->isInvalidDecl()) {
9743 Invalid = true;
9744 continue;
9745 }
9746
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009747 // Check for members of reference type; we can't move those.
9748 if (Field->getType()->isReferenceType()) {
9749 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9750 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9751 Diag(Field->getLocation(), diag::note_declared_at);
9752 Diag(CurrentLocation, diag::note_member_synthesized_at)
9753 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9754 Invalid = true;
9755 continue;
9756 }
9757
9758 // Check for members of const-qualified, non-class type.
9759 QualType BaseType = Context.getBaseElementType(Field->getType());
9760 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9761 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9762 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9763 Diag(Field->getLocation(), diag::note_declared_at);
9764 Diag(CurrentLocation, diag::note_member_synthesized_at)
9765 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9766 Invalid = true;
9767 continue;
9768 }
9769
9770 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009771 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9772 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009773
9774 QualType FieldType = Field->getType().getNonReferenceType();
9775 if (FieldType->isIncompleteArrayType()) {
9776 assert(ClassDecl->hasFlexibleArrayMember() &&
9777 "Incomplete array type is not valid");
9778 continue;
9779 }
9780
9781 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009782 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9783 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009784 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009785 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009786 MemberBuilder From(MoveOther, OtherRefType,
9787 /*IsArrow=*/false, MemberLookup);
9788 MemberBuilder To(This, getCurrentThisType(),
9789 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009790
Pavel Labath66ea35d2013-08-30 08:52:28 +00009791 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009792 "Member reference with rvalue base must be rvalue except for reference "
9793 "members, which aren't allowed for move assignment.");
9794
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009795 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009796 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009797 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009798 /*CopyingBaseSubobject=*/false,
9799 /*Copying=*/false);
9800 if (Move.isInvalid()) {
9801 Diag(CurrentLocation, diag::note_member_synthesized_at)
9802 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9803 MoveAssignOperator->setInvalidDecl();
9804 return;
9805 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009806
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009807 // Success! Record the copy.
9808 Statements.push_back(Move.takeAs<Stmt>());
9809 }
9810
9811 if (!Invalid) {
9812 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009813 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009814
9815 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9816 if (Return.isInvalid())
9817 Invalid = true;
9818 else {
9819 Statements.push_back(Return.takeAs<Stmt>());
9820
9821 if (Trap.hasErrorOccurred()) {
9822 Diag(CurrentLocation, diag::note_member_synthesized_at)
9823 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9824 Invalid = true;
9825 }
9826 }
9827 }
9828
9829 if (Invalid) {
9830 MoveAssignOperator->setInvalidDecl();
9831 return;
9832 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009833
9834 StmtResult Body;
9835 {
9836 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009837 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009838 /*isStmtExpr=*/false);
9839 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9840 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009841 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9842
9843 if (ASTMutationListener *L = getASTMutationListener()) {
9844 L->CompletedImplicitDefinition(MoveAssignOperator);
9845 }
9846}
9847
Richard Smithb9d0b762012-07-27 04:22:15 +00009848Sema::ImplicitExceptionSpecification
9849Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9850 CXXRecordDecl *ClassDecl = MD->getParent();
9851
9852 ImplicitExceptionSpecification ExceptSpec(*this);
9853 if (ClassDecl->isInvalidDecl())
9854 return ExceptSpec;
9855
9856 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9857 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9858 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9859
Douglas Gregor0d405db2010-07-01 20:59:04 +00009860 // C++ [except.spec]p14:
9861 // An implicitly declared special member function (Clause 12) shall have an
9862 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009863 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9864 BaseEnd = ClassDecl->bases_end();
9865 Base != BaseEnd;
9866 ++Base) {
9867 // Virtual bases are handled below.
9868 if (Base->isVirtual())
9869 continue;
9870
Douglas Gregor22584312010-07-02 23:41:54 +00009871 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009872 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009873 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009874 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009875 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009876 }
9877 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9878 BaseEnd = ClassDecl->vbases_end();
9879 Base != BaseEnd;
9880 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009881 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009882 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009883 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009884 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009885 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009886 }
9887 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9888 FieldEnd = ClassDecl->field_end();
9889 Field != FieldEnd;
9890 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009891 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009892 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9893 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009894 LookupCopyingConstructor(FieldClassDecl,
9895 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009896 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009897 }
9898 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009899
Richard Smithb9d0b762012-07-27 04:22:15 +00009900 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009901}
9902
9903CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9904 CXXRecordDecl *ClassDecl) {
9905 // C++ [class.copy]p4:
9906 // If the class definition does not explicitly declare a copy
9907 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009908 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009909
Richard Smithafb49182012-11-29 01:34:07 +00009910 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9911 if (DSM.isAlreadyBeingDeclared())
9912 return 0;
9913
Sean Hunt49634cf2011-05-13 06:10:58 +00009914 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9915 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009916 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009917 if (Const)
9918 ArgType = ArgType.withConst();
9919 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009920
Richard Smith7756afa2012-06-10 05:43:50 +00009921 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9922 CXXCopyConstructor,
9923 Const);
9924
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009925 DeclarationName Name
9926 = Context.DeclarationNames.getCXXConstructorName(
9927 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009928 SourceLocation ClassLoc = ClassDecl->getLocation();
9929 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009930
9931 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009932 // member of its class.
9933 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009934 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009935 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009936 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009937 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009938 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009939
Richard Smithb9d0b762012-07-27 04:22:15 +00009940 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009941 FunctionProtoType::ExtProtoInfo EPI =
9942 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +00009943 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009944 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009945
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009946 // Add the parameter to the constructor.
9947 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009948 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009949 /*IdentifierInfo=*/0,
9950 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009951 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009952 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009953
Richard Smithbc2a35d2012-12-08 08:32:28 +00009954 CopyConstructor->setTrivial(
9955 ClassDecl->needsOverloadResolutionForCopyConstructor()
9956 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9957 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009958
Richard Smith6c4c36c2012-03-30 20:53:28 +00009959 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009960 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009961
Richard Smithbc2a35d2012-12-08 08:32:28 +00009962 // Note that we have declared this constructor.
9963 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9964
9965 if (Scope *S = getScopeForContext(ClassDecl))
9966 PushOnScopeChains(CopyConstructor, S, false);
9967 ClassDecl->addDecl(CopyConstructor);
9968
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009969 return CopyConstructor;
9970}
9971
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009972void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009973 CXXConstructorDecl *CopyConstructor) {
9974 assert((CopyConstructor->isDefaulted() &&
9975 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009976 !CopyConstructor->doesThisDeclarationHaveABody() &&
9977 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009978 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009979
Anders Carlsson63010a72010-04-23 16:24:12 +00009980 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009981 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009982
Richard Smith36155c12013-06-13 03:23:42 +00009983 // C++11 [class.copy]p7:
Benjamin Kramere5753592013-09-09 14:48:42 +00009984 // The [definition of an implicitly declared copy constructor] is
Richard Smith36155c12013-06-13 03:23:42 +00009985 // deprecated if the class has a user-declared copy assignment operator
9986 // or a user-declared destructor.
9987 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9988 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9989
Eli Friedman9a14db32012-10-18 20:14:08 +00009990 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009991 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009992
David Blaikie93c86172013-01-17 05:26:25 +00009993 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009994 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009995 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009996 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009997 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009998 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009999 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010000 CopyConstructor->setBody(ActOnCompoundStmt(
10001 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10002 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +000010003 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010004
Eli Friedman86164e82013-09-05 00:02:25 +000010005 CopyConstructor->markUsed(Context);
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010006 if (ASTMutationListener *L = getASTMutationListener()) {
10007 L->CompletedImplicitDefinition(CopyConstructor);
10008 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010009}
10010
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010011Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010012Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10013 CXXRecordDecl *ClassDecl = MD->getParent();
10014
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010015 // C++ [except.spec]p14:
10016 // An implicitly declared special member function (Clause 12) shall have an
10017 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +000010018 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010019 if (ClassDecl->isInvalidDecl())
10020 return ExceptSpec;
10021
10022 // Direct base-class constructors.
10023 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10024 BEnd = ClassDecl->bases_end();
10025 B != BEnd; ++B) {
10026 if (B->isVirtual()) // Handled below.
10027 continue;
10028
10029 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10030 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010031 CXXConstructorDecl *Constructor =
10032 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010033 // If this is a deleted function, add it anyway. This might be conformant
10034 // with the standard. This might not. I'm not sure. It might not matter.
10035 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010036 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010037 }
10038 }
10039
10040 // Virtual base-class constructors.
10041 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10042 BEnd = ClassDecl->vbases_end();
10043 B != BEnd; ++B) {
10044 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10045 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010046 CXXConstructorDecl *Constructor =
10047 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010048 // If this is a deleted function, add it anyway. This might be conformant
10049 // with the standard. This might not. I'm not sure. It might not matter.
10050 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010051 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010052 }
10053 }
10054
10055 // Field constructors.
10056 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10057 FEnd = ClassDecl->field_end();
10058 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010059 QualType FieldType = Context.getBaseElementType(F->getType());
10060 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10061 CXXConstructorDecl *Constructor =
10062 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010063 // If this is a deleted function, add it anyway. This might be conformant
10064 // with the standard. This might not. I'm not sure. It might not matter.
10065 // In particular, the problem is that this function never gets called. It
10066 // might just be ill-formed because this function attempts to refer to
10067 // a deleted function here.
10068 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010069 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010070 }
10071 }
10072
10073 return ExceptSpec;
10074}
10075
10076CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10077 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010078 assert(ClassDecl->needsImplicitMoveConstructor());
10079
Richard Smithafb49182012-11-29 01:34:07 +000010080 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10081 if (DSM.isAlreadyBeingDeclared())
10082 return 0;
10083
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010084 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10085 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010086
Richard Smith7756afa2012-06-10 05:43:50 +000010087 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10088 CXXMoveConstructor,
10089 false);
10090
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010091 DeclarationName Name
10092 = Context.DeclarationNames.getCXXConstructorName(
10093 Context.getCanonicalType(ClassType));
10094 SourceLocation ClassLoc = ClassDecl->getLocation();
10095 DeclarationNameInfo NameInfo(Name, ClassLoc);
10096
Richard Smitha8942d72013-05-07 03:19:20 +000010097 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010098 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010099 // member of its class.
10100 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010101 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010102 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010103 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010104 MoveConstructor->setAccess(AS_public);
10105 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010106
Richard Smithb9d0b762012-07-27 04:22:15 +000010107 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010108 FunctionProtoType::ExtProtoInfo EPI =
10109 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010110 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010111 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010112
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010113 // Add the parameter to the constructor.
10114 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10115 ClassLoc, ClassLoc,
10116 /*IdentifierInfo=*/0,
10117 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010118 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010119 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010120
Richard Smithbc2a35d2012-12-08 08:32:28 +000010121 MoveConstructor->setTrivial(
10122 ClassDecl->needsOverloadResolutionForMoveConstructor()
10123 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10124 : ClassDecl->hasTrivialMoveConstructor());
10125
Sean Hunt769bb2d2011-10-11 06:43:29 +000010126 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Richard Smith743cbb92013-11-04 01:48:18 +000010127 ClassDecl->setImplicitMoveConstructorIsDeleted();
10128 SetDeclDeleted(MoveConstructor, ClassLoc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010129 }
10130
10131 // Note that we have declared this constructor.
10132 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10133
10134 if (Scope *S = getScopeForContext(ClassDecl))
10135 PushOnScopeChains(MoveConstructor, S, false);
10136 ClassDecl->addDecl(MoveConstructor);
10137
10138 return MoveConstructor;
10139}
10140
10141void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10142 CXXConstructorDecl *MoveConstructor) {
10143 assert((MoveConstructor->isDefaulted() &&
10144 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010145 !MoveConstructor->doesThisDeclarationHaveABody() &&
10146 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010147 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10148
10149 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10150 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10151
Eli Friedman9a14db32012-10-18 20:14:08 +000010152 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010153 DiagnosticErrorTrap Trap(Diags);
10154
David Blaikie93c86172013-01-17 05:26:25 +000010155 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010156 Trap.hasErrorOccurred()) {
10157 Diag(CurrentLocation, diag::note_member_synthesized_at)
10158 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10159 MoveConstructor->setInvalidDecl();
10160 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010161 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010162 MoveConstructor->setBody(ActOnCompoundStmt(
10163 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10164 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010165 }
10166
Eli Friedman86164e82013-09-05 00:02:25 +000010167 MoveConstructor->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010168
10169 if (ASTMutationListener *L = getASTMutationListener()) {
10170 L->CompletedImplicitDefinition(MoveConstructor);
10171 }
10172}
10173
Douglas Gregore4e68d42012-02-15 19:33:52 +000010174bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010175 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010176}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010177
10178void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Valid6992ab2013-09-29 08:45:24 +000010179 SourceLocation CurrentLocation,
10180 CXXConversionDecl *Conv) {
10181 CXXRecordDecl *Lambda = Conv->getParent();
10182 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10183 // If we are defining a specialization of a conversion to function-ptr
10184 // cache the deduced template arguments for this specialization
10185 // so that we can use them to retrieve the corresponding call-operator
10186 // and static-invoker.
10187 const TemplateArgumentList *DeducedTemplateArgs = 0;
10188
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010189
Faisal Valid6992ab2013-09-29 08:45:24 +000010190 // Retrieve the corresponding call-operator specialization.
10191 if (Lambda->isGenericLambda()) {
10192 assert(Conv->isFunctionTemplateSpecialization());
10193 FunctionTemplateDecl *CallOpTemplate =
10194 CallOp->getDescribedFunctionTemplate();
10195 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10196 void *InsertPos = 0;
10197 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10198 DeducedTemplateArgs->data(),
10199 DeducedTemplateArgs->size(),
10200 InsertPos);
10201 assert(CallOpSpec &&
10202 "Conversion operator must have a corresponding call operator");
10203 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10204 }
10205 // Mark the call operator referenced (and add to pending instantiations
10206 // if necessary).
10207 // For both the conversion and static-invoker template specializations
10208 // we construct their body's in this function, so no need to add them
10209 // to the PendingInstantiations.
10210 MarkFunctionReferenced(CurrentLocation, CallOp);
10211
Eli Friedman9a14db32012-10-18 20:14:08 +000010212 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010213 DiagnosticErrorTrap Trap(Diags);
Faisal Valid6992ab2013-09-29 08:45:24 +000010214
10215 // Retreive the static invoker...
10216 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10217 // ... and get the corresponding specialization for a generic lambda.
10218 if (Lambda->isGenericLambda()) {
10219 assert(DeducedTemplateArgs &&
10220 "Must have deduced template arguments from Conversion Operator");
10221 FunctionTemplateDecl *InvokeTemplate =
10222 Invoker->getDescribedFunctionTemplate();
10223 void *InsertPos = 0;
10224 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10225 DeducedTemplateArgs->data(),
10226 DeducedTemplateArgs->size(),
10227 InsertPos);
10228 assert(InvokeSpec &&
10229 "Must have a corresponding static invoker specialization");
10230 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10231 }
10232 // Construct the body of the conversion function { return __invoke; }.
10233 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10234 VK_LValue, Conv->getLocation()).take();
10235 assert(FunctionRef && "Can't refer to __invoke function?");
10236 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10237 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10238 Conv->getLocation(),
10239 Conv->getLocation()));
10240
10241 Conv->markUsed(Context);
10242 Conv->setReferenced();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010243
Faisal Valid6992ab2013-09-29 08:45:24 +000010244 // Fill in the __invoke function with a dummy implementation. IR generation
10245 // will fill in the actual details.
10246 Invoker->markUsed(Context);
10247 Invoker->setReferenced();
10248 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10249
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010250 if (ASTMutationListener *L = getASTMutationListener()) {
10251 L->CompletedImplicitDefinition(Conv);
Faisal Valid6992ab2013-09-29 08:45:24 +000010252 L->CompletedImplicitDefinition(Invoker);
10253 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010254}
10255
Faisal Valid6992ab2013-09-29 08:45:24 +000010256
10257
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010258void Sema::DefineImplicitLambdaToBlockPointerConversion(
10259 SourceLocation CurrentLocation,
10260 CXXConversionDecl *Conv)
10261{
Faisal Vali56fe35b2013-09-29 17:08:32 +000010262 assert(!Conv->getParent()->isGenericLambda());
Faisal Valid6992ab2013-09-29 08:45:24 +000010263
Eli Friedman86164e82013-09-05 00:02:25 +000010264 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010265
Eli Friedman9a14db32012-10-18 20:14:08 +000010266 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010267 DiagnosticErrorTrap Trap(Diags);
10268
Douglas Gregorac1303e2012-02-22 05:02:47 +000010269 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010270 Expr *This = ActOnCXXThis(CurrentLocation).take();
10271 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010272
Eli Friedman23f02672012-03-01 04:01:32 +000010273 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10274 Conv->getLocation(),
10275 Conv, DerefThis);
10276
10277 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10278 // behavior. Note that only the general conversion function does this
10279 // (since it's unusable otherwise); in the case where we inline the
10280 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010281 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010282 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10283 CK_CopyAndAutoreleaseBlockObject,
10284 BuildBlock.get(), 0, VK_RValue);
10285
10286 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010287 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010288 Conv->setInvalidDecl();
10289 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010290 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010291
Douglas Gregorac1303e2012-02-22 05:02:47 +000010292 // Create the return statement that returns the block from the conversion
10293 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010294 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010295 if (Return.isInvalid()) {
10296 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10297 Conv->setInvalidDecl();
10298 return;
10299 }
10300
10301 // Set the body of the conversion function.
10302 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010303 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010304 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010305 Conv->getLocation()));
10306
Douglas Gregorac1303e2012-02-22 05:02:47 +000010307 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010308 if (ASTMutationListener *L = getASTMutationListener()) {
10309 L->CompletedImplicitDefinition(Conv);
10310 }
10311}
10312
Douglas Gregorf52757d2012-03-10 06:53:13 +000010313/// \brief Determine whether the given list arguments contains exactly one
10314/// "real" (non-default) argument.
10315static bool hasOneRealArgument(MultiExprArg Args) {
10316 switch (Args.size()) {
10317 case 0:
10318 return false;
10319
10320 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010321 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010322 return false;
10323
10324 // fall through
10325 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010326 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010327 }
10328
10329 return false;
10330}
10331
John McCall60d7b3a2010-08-24 06:29:42 +000010332ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010333Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010334 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010335 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010336 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010337 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010338 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010339 unsigned ConstructKind,
10340 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010341 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010342
Douglas Gregor2f599792010-04-02 18:24:57 +000010343 // C++0x [class.copy]p34:
10344 // When certain criteria are met, an implementation is allowed to
10345 // omit the copy/move construction of a class object, even if the
10346 // copy/move constructor and/or destructor for the object have
10347 // side effects. [...]
10348 // - when a temporary class object that has not been bound to a
10349 // reference (12.2) would be copied/moved to a class object
10350 // with the same cv-unqualified type, the copy/move operation
10351 // can be omitted by constructing the temporary object
10352 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010353 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010354 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010355 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010356 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010357 }
Mike Stump1eb44332009-09-09 15:08:12 +000010358
10359 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010360 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010361 IsListInitialization, RequiresZeroInit,
10362 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010363}
10364
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010365/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10366/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010367ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010368Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10369 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010370 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010371 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010372 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010373 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010374 unsigned ConstructKind,
10375 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010376 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010377 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010378 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010379 HadMultipleCandidates,
10380 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010381 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10382 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010383}
10384
John McCall68c6c9a2010-02-02 09:10:11 +000010385void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010386 if (VD->isInvalidDecl()) return;
10387
John McCall68c6c9a2010-02-02 09:10:11 +000010388 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010389 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010390 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010391 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010392
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010393 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010394 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010395 CheckDestructorAccess(VD->getLocation(), Destructor,
10396 PDiag(diag::err_access_dtor_var)
10397 << VD->getDeclName()
10398 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010399 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010400
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010401 if (!VD->hasGlobalStorage()) return;
10402
10403 // Emit warning for non-trivial dtor in global scope (a real global,
10404 // class-static, function-static).
10405 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10406
10407 // TODO: this should be re-enabled for static locals by !CXAAtExit
10408 if (!VD->isStaticLocal())
10409 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010410}
10411
Douglas Gregor39da0b82009-09-09 23:08:42 +000010412/// \brief Given a constructor and the set of arguments provided for the
10413/// constructor, convert the arguments and add any required default arguments
10414/// to form a proper call to this constructor.
10415///
10416/// \returns true if an error occurred, false otherwise.
10417bool
10418Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10419 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010420 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010421 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010422 bool AllowExplicit,
10423 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010424 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10425 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010426 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010427
10428 const FunctionProtoType *Proto
10429 = Constructor->getType()->getAs<FunctionProtoType>();
10430 assert(Proto && "Constructor without a prototype?");
10431 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010432
10433 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010434 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010435 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010436 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010437 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010438
10439 VariadicCallType CallType =
10440 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010441 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010442 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010443 Proto, 0,
10444 llvm::makeArrayRef(Args, NumArgs),
10445 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010446 CallType, AllowExplicit,
10447 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010448 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010449
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010450 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010451
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010452 CheckConstructorCall(Constructor,
10453 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10454 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010455 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010456
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010457 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010458}
10459
Anders Carlsson20d45d22009-12-12 00:32:00 +000010460static inline bool
10461CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10462 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010463 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010464 if (isa<NamespaceDecl>(DC)) {
10465 return SemaRef.Diag(FnDecl->getLocation(),
10466 diag::err_operator_new_delete_declared_in_namespace)
10467 << FnDecl->getDeclName();
10468 }
10469
10470 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010471 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010472 return SemaRef.Diag(FnDecl->getLocation(),
10473 diag::err_operator_new_delete_declared_static)
10474 << FnDecl->getDeclName();
10475 }
10476
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010477 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010478}
10479
Anders Carlsson156c78e2009-12-13 17:53:43 +000010480static inline bool
10481CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10482 CanQualType ExpectedResultType,
10483 CanQualType ExpectedFirstParamType,
10484 unsigned DependentParamTypeDiag,
10485 unsigned InvalidParamTypeDiag) {
10486 QualType ResultType =
10487 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10488
10489 // Check that the result type is not dependent.
10490 if (ResultType->isDependentType())
10491 return SemaRef.Diag(FnDecl->getLocation(),
10492 diag::err_operator_new_delete_dependent_result_type)
10493 << FnDecl->getDeclName() << ExpectedResultType;
10494
10495 // Check that the result type is what we expect.
10496 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10497 return SemaRef.Diag(FnDecl->getLocation(),
10498 diag::err_operator_new_delete_invalid_result_type)
10499 << FnDecl->getDeclName() << ExpectedResultType;
10500
10501 // A function template must have at least 2 parameters.
10502 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10503 return SemaRef.Diag(FnDecl->getLocation(),
10504 diag::err_operator_new_delete_template_too_few_parameters)
10505 << FnDecl->getDeclName();
10506
10507 // The function decl must have at least 1 parameter.
10508 if (FnDecl->getNumParams() == 0)
10509 return SemaRef.Diag(FnDecl->getLocation(),
10510 diag::err_operator_new_delete_too_few_parameters)
10511 << FnDecl->getDeclName();
10512
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010513 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010514 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10515 if (FirstParamType->isDependentType())
10516 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10517 << FnDecl->getDeclName() << ExpectedFirstParamType;
10518
10519 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010520 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010521 ExpectedFirstParamType)
10522 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10523 << FnDecl->getDeclName() << ExpectedFirstParamType;
10524
10525 return false;
10526}
10527
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010528static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010529CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010530 // C++ [basic.stc.dynamic.allocation]p1:
10531 // A program is ill-formed if an allocation function is declared in a
10532 // namespace scope other than global scope or declared static in global
10533 // scope.
10534 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10535 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010536
10537 CanQualType SizeTy =
10538 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10539
10540 // C++ [basic.stc.dynamic.allocation]p1:
10541 // The return type shall be void*. The first parameter shall have type
10542 // std::size_t.
10543 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10544 SizeTy,
10545 diag::err_operator_new_dependent_param_type,
10546 diag::err_operator_new_param_type))
10547 return true;
10548
10549 // C++ [basic.stc.dynamic.allocation]p1:
10550 // The first parameter shall not have an associated default argument.
10551 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010552 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010553 diag::err_operator_new_default_arg)
10554 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10555
10556 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010557}
10558
10559static bool
Richard Smith444d3842012-10-20 08:26:51 +000010560CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010561 // C++ [basic.stc.dynamic.deallocation]p1:
10562 // A program is ill-formed if deallocation functions are declared in a
10563 // namespace scope other than global scope or declared static in global
10564 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010565 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10566 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010567
10568 // C++ [basic.stc.dynamic.deallocation]p2:
10569 // Each deallocation function shall return void and its first parameter
10570 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010571 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10572 SemaRef.Context.VoidPtrTy,
10573 diag::err_operator_delete_dependent_param_type,
10574 diag::err_operator_delete_param_type))
10575 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010576
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010577 return false;
10578}
10579
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010580/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10581/// of this overloaded operator is well-formed. If so, returns false;
10582/// otherwise, emits appropriate diagnostics and returns true.
10583bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010584 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010585 "Expected an overloaded operator declaration");
10586
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010587 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10588
Mike Stump1eb44332009-09-09 15:08:12 +000010589 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010590 // The allocation and deallocation functions, operator new,
10591 // operator new[], operator delete and operator delete[], are
10592 // described completely in 3.7.3. The attributes and restrictions
10593 // found in the rest of this subclause do not apply to them unless
10594 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010595 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010596 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010597
Anders Carlssona3ccda52009-12-12 00:26:23 +000010598 if (Op == OO_New || Op == OO_Array_New)
10599 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010600
10601 // C++ [over.oper]p6:
10602 // An operator function shall either be a non-static member
10603 // function or be a non-member function and have at least one
10604 // parameter whose type is a class, a reference to a class, an
10605 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010606 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10607 if (MethodDecl->isStatic())
10608 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010609 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010610 } else {
10611 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010612 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10613 ParamEnd = FnDecl->param_end();
10614 Param != ParamEnd; ++Param) {
10615 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010616 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10617 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010618 ClassOrEnumParam = true;
10619 break;
10620 }
10621 }
10622
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010623 if (!ClassOrEnumParam)
10624 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010625 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010626 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010627 }
10628
10629 // C++ [over.oper]p8:
10630 // An operator function cannot have default arguments (8.3.6),
10631 // except where explicitly stated below.
10632 //
Mike Stump1eb44332009-09-09 15:08:12 +000010633 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010634 // (C++ [over.call]p1).
10635 if (Op != OO_Call) {
10636 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10637 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010638 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010639 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010640 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010641 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010642 }
10643 }
10644
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010645 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10646 { false, false, false }
10647#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10648 , { Unary, Binary, MemberOnly }
10649#include "clang/Basic/OperatorKinds.def"
10650 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010651
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010652 bool CanBeUnaryOperator = OperatorUses[Op][0];
10653 bool CanBeBinaryOperator = OperatorUses[Op][1];
10654 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010655
10656 // C++ [over.oper]p8:
10657 // [...] Operator functions cannot have more or fewer parameters
10658 // than the number required for the corresponding operator, as
10659 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010660 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010661 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010662 if (Op != OO_Call &&
10663 ((NumParams == 1 && !CanBeUnaryOperator) ||
10664 (NumParams == 2 && !CanBeBinaryOperator) ||
10665 (NumParams < 1) || (NumParams > 2))) {
10666 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010667 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010668 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010669 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010670 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010671 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010672 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010673 assert(CanBeBinaryOperator &&
10674 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010675 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010676 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010677
Chris Lattner416e46f2008-11-21 07:57:12 +000010678 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010679 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010680 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010681
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010682 // Overloaded operators other than operator() cannot be variadic.
10683 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010684 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010685 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010686 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010687 }
10688
10689 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010690 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10691 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010692 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010693 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010694 }
10695
10696 // C++ [over.inc]p1:
10697 // The user-defined function called operator++ implements the
10698 // prefix and postfix ++ operator. If this function is a member
10699 // function with no parameters, or a non-member function with one
10700 // parameter of class or enumeration type, it defines the prefix
10701 // increment operator ++ for objects of that type. If the function
10702 // is a member function with one parameter (which shall be of type
10703 // int) or a non-member function with two parameters (the second
10704 // of which shall be of type int), it defines the postfix
10705 // increment operator ++ for objects of that type.
10706 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10707 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10708 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010709 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010710 ParamIsInt = BT->getKind() == BuiltinType::Int;
10711
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010712 if (!ParamIsInt)
10713 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010714 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010715 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010716 }
10717
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010718 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010719}
Chris Lattner5a003a42008-12-17 07:09:26 +000010720
Sean Hunta6c058d2010-01-13 09:01:02 +000010721/// CheckLiteralOperatorDeclaration - Check whether the declaration
10722/// of this literal operator function is well-formed. If so, returns
10723/// false; otherwise, emits appropriate diagnostics and returns true.
10724bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010725 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010726 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10727 << FnDecl->getDeclName();
10728 return true;
10729 }
10730
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010731 if (FnDecl->isExternC()) {
10732 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10733 return true;
10734 }
10735
Sean Hunta6c058d2010-01-13 09:01:02 +000010736 bool Valid = false;
10737
Richard Smith36f5cfe2012-03-09 08:00:36 +000010738 // This might be the definition of a literal operator template.
10739 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10740 // This might be a specialization of a literal operator template.
10741 if (!TpDecl)
10742 TpDecl = FnDecl->getPrimaryTemplate();
10743
Richard Smithb328e292013-10-07 19:57:58 +000010744 // template <char...> type operator "" name() and
10745 // template <class T, T...> type operator "" name() are the only valid
10746 // template signatures, and the only valid signatures with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010747 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010748 if (FnDecl->param_size() == 0) {
Richard Smithb328e292013-10-07 19:57:58 +000010749 // Must have one or two template parameters
Sean Hunt216c2782010-04-07 23:11:06 +000010750 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10751 if (Params->size() == 1) {
10752 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010753 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010754
Sean Hunt216c2782010-04-07 23:11:06 +000010755 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010756 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10757 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10758 Valid = true;
Richard Smithb328e292013-10-07 19:57:58 +000010759 } else if (Params->size() == 2) {
10760 TemplateTypeParmDecl *PmType =
10761 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10762 NonTypeTemplateParmDecl *PmArgs =
10763 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10764
10765 // The second template parameter must be a parameter pack with the
10766 // first template parameter as its type.
10767 if (PmType && PmArgs &&
10768 !PmType->isTemplateParameterPack() &&
10769 PmArgs->isTemplateParameterPack()) {
10770 const TemplateTypeParmType *TArgs =
10771 PmArgs->getType()->getAs<TemplateTypeParmType>();
10772 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10773 TArgs->getIndex() == PmType->getIndex()) {
10774 Valid = true;
10775 if (ActiveTemplateInstantiations.empty())
10776 Diag(FnDecl->getLocation(),
10777 diag::ext_string_literal_operator_template);
10778 }
10779 }
Sean Hunt216c2782010-04-07 23:11:06 +000010780 }
10781 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010782 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010783 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010784 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10785
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010786 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010787
Sean Hunt30019c02010-04-07 22:57:35 +000010788 // unsigned long long int, long double, and any character type are allowed
10789 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010790 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10791 Context.hasSameType(T, Context.LongDoubleTy) ||
10792 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010793 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010794 Context.hasSameType(T, Context.Char16Ty) ||
10795 Context.hasSameType(T, Context.Char32Ty)) {
10796 if (++Param == FnDecl->param_end())
10797 Valid = true;
10798 goto FinishedParams;
10799 }
10800
Sean Hunt30019c02010-04-07 22:57:35 +000010801 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010802 const PointerType *PT = T->getAs<PointerType>();
10803 if (!PT)
10804 goto FinishedParams;
10805 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010806 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010807 goto FinishedParams;
10808 T = T.getUnqualifiedType();
10809
10810 // Move on to the second parameter;
10811 ++Param;
10812
10813 // If there is no second parameter, the first must be a const char *
10814 if (Param == FnDecl->param_end()) {
10815 if (Context.hasSameType(T, Context.CharTy))
10816 Valid = true;
10817 goto FinishedParams;
10818 }
10819
10820 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10821 // are allowed as the first parameter to a two-parameter function
10822 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010823 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010824 Context.hasSameType(T, Context.Char16Ty) ||
10825 Context.hasSameType(T, Context.Char32Ty)))
10826 goto FinishedParams;
10827
10828 // The second and final parameter must be an std::size_t
10829 T = (*Param)->getType().getUnqualifiedType();
10830 if (Context.hasSameType(T, Context.getSizeType()) &&
10831 ++Param == FnDecl->param_end())
10832 Valid = true;
10833 }
10834
10835 // FIXME: This diagnostic is absolutely terrible.
10836FinishedParams:
10837 if (!Valid) {
10838 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10839 << FnDecl->getDeclName();
10840 return true;
10841 }
10842
Richard Smitha9e88b22012-03-09 08:16:22 +000010843 // A parameter-declaration-clause containing a default argument is not
10844 // equivalent to any of the permitted forms.
10845 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10846 ParamEnd = FnDecl->param_end();
10847 Param != ParamEnd; ++Param) {
10848 if ((*Param)->hasDefaultArg()) {
10849 Diag((*Param)->getDefaultArgRange().getBegin(),
10850 diag::err_literal_operator_default_argument)
10851 << (*Param)->getDefaultArgRange();
10852 break;
10853 }
10854 }
10855
Richard Smith2fb4ae32012-03-08 02:39:21 +000010856 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010857 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10858 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010859 // C++11 [usrlit.suffix]p1:
10860 // Literal suffix identifiers that do not start with an underscore
10861 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000010862 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10863 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000010864 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010865
Sean Hunta6c058d2010-01-13 09:01:02 +000010866 return false;
10867}
10868
Douglas Gregor074149e2009-01-05 19:45:36 +000010869/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10870/// linkage specification, including the language and (if present)
10871/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10872/// the location of the language string literal, which is provided
10873/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10874/// the '{' brace. Otherwise, this linkage specification does not
10875/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010876Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10877 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010878 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010879 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010880 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010881 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010882 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010883 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010884 Language = LinkageSpecDecl::lang_cxx;
10885 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010886 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010887 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010888 }
Mike Stump1eb44332009-09-09 15:08:12 +000010889
Chris Lattnercc98eac2008-12-17 07:13:27 +000010890 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010891
Douglas Gregor074149e2009-01-05 19:45:36 +000010892 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010893 ExternLoc, LangLoc, Language,
10894 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010895 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010896 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010897 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010898}
10899
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010900/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010901/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10902/// valid, it's the position of the closing '}' brace in a linkage
10903/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010904Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010905 Decl *LinkageSpec,
10906 SourceLocation RBraceLoc) {
10907 if (LinkageSpec) {
10908 if (RBraceLoc.isValid()) {
10909 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10910 LSDecl->setRBraceLoc(RBraceLoc);
10911 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010912 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010913 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010914 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010915}
10916
Michael Han684aa732013-02-22 17:15:32 +000010917Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10918 AttributeList *AttrList,
10919 SourceLocation SemiLoc) {
10920 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10921 // Attribute declarations appertain to empty declaration so we handle
10922 // them here.
10923 if (AttrList)
10924 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010925
Michael Han684aa732013-02-22 17:15:32 +000010926 CurContext->addDecl(ED);
10927 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010928}
10929
Douglas Gregord308e622009-05-18 20:51:54 +000010930/// \brief Perform semantic analysis for the variable declaration that
10931/// occurs within a C++ catch clause, returning the newly-created
10932/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010933VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010934 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010935 SourceLocation StartLoc,
10936 SourceLocation Loc,
10937 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010938 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010939 QualType ExDeclType = TInfo->getType();
10940
Sebastian Redl4b07b292008-12-22 19:15:10 +000010941 // Arrays and functions decay.
10942 if (ExDeclType->isArrayType())
10943 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10944 else if (ExDeclType->isFunctionType())
10945 ExDeclType = Context.getPointerType(ExDeclType);
10946
10947 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10948 // The exception-declaration shall not denote a pointer or reference to an
10949 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010950 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010951 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010952 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010953 Invalid = true;
10954 }
Douglas Gregord308e622009-05-18 20:51:54 +000010955
Sebastian Redl4b07b292008-12-22 19:15:10 +000010956 QualType BaseType = ExDeclType;
10957 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010958 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010959 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010960 BaseType = Ptr->getPointeeType();
10961 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010962 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010963 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010964 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010965 BaseType = Ref->getPointeeType();
10966 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010967 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010968 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010969 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010970 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010971 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010972
Mike Stump1eb44332009-09-09 15:08:12 +000010973 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010974 RequireNonAbstractType(Loc, ExDeclType,
10975 diag::err_abstract_type_in_decl,
10976 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010977 Invalid = true;
10978
John McCall5a180392010-07-24 00:37:23 +000010979 // Only the non-fragile NeXT runtime currently supports C++ catches
10980 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010981 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010982 QualType T = ExDeclType;
10983 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10984 T = RT->getPointeeType();
10985
10986 if (T->isObjCObjectType()) {
10987 Diag(Loc, diag::err_objc_object_catch);
10988 Invalid = true;
10989 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010990 // FIXME: should this be a test for macosx-fragile specifically?
10991 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010992 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010993 }
10994 }
10995
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010996 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010997 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010998 ExDecl->setExceptionVariable(true);
10999
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011000 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011001 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011002 Invalid = true;
11003
Douglas Gregorc41b8782011-07-06 18:14:43 +000011004 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000011005 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000011006 // Insulate this from anything else we might currently be parsing.
11007 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11008
Douglas Gregor6d182892010-03-05 23:38:39 +000011009 // C++ [except.handle]p16:
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011010 // The object declared in an exception-declaration or, if the
11011 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6d182892010-03-05 23:38:39 +000011012 // copy-initialized (8.5) from the exception object. [...]
11013 // The object is destroyed when the handler exits, after the destruction
11014 // of any automatic objects initialized within the handler.
11015 //
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011016 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6d182892010-03-05 23:38:39 +000011017 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000011018 QualType initType = ExDeclType;
11019
11020 InitializedEntity entity =
11021 InitializedEntity::InitializeVariable(ExDecl);
11022 InitializationKind initKind =
11023 InitializationKind::CreateCopy(Loc, SourceLocation());
11024
11025 Expr *opaqueValue =
11026 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011027 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11028 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000011029 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000011030 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000011031 else {
11032 // If the constructor used was non-trivial, set this as the
11033 // "initializer".
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011034 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCalle996ffd2011-02-16 08:02:54 +000011035 if (!construct->getConstructor()->isTrivial()) {
11036 Expr *init = MaybeCreateExprWithCleanups(construct);
11037 ExDecl->setInit(init);
11038 }
11039
11040 // And make sure it's destructable.
11041 FinalizeVarWithDestructor(ExDecl, recordType);
11042 }
Douglas Gregor6d182892010-03-05 23:38:39 +000011043 }
11044 }
11045
Douglas Gregord308e622009-05-18 20:51:54 +000011046 if (Invalid)
11047 ExDecl->setInvalidDecl();
11048
11049 return ExDecl;
11050}
11051
11052/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11053/// handler.
John McCalld226f652010-08-21 09:40:31 +000011054Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000011055 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000011056 bool Invalid = D.isInvalidType();
11057
11058 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000011059 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11060 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000011061 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11062 D.getIdentifierLoc());
11063 Invalid = true;
11064 }
11065
Sebastian Redl4b07b292008-12-22 19:15:10 +000011066 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000011067 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000011068 LookupOrdinaryName,
11069 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011070 // The scope should be freshly made just for us. There is just no way
11071 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000011072 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000011073 if (PrevDecl->isTemplateParameter()) {
11074 // Maybe we will complain about the shadowed template parameter.
11075 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000011076 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011077 }
11078 }
11079
Chris Lattnereaaebc72009-04-25 08:06:05 +000011080 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011081 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11082 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000011083 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011084 }
11085
Douglas Gregor83cb9422010-09-09 17:09:21 +000011086 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000011087 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011088 D.getIdentifierLoc(),
11089 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000011090 if (Invalid)
11091 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000011092
Sebastian Redl4b07b292008-12-22 19:15:10 +000011093 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011094 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000011095 PushOnScopeChains(ExDecl, S);
11096 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011097 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000011098
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011099 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000011100 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011101}
Anders Carlssonfb311762009-03-14 00:25:26 +000011102
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011103Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000011104 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000011105 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011106 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000011107 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000011108
Richard Smithe3f470a2012-07-11 22:37:56 +000011109 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11110 return 0;
11111
11112 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11113 AssertMessage, RParenLoc, false);
11114}
11115
11116Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11117 Expr *AssertExpr,
11118 StringLiteral *AssertMessage,
11119 SourceLocation RParenLoc,
11120 bool Failed) {
11121 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11122 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000011123 // In a static_assert-declaration, the constant-expression shall be a
11124 // constant expression that can be contextually converted to bool.
11125 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11126 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011127 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000011128
Richard Smithdaaefc52011-12-14 23:32:26 +000011129 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000011130 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011131 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000011132 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011133 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000011134
Richard Smithe3f470a2012-07-11 22:37:56 +000011135 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011136 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000011137 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000011138 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011139 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000011140 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000011141 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000011142 }
Anders Carlssonc3082412009-03-14 00:33:21 +000011143 }
Mike Stump1eb44332009-09-09 15:08:12 +000011144
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011145 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000011146 AssertExpr, AssertMessage, RParenLoc,
11147 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000011148
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011149 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000011150 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000011151}
Sebastian Redl50de12f2009-03-24 22:27:57 +000011152
Douglas Gregor1d869352010-04-07 16:53:43 +000011153/// \brief Perform semantic analysis of the given friend type declaration.
11154///
11155/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000011156FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000011157 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011158 TypeSourceInfo *TSInfo) {
11159 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11160
11161 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000011162 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000011163
Richard Smith6b130222011-10-18 21:39:00 +000011164 // C++03 [class.friend]p2:
11165 // An elaborated-type-specifier shall be used in a friend declaration
11166 // for a class.*
11167 //
11168 // * The class-key of the elaborated-type-specifier is required.
11169 if (!ActiveTemplateInstantiations.empty()) {
11170 // Do not complain about the form of friend template types during
11171 // template instantiation; we will already have complained when the
11172 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011173 } else {
11174 if (!T->isElaboratedTypeSpecifier()) {
11175 // If we evaluated the type to a record type, suggest putting
11176 // a tag in front.
11177 if (const RecordType *RT = T->getAs<RecordType>()) {
11178 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000011179
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011180 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000011181
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011182 Diag(TypeRange.getBegin(),
11183 getLangOpts().CPlusPlus11 ?
11184 diag::warn_cxx98_compat_unelaborated_friend_type :
11185 diag::ext_unelaborated_friend_type)
11186 << (unsigned) RD->getTagKind()
11187 << T
11188 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11189 InsertionText);
11190 } else {
11191 Diag(FriendLoc,
11192 getLangOpts().CPlusPlus11 ?
11193 diag::warn_cxx98_compat_nonclass_type_friend :
11194 diag::ext_nonclass_type_friend)
11195 << T
11196 << TypeRange;
11197 }
11198 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000011199 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000011200 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011201 diag::warn_cxx98_compat_enum_friend :
11202 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000011203 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000011204 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000011205 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011206
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011207 // C++11 [class.friend]p3:
11208 // A friend declaration that does not declare a function shall have one
11209 // of the following forms:
11210 // friend elaborated-type-specifier ;
11211 // friend simple-type-specifier ;
11212 // friend typename-specifier ;
11213 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11214 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11215 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011216
Douglas Gregor06245bf2010-04-07 17:57:12 +000011217 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011218 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011219 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011220 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011221}
11222
John McCall9a34edb2010-10-19 01:40:49 +000011223/// Handle a friend tag declaration where the scope specifier was
11224/// templated.
11225Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11226 unsigned TagSpec, SourceLocation TagLoc,
11227 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011228 IdentifierInfo *Name,
11229 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011230 AttributeList *Attr,
11231 MultiTemplateParamsArg TempParamLists) {
11232 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11233
11234 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011235 bool Invalid = false;
11236
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011237 if (TemplateParameterList *TemplateParams =
11238 MatchTemplateParametersToScopeSpecifier(
11239 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11240 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011241 if (TemplateParams->size() > 0) {
11242 // This is a declaration of a class template.
11243 if (Invalid)
11244 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011245
Eric Christopher4110e132011-07-21 05:34:24 +000011246 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11247 SS, Name, NameLoc, Attr,
11248 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011249 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011250 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011251 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011252 } else {
11253 // The "template<>" header is extraneous.
11254 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11255 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11256 isExplicitSpecialization = true;
11257 }
11258 }
11259
11260 if (Invalid) return 0;
11261
John McCall9a34edb2010-10-19 01:40:49 +000011262 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011263 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011264 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011265 isAllExplicitSpecializations = false;
11266 break;
11267 }
11268 }
11269
11270 // FIXME: don't ignore attributes.
11271
11272 // If it's explicit specializations all the way down, just forget
11273 // about the template header and build an appropriate non-templated
11274 // friend. TODO: for source fidelity, remember the headers.
11275 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011276 if (SS.isEmpty()) {
11277 bool Owned = false;
11278 bool IsDependent = false;
11279 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11280 Attr, AS_public,
11281 /*ModulePrivateLoc=*/SourceLocation(),
11282 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011283 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011284 /*ScopedEnumUsesClassTag=*/false,
11285 /*UnderlyingType=*/TypeResult());
11286 }
11287
Douglas Gregor2494dd02011-03-01 01:34:45 +000011288 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011289 ElaboratedTypeKeyword Keyword
11290 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011291 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011292 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011293 if (T.isNull())
11294 return 0;
11295
11296 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11297 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011298 DependentNameTypeLoc TL =
11299 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011300 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011301 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011302 TL.setNameLoc(NameLoc);
11303 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011304 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011305 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011306 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011307 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011308 }
11309
11310 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011311 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011312 Friend->setAccess(AS_public);
11313 CurContext->addDecl(Friend);
11314 return Friend;
11315 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011316
11317 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11318
11319
John McCall9a34edb2010-10-19 01:40:49 +000011320
11321 // Handle the case of a templated-scope friend class. e.g.
11322 // template <class T> class A<T>::B;
11323 // FIXME: we don't support these right now.
11324 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11325 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11326 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011327 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011328 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011329 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011330 TL.setNameLoc(NameLoc);
11331
11332 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011333 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011334 Friend->setAccess(AS_public);
11335 Friend->setUnsupportedFriend(true);
11336 CurContext->addDecl(Friend);
11337 return Friend;
11338}
11339
11340
John McCalldd4a3b02009-09-16 22:47:08 +000011341/// Handle a friend type declaration. This works in tandem with
11342/// ActOnTag.
11343///
11344/// Notes on friend class templates:
11345///
11346/// We generally treat friend class declarations as if they were
11347/// declaring a class. So, for example, the elaborated type specifier
11348/// in a friend declaration is required to obey the restrictions of a
11349/// class-head (i.e. no typedefs in the scope chain), template
11350/// parameters are required to match up with simple template-ids, &c.
11351/// However, unlike when declaring a template specialization, it's
11352/// okay to refer to a template specialization without an empty
11353/// template parameter declaration, e.g.
11354/// friend class A<T>::B<unsigned>;
11355/// We permit this as a special case; if there are any template
11356/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011357/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011358Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011359 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011360 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011361
11362 assert(DS.isFriendSpecified());
11363 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11364
John McCalldd4a3b02009-09-16 22:47:08 +000011365 // Try to convert the decl specifier to a type. This works for
11366 // friend templates because ActOnTag never produces a ClassTemplateDecl
11367 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011368 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011369 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11370 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011371 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011372 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011373
Douglas Gregor6ccab972010-12-16 01:14:37 +000011374 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11375 return 0;
11376
John McCalldd4a3b02009-09-16 22:47:08 +000011377 // This is definitely an error in C++98. It's probably meant to
11378 // be forbidden in C++0x, too, but the specification is just
11379 // poorly written.
11380 //
11381 // The problem is with declarations like the following:
11382 // template <T> friend A<T>::foo;
11383 // where deciding whether a class C is a friend or not now hinges
11384 // on whether there exists an instantiation of A that causes
11385 // 'foo' to equal C. There are restrictions on class-heads
11386 // (which we declare (by fiat) elaborated friend declarations to
11387 // be) that makes this tractable.
11388 //
11389 // FIXME: handle "template <> friend class A<T>;", which
11390 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011391 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011392 Diag(Loc, diag::err_tagless_friend_type_template)
11393 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011394 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011395 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011396
John McCall02cace72009-08-28 07:59:38 +000011397 // C++98 [class.friend]p1: A friend of a class is a function
11398 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011399 // This is fixed in DR77, which just barely didn't make the C++03
11400 // deadline. It's also a very silly restriction that seriously
11401 // affects inner classes and which nobody else seems to implement;
11402 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011403 //
11404 // But note that we could warn about it: it's always useless to
11405 // friend one of your own members (it's not, however, worthless to
11406 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011407
John McCalldd4a3b02009-09-16 22:47:08 +000011408 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011409 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011410 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011411 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011412 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011413 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011414 DS.getFriendSpecLoc());
11415 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011416 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011417
11418 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011419 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011420
John McCalldd4a3b02009-09-16 22:47:08 +000011421 D->setAccess(AS_public);
11422 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011423
John McCalld226f652010-08-21 09:40:31 +000011424 return D;
John McCall02cace72009-08-28 07:59:38 +000011425}
11426
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011427NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11428 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011429 const DeclSpec &DS = D.getDeclSpec();
11430
11431 assert(DS.isFriendSpecified());
11432 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11433
11434 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011435 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011436
11437 // C++ [class.friend]p1
11438 // A friend of a class is a function or class....
11439 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011440 // It *doesn't* see through dependent types, which is correct
11441 // according to [temp.arg.type]p3:
11442 // If a declaration acquires a function type through a
11443 // type dependent on a template-parameter and this causes
11444 // a declaration that does not use the syntactic form of a
11445 // function declarator to have a function type, the program
11446 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011447 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011448 Diag(Loc, diag::err_unexpected_friend);
11449
11450 // It might be worthwhile to try to recover by creating an
11451 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011452 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011453 }
11454
11455 // C++ [namespace.memdef]p3
11456 // - If a friend declaration in a non-local class first declares a
11457 // class or function, the friend class or function is a member
11458 // of the innermost enclosing namespace.
11459 // - The name of the friend is not found by simple name lookup
11460 // until a matching declaration is provided in that namespace
11461 // scope (either before or after the class declaration granting
11462 // friendship).
11463 // - If a friend function is called, its name may be found by the
11464 // name lookup that considers functions from namespaces and
11465 // classes associated with the types of the function arguments.
11466 // - When looking for a prior declaration of a class or a function
11467 // declared as a friend, scopes outside the innermost enclosing
11468 // namespace scope are not considered.
11469
John McCall337ec3d2010-10-12 23:13:28 +000011470 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011471 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11472 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011473 assert(Name);
11474
Douglas Gregor6ccab972010-12-16 01:14:37 +000011475 // Check for unexpanded parameter packs.
11476 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11477 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11478 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11479 return 0;
11480
John McCall67d1a672009-08-06 02:15:43 +000011481 // The context we found the declaration in, or in which we should
11482 // create the declaration.
11483 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011484 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011485 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011486 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011487
Richard Smith4e9686b2013-08-09 04:35:01 +000011488 // There are five cases here.
11489 // - There's no scope specifier and we're in a local class. Only look
11490 // for functions declared in the immediately-enclosing block scope.
11491 // We recover from invalid scope qualifiers as if they just weren't there.
11492 FunctionDecl *FunctionContainingLocalClass = 0;
11493 if ((SS.isInvalid() || !SS.isSet()) &&
11494 (FunctionContainingLocalClass =
11495 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11496 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000011497 // If a friend declaration appears in a local class and the name
11498 // specified is an unqualified name, a prior declaration is
11499 // looked up without considering scopes that are outside the
11500 // innermost enclosing non-class scope. For a friend function
11501 // declaration, if there is no prior declaration, the program is
11502 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000011503
11504 // Find the innermost enclosing non-class scope. This is the block
11505 // scope containing the local class definition (or for a nested class,
11506 // the outer local class).
11507 DCScope = S->getFnParent();
11508
11509 // Look up the function name in the scope.
11510 Previous.clear(LookupLocalFriendName);
11511 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11512
11513 if (!Previous.empty()) {
11514 // All possible previous declarations must have the same context:
11515 // either they were declared at block scope or they are members of
11516 // one of the enclosing local classes.
11517 DC = Previous.getRepresentativeDecl()->getDeclContext();
11518 } else {
11519 // This is ill-formed, but provide the context that we would have
11520 // declared the function in, if we were permitted to, for error recovery.
11521 DC = FunctionContainingLocalClass;
11522 }
Richard Smitha41c97a2013-09-20 01:15:31 +000011523 adjustContextForLocalExternDecl(DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011524
11525 // C++ [class.friend]p6:
11526 // A function can be defined in a friend declaration of a class if and
11527 // only if the class is a non-local class (9.8), the function name is
11528 // unqualified, and the function has namespace scope.
11529 if (D.isFunctionDefinition()) {
11530 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11531 }
11532
11533 // - There's no scope specifier, in which case we just go to the
11534 // appropriate scope and look for a function or function template
11535 // there as appropriate.
11536 } else if (SS.isInvalid() || !SS.isSet()) {
11537 // C++11 [namespace.memdef]p3:
11538 // If the name in a friend declaration is neither qualified nor
11539 // a template-id and the declaration is a function or an
11540 // elaborated-type-specifier, the lookup to determine whether
11541 // the entity has been previously declared shall not consider
11542 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000011543 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011544
John McCall29ae6e52010-10-13 05:45:15 +000011545 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011546 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011547
Rafael Espindola11dc6342013-04-25 20:12:36 +000011548 // Skip class contexts. If someone can cite chapter and verse
11549 // for this behavior, that would be nice --- it's what GCC and
11550 // EDG do, and it seems like a reasonable intent, but the spec
11551 // really only says that checks for unqualified existing
11552 // declarations should stop at the nearest enclosing namespace,
11553 // not that they should only consider the nearest enclosing
11554 // namespace.
11555 while (DC->isRecord())
11556 DC = DC->getParent();
11557
11558 DeclContext *LookupDC = DC;
11559 while (LookupDC->isTransparentContext())
11560 LookupDC = LookupDC->getParent();
11561
11562 while (true) {
11563 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011564
Rafael Espindola11dc6342013-04-25 20:12:36 +000011565 if (!Previous.empty()) {
11566 DC = LookupDC;
11567 break;
John McCall8a407372010-10-14 22:22:28 +000011568 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011569
11570 if (isTemplateId) {
11571 if (isa<TranslationUnitDecl>(LookupDC)) break;
11572 } else {
11573 if (LookupDC->isFileContext()) break;
11574 }
11575 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011576 }
11577
John McCall380aaa42010-10-13 06:22:15 +000011578 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011579
John McCall337ec3d2010-10-12 23:13:28 +000011580 // - There's a non-dependent scope specifier, in which case we
11581 // compute it and do a previous lookup there for a function
11582 // or function template.
11583 } else if (!SS.getScopeRep()->isDependent()) {
11584 DC = computeDeclContext(SS);
11585 if (!DC) return 0;
11586
11587 if (RequireCompleteDeclContext(SS, DC)) return 0;
11588
11589 LookupQualifiedName(Previous, DC);
11590
11591 // Ignore things found implicitly in the wrong scope.
11592 // TODO: better diagnostics for this case. Suggesting the right
11593 // qualified scope would be nice...
11594 LookupResult::Filter F = Previous.makeFilter();
11595 while (F.hasNext()) {
11596 NamedDecl *D = F.next();
11597 if (!DC->InEnclosingNamespaceSetOf(
11598 D->getDeclContext()->getRedeclContext()))
11599 F.erase();
11600 }
11601 F.done();
11602
11603 if (Previous.empty()) {
11604 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011605 Diag(Loc, diag::err_qualified_friend_not_found)
11606 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011607 return 0;
11608 }
11609
11610 // C++ [class.friend]p1: A friend of a class is a function or
11611 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011612 if (DC->Equals(CurContext))
11613 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011614 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011615 diag::warn_cxx98_compat_friend_is_member :
11616 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011617
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011618 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011619 // C++ [class.friend]p6:
11620 // A function can be defined in a friend declaration of a class if and
11621 // only if the class is a non-local class (9.8), the function name is
11622 // unqualified, and the function has namespace scope.
11623 SemaDiagnosticBuilder DB
11624 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11625
11626 DB << SS.getScopeRep();
11627 if (DC->isFileContext())
11628 DB << FixItHint::CreateRemoval(SS.getRange());
11629 SS.clear();
11630 }
John McCall337ec3d2010-10-12 23:13:28 +000011631
11632 // - There's a scope specifier that does not match any template
11633 // parameter lists, in which case we use some arbitrary context,
11634 // create a method or method template, and wait for instantiation.
11635 // - There's a scope specifier that does match some template
11636 // parameter lists, which we don't handle right now.
11637 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011638 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011639 // C++ [class.friend]p6:
11640 // A function can be defined in a friend declaration of a class if and
11641 // only if the class is a non-local class (9.8), the function name is
11642 // unqualified, and the function has namespace scope.
11643 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11644 << SS.getScopeRep();
11645 }
11646
John McCall337ec3d2010-10-12 23:13:28 +000011647 DC = CurContext;
11648 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011649 }
Douglas Gregor883af832011-10-10 01:11:59 +000011650
John McCall29ae6e52010-10-13 05:45:15 +000011651 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011652 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011653 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11654 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11655 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011656 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011657 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11658 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011659 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011660 }
John McCall67d1a672009-08-06 02:15:43 +000011661 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011662
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011663 // FIXME: This is an egregious hack to cope with cases where the scope stack
11664 // does not contain the declaration context, i.e., in an out-of-line
11665 // definition of a class.
11666 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11667 if (!DCScope) {
11668 FakeDCScope.setEntity(DC);
11669 DCScope = &FakeDCScope;
11670 }
Richard Smith4e9686b2013-08-09 04:35:01 +000011671
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011672 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011673 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011674 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011675 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011676
Douglas Gregor182ddf02009-09-28 00:08:27 +000011677 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011678
Richard Smith4e9686b2013-08-09 04:35:01 +000011679 // If we performed typo correction, we might have added a scope specifier
11680 // and changed the decl context.
11681 DC = ND->getDeclContext();
11682
John McCallab88d972009-08-31 22:39:49 +000011683 // Add the function declaration to the appropriate lookup tables,
11684 // adjusting the redeclarations list as necessary. We don't
11685 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011686 //
John McCallab88d972009-08-31 22:39:49 +000011687 // Also update the scope-based lookup if the target context's
11688 // lookup context is in lexical scope.
11689 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011690 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011691 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011692 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011693 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011694 }
John McCall02cace72009-08-28 07:59:38 +000011695
11696 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011697 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011698 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011699 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011700 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011701
John McCall1f2e1a92012-08-10 03:15:35 +000011702 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011703 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011704 } else {
11705 if (DC->isRecord()) CheckFriendAccess(ND);
11706
John McCall6102ca12010-10-16 06:59:13 +000011707 FunctionDecl *FD;
11708 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11709 FD = FTD->getTemplatedDecl();
11710 else
11711 FD = cast<FunctionDecl>(ND);
11712
David Majnemerf6a144f2013-06-25 23:09:30 +000011713 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11714 // default argument expression, that declaration shall be a definition
11715 // and shall be the only declaration of the function or function
11716 // template in the translation unit.
11717 if (functionDeclHasDefaultArgument(FD)) {
11718 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11719 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11720 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11721 } else if (!D.isFunctionDefinition())
11722 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11723 }
11724
John McCall6102ca12010-10-16 06:59:13 +000011725 // Mark templated-scope function declarations as unsupported.
11726 if (FD->getNumTemplateParameterLists())
11727 FrD->setUnsupportedFriend(true);
11728 }
John McCall337ec3d2010-10-12 23:13:28 +000011729
John McCalld226f652010-08-21 09:40:31 +000011730 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011731}
11732
John McCalld226f652010-08-21 09:40:31 +000011733void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11734 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011735
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011736 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011737 if (!Fn) {
11738 Diag(DelLoc, diag::err_deleted_non_function);
11739 return;
11740 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011741
Douglas Gregoref96ee02012-01-14 16:38:05 +000011742 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011743 // Don't consider the implicit declaration we generate for explicit
11744 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011745 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11746 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011747 Diag(DelLoc, diag::err_deleted_decl_not_first);
11748 Diag(Prev->getLocation(), diag::note_previous_declaration);
11749 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011750 // If the declaration wasn't the first, we delete the function anyway for
11751 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011752 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011753 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011754
11755 if (Fn->isDeleted())
11756 return;
11757
11758 // See if we're deleting a function which is already known to override a
11759 // non-deleted virtual function.
11760 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11761 bool IssuedDiagnostic = false;
11762 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11763 E = MD->end_overridden_methods();
11764 I != E; ++I) {
11765 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11766 if (!IssuedDiagnostic) {
11767 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11768 IssuedDiagnostic = true;
11769 }
11770 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11771 }
11772 }
11773 }
11774
Sean Hunt10620eb2011-05-06 20:44:56 +000011775 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011776}
Sebastian Redl13e88542009-04-27 21:33:24 +000011777
Sean Hunte4246a62011-05-12 06:15:49 +000011778void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011779 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011780
11781 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011782 if (MD->getParent()->isDependentType()) {
11783 MD->setDefaulted();
11784 MD->setExplicitlyDefaulted();
11785 return;
11786 }
11787
Sean Hunte4246a62011-05-12 06:15:49 +000011788 CXXSpecialMember Member = getSpecialMember(MD);
11789 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011790 if (!MD->isInvalidDecl())
11791 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000011792 return;
11793 }
11794
11795 MD->setDefaulted();
11796 MD->setExplicitlyDefaulted();
11797
Sean Huntcd10dec2011-05-23 23:14:04 +000011798 // If this definition appears within the record, do the checking when
11799 // the record is complete.
11800 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011801 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011802 // Find the uninstantiated declaration that actually had the '= default'
11803 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011804 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011805
Richard Smith12fef492013-03-27 00:22:47 +000011806 // If the method was defaulted on its first declaration, we will have
11807 // already performed the checking in CheckCompletedCXXClass. Such a
11808 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011809 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011810 return;
11811
Richard Smithb9d0b762012-07-27 04:22:15 +000011812 CheckExplicitlyDefaultedSpecialMember(MD);
11813
Richard Smith1d28caf2012-12-11 01:14:52 +000011814 // The exception specification is needed because we are defining the
11815 // function.
11816 ResolveExceptionSpec(DefaultLoc,
11817 MD->getType()->castAs<FunctionProtoType>());
11818
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011819 if (MD->isInvalidDecl())
11820 return;
11821
Sean Hunte4246a62011-05-12 06:15:49 +000011822 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011823 case CXXDefaultConstructor:
11824 DefineImplicitDefaultConstructor(DefaultLoc,
11825 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000011826 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011827 case CXXCopyConstructor:
11828 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000011829 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011830 case CXXCopyAssignment:
11831 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000011832 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011833 case CXXDestructor:
11834 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000011835 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011836 case CXXMoveConstructor:
11837 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000011838 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011839 case CXXMoveAssignment:
11840 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011841 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011842 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011843 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011844 }
11845 } else {
11846 Diag(DefaultLoc, diag::err_default_special_members);
11847 }
11848}
11849
Sebastian Redl13e88542009-04-27 21:33:24 +000011850static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011851 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011852 Stmt *SubStmt = *CI;
11853 if (!SubStmt)
11854 continue;
11855 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011856 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011857 diag::err_return_in_constructor_handler);
11858 if (!isa<Expr>(SubStmt))
11859 SearchForReturnInStmt(Self, SubStmt);
11860 }
11861}
11862
11863void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11864 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11865 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11866 SearchForReturnInStmt(*this, Handler);
11867 }
11868}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011869
David Blaikie299adab2013-01-18 23:03:15 +000011870bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011871 const CXXMethodDecl *Old) {
11872 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11873 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11874
11875 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11876
11877 // If the calling conventions match, everything is fine
11878 if (NewCC == OldCC)
11879 return false;
11880
Reid Kleckneref072032013-08-27 23:08:25 +000011881 Diag(New->getLocation(),
11882 diag::err_conflicting_overriding_cc_attributes)
11883 << New->getDeclName() << New->getType() << Old->getType();
11884 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11885 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011886}
11887
Mike Stump1eb44332009-09-09 15:08:12 +000011888bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011889 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011890 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11891 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011892
Chandler Carruth73857792010-02-15 11:53:20 +000011893 if (Context.hasSameType(NewTy, OldTy) ||
11894 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011895 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011896
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011897 // Check if the return types are covariant
11898 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011899
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011900 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011901 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11902 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011903 NewClassTy = NewPT->getPointeeType();
11904 OldClassTy = OldPT->getPointeeType();
11905 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011906 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11907 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11908 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11909 NewClassTy = NewRT->getPointeeType();
11910 OldClassTy = OldRT->getPointeeType();
11911 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011912 }
11913 }
Mike Stump1eb44332009-09-09 15:08:12 +000011914
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011915 // The return types aren't either both pointers or references to a class type.
11916 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011917 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011918 diag::err_different_return_type_for_overriding_virtual_function)
11919 << New->getDeclName() << NewTy << OldTy;
11920 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011921
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011922 return true;
11923 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011924
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011925 // C++ [class.virtual]p6:
11926 // If the return type of D::f differs from the return type of B::f, the
11927 // class type in the return type of D::f shall be complete at the point of
11928 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011929 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11930 if (!RT->isBeingDefined() &&
11931 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011932 diag::err_covariant_return_incomplete,
11933 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011934 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011935 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011936
Douglas Gregora4923eb2009-11-16 21:35:15 +000011937 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011938 // Check if the new class derives from the old class.
11939 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11940 Diag(New->getLocation(),
11941 diag::err_covariant_return_not_derived)
11942 << New->getDeclName() << NewTy << OldTy;
11943 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11944 return true;
11945 }
Mike Stump1eb44332009-09-09 15:08:12 +000011946
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011947 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011948 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011949 diag::err_covariant_return_inaccessible_base,
11950 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11951 // FIXME: Should this point to the return type?
11952 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011953 // FIXME: this note won't trigger for delayed access control
11954 // diagnostics, and it's impossible to get an undelayed error
11955 // here from access control during the original parse because
11956 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011957 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11958 return true;
11959 }
11960 }
Mike Stump1eb44332009-09-09 15:08:12 +000011961
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011962 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011963 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011964 Diag(New->getLocation(),
11965 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011966 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011967 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11968 return true;
11969 };
Mike Stump1eb44332009-09-09 15:08:12 +000011970
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011971
11972 // The new class type must have the same or less qualifiers as the old type.
11973 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11974 Diag(New->getLocation(),
11975 diag::err_covariant_return_type_class_type_more_qualified)
11976 << New->getDeclName() << NewTy << OldTy;
11977 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11978 return true;
11979 };
Mike Stump1eb44332009-09-09 15:08:12 +000011980
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011981 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011982}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011983
Douglas Gregor4ba31362009-12-01 17:24:26 +000011984/// \brief Mark the given method pure.
11985///
11986/// \param Method the method to be marked pure.
11987///
11988/// \param InitRange the source range that covers the "0" initializer.
11989bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011990 SourceLocation EndLoc = InitRange.getEnd();
11991 if (EndLoc.isValid())
11992 Method->setRangeEnd(EndLoc);
11993
Douglas Gregor4ba31362009-12-01 17:24:26 +000011994 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11995 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011996 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011997 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011998
11999 if (!Method->isInvalidDecl())
12000 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12001 << Method->getDeclName() << InitRange;
12002 return true;
12003}
12004
Douglas Gregor552e2992012-02-21 02:22:07 +000012005/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012006static bool isStaticDataMember(const Decl *D) {
12007 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12008 return Var->isStaticDataMember();
12009
12010 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000012011}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012012
John McCall731ad842009-12-19 09:28:58 +000012013/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12014/// an initializer for the out-of-line declaration 'Dcl'. The scope
12015/// is a fresh scope pushed for just this purpose.
12016///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012017/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12018/// static data member of class X, names should be looked up in the scope of
12019/// class X.
John McCalld226f652010-08-21 09:40:31 +000012020void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012021 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012022 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012023
John McCall731ad842009-12-19 09:28:58 +000012024 // We should only get called for declarations with scope specifiers, like:
12025 // int foo::bar;
12026 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012027 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000012028
12029 // If we are parsing the initializer for a static data member, push a
12030 // new expression evaluation context that is associated with this static
12031 // data member.
12032 if (isStaticDataMember(D))
12033 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012034}
12035
12036/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000012037/// initializer for the out-of-line declaration 'D'.
12038void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012039 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012040 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012041
Douglas Gregor552e2992012-02-21 02:22:07 +000012042 if (isStaticDataMember(D))
12043 PopExpressionEvaluationContext();
12044
John McCall731ad842009-12-19 09:28:58 +000012045 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012046 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012047}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012048
12049/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12050/// C++ if/switch/while/for statement.
12051/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000012052DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012053 // C++ 6.4p2:
12054 // The declarator shall not specify a function or an array.
12055 // The type-specifier-seq shall not contain typedef and shall not declare a
12056 // new class or enumeration.
12057 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12058 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012059
12060 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000012061 if (!Dcl)
12062 return true;
12063
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012064 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12065 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012066 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000012067 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012068 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012069
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012070 return Dcl;
12071}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012072
Douglas Gregordfe65432011-07-28 19:11:31 +000012073void Sema::LoadExternalVTableUses() {
12074 if (!ExternalSource)
12075 return;
12076
12077 SmallVector<ExternalVTableUse, 4> VTables;
12078 ExternalSource->ReadUsedVTables(VTables);
12079 SmallVector<VTableUse, 4> NewUses;
12080 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12081 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12082 = VTablesUsed.find(VTables[I].Record);
12083 // Even if a definition wasn't required before, it may be required now.
12084 if (Pos != VTablesUsed.end()) {
12085 if (!Pos->second && VTables[I].DefinitionRequired)
12086 Pos->second = true;
12087 continue;
12088 }
12089
12090 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12091 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12092 }
12093
12094 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12095}
12096
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012097void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12098 bool DefinitionRequired) {
12099 // Ignore any vtable uses in unevaluated operands or for classes that do
12100 // not have a vtable.
12101 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000012102 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000012103 return;
12104
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012105 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000012106 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012107 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12108 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12109 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12110 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000012111 // If we already had an entry, check to see if we are promoting this vtable
12112 // to required a definition. If so, we need to reappend to the VTableUses
12113 // list, since we may have already processed the first entry.
12114 if (DefinitionRequired && !Pos.first->second) {
12115 Pos.first->second = true;
12116 } else {
12117 // Otherwise, we can early exit.
12118 return;
12119 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012120 }
12121
12122 // Local classes need to have their virtual members marked
12123 // immediately. For all other classes, we mark their virtual members
12124 // at the end of the translation unit.
12125 if (Class->isLocalClass())
12126 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000012127 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012128 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000012129}
12130
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012131bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000012132 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012133 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000012134 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000012135
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012136 // Note: The VTableUses vector could grow as a result of marking
12137 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000012138 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012139 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000012140 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012141 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000012142 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012143 if (!Class)
12144 continue;
12145
12146 SourceLocation Loc = VTableUses[I].second;
12147
Richard Smithb9d0b762012-07-27 04:22:15 +000012148 bool DefineVTable = true;
12149
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012150 // If this class has a key function, but that key function is
12151 // defined in another translation unit, we don't need to emit the
12152 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000012153 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000012154 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000012155 // The key function is in another translation unit.
12156 DefineVTable = false;
12157 TemplateSpecializationKind TSK =
12158 KeyFunction->getTemplateSpecializationKind();
12159 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12160 TSK != TSK_ImplicitInstantiation &&
12161 "Instantiations don't have key functions");
12162 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012163 } else if (!KeyFunction) {
12164 // If we have a class with no key function that is the subject
12165 // of an explicit instantiation declaration, suppress the
12166 // vtable; it will live with the explicit instantiation
12167 // definition.
12168 bool IsExplicitInstantiationDeclaration
12169 = Class->getTemplateSpecializationKind()
12170 == TSK_ExplicitInstantiationDeclaration;
12171 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12172 REnd = Class->redecls_end();
12173 R != REnd; ++R) {
12174 TemplateSpecializationKind TSK
12175 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12176 if (TSK == TSK_ExplicitInstantiationDeclaration)
12177 IsExplicitInstantiationDeclaration = true;
12178 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12179 IsExplicitInstantiationDeclaration = false;
12180 break;
12181 }
12182 }
12183
12184 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000012185 DefineVTable = false;
12186 }
12187
12188 // The exception specifications for all virtual members may be needed even
12189 // if we are not providing an authoritative form of the vtable in this TU.
12190 // We may choose to emit it available_externally anyway.
12191 if (!DefineVTable) {
12192 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12193 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012194 }
12195
12196 // Mark all of the virtual members of this class as referenced, so
12197 // that we can build a vtable. Then, tell the AST consumer that a
12198 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012199 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012200 MarkVirtualMembersReferenced(Loc, Class);
12201 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12202 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12203
12204 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012205 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012206 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000012207 const FunctionDecl *KeyFunctionDef = 0;
12208 if (!KeyFunction ||
12209 (KeyFunction->hasBody(KeyFunctionDef) &&
12210 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012211 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12212 TSK_ExplicitInstantiationDefinition
12213 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12214 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012215 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012216 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012217 VTableUses.clear();
12218
Douglas Gregor78844032011-04-22 22:25:37 +000012219 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012220}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012221
Richard Smithb9d0b762012-07-27 04:22:15 +000012222void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12223 const CXXRecordDecl *RD) {
12224 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12225 E = RD->method_end(); I != E; ++I)
12226 if ((*I)->isVirtual() && !(*I)->isPure())
12227 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12228}
12229
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012230void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12231 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012232 // Mark all functions which will appear in RD's vtable as used.
12233 CXXFinalOverriderMap FinalOverriders;
12234 RD->getFinalOverriders(FinalOverriders);
12235 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12236 E = FinalOverriders.end();
12237 I != E; ++I) {
12238 for (OverridingMethods::const_iterator OI = I->second.begin(),
12239 OE = I->second.end();
12240 OI != OE; ++OI) {
12241 assert(OI->second.size() > 0 && "no final overrider");
12242 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012243
Richard Smithff817f72012-07-07 06:59:51 +000012244 // C++ [basic.def.odr]p2:
12245 // [...] A virtual member function is used if it is not pure. [...]
12246 if (!Overrider->isPure())
12247 MarkFunctionReferenced(Loc, Overrider);
12248 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012249 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012250
12251 // Only classes that have virtual bases need a VTT.
12252 if (RD->getNumVBases() == 0)
12253 return;
12254
12255 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12256 e = RD->bases_end(); i != e; ++i) {
12257 const CXXRecordDecl *Base =
12258 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012259 if (Base->getNumVBases() == 0)
12260 continue;
12261 MarkVirtualMembersReferenced(Loc, Base);
12262 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012263}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012264
12265/// SetIvarInitializers - This routine builds initialization ASTs for the
12266/// Objective-C implementation whose ivars need be initialized.
12267void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012268 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012269 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012270 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012271 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012272 CollectIvarsToConstructOrDestruct(OID, ivars);
12273 if (ivars.empty())
12274 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012275 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012276 for (unsigned i = 0; i < ivars.size(); i++) {
12277 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012278 if (Field->isInvalidDecl())
12279 continue;
12280
Sean Huntcbb67482011-01-08 20:30:50 +000012281 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012282 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12283 InitializationKind InitKind =
12284 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012285
12286 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12287 ExprResult MemberInit =
12288 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012289 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012290 // Note, MemberInit could actually come back empty if no initialization
12291 // is required (e.g., because it would call a trivial default constructor)
12292 if (!MemberInit.get() || MemberInit.isInvalid())
12293 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012294
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012295 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012296 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12297 SourceLocation(),
12298 MemberInit.takeAs<Expr>(),
12299 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012300 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012301
12302 // Be sure that the destructor is accessible and is marked as referenced.
12303 if (const RecordType *RecordTy
12304 = Context.getBaseElementType(Field->getType())
12305 ->getAs<RecordType>()) {
12306 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012307 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012308 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012309 CheckDestructorAccess(Field->getLocation(), Destructor,
12310 PDiag(diag::err_access_dtor_ivar)
12311 << Context.getBaseElementType(Field->getType()));
12312 }
12313 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012314 }
12315 ObjCImplementation->setIvarInitializers(Context,
12316 AllToInit.data(), AllToInit.size());
12317 }
12318}
Sean Huntfe57eef2011-05-04 05:57:24 +000012319
Sean Huntebcbe1d2011-05-04 23:29:54 +000012320static
12321void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12322 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12323 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12324 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12325 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012326 if (Ctor->isInvalidDecl())
12327 return;
12328
Richard Smitha8eaf002012-08-23 06:16:52 +000012329 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12330
12331 // Target may not be determinable yet, for instance if this is a dependent
12332 // call in an uninstantiated template.
12333 if (Target) {
12334 const FunctionDecl *FNTarget = 0;
12335 (void)Target->hasBody(FNTarget);
12336 Target = const_cast<CXXConstructorDecl*>(
12337 cast_or_null<CXXConstructorDecl>(FNTarget));
12338 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012339
12340 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12341 // Avoid dereferencing a null pointer here.
12342 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12343
12344 if (!Current.insert(Canonical))
12345 return;
12346
12347 // We know that beyond here, we aren't chaining into a cycle.
12348 if (!Target || !Target->isDelegatingConstructor() ||
12349 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012350 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012351 Current.clear();
12352 // We've hit a cycle.
12353 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12354 Current.count(TCanonical)) {
12355 // If we haven't diagnosed this cycle yet, do so now.
12356 if (!Invalid.count(TCanonical)) {
12357 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012358 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012359 << Ctor;
12360
Richard Smitha8eaf002012-08-23 06:16:52 +000012361 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012362 if (TCanonical != Canonical)
12363 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12364
12365 CXXConstructorDecl *C = Target;
12366 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012367 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012368 (void)C->getTargetConstructor()->hasBody(FNTarget);
12369 assert(FNTarget && "Ctor cycle through bodiless function");
12370
Richard Smitha8eaf002012-08-23 06:16:52 +000012371 C = const_cast<CXXConstructorDecl*>(
12372 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012373 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12374 }
12375 }
12376
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012377 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012378 Current.clear();
12379 } else {
12380 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12381 }
12382}
12383
12384
Sean Huntfe57eef2011-05-04 05:57:24 +000012385void Sema::CheckDelegatingCtorCycles() {
12386 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12387
Douglas Gregor0129b562011-07-27 21:57:17 +000012388 for (DelegatingCtorDeclsType::iterator
12389 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012390 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012391 I != E; ++I)
12392 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012393
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012394 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12395 CE = Invalid.end();
12396 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012397 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012398}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012399
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012400namespace {
12401 /// \brief AST visitor that finds references to the 'this' expression.
12402 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12403 Sema &S;
12404
12405 public:
12406 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12407
12408 bool VisitCXXThisExpr(CXXThisExpr *E) {
12409 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12410 << E->isImplicit();
12411 return false;
12412 }
12413 };
12414}
12415
12416bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12417 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12418 if (!TSInfo)
12419 return false;
12420
12421 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012422 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012423 if (!ProtoTL)
12424 return false;
12425
12426 // C++11 [expr.prim.general]p3:
12427 // [The expression this] shall not appear before the optional
12428 // cv-qualifier-seq and it shall not appear within the declaration of a
12429 // static member function (although its type and value category are defined
12430 // within a static member function as they are within a non-static member
12431 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012432 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012433 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012434 FindCXXThisExpr Finder(*this);
12435
12436 // If the return type came after the cv-qualifier-seq, check it now.
12437 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012438 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012439 return true;
12440
12441 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012442 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12443 return true;
12444
12445 return checkThisInStaticMemberFunctionAttributes(Method);
12446}
12447
12448bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12449 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12450 if (!TSInfo)
12451 return false;
12452
12453 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012454 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012455 if (!ProtoTL)
12456 return false;
12457
David Blaikie39e6ab42013-02-18 22:06:02 +000012458 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012459 FindCXXThisExpr Finder(*this);
12460
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012461 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012462 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012463 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012464 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012465 case EST_DynamicNone:
12466 case EST_MSAny:
12467 case EST_None:
12468 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012469
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012470 case EST_ComputedNoexcept:
12471 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12472 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012473
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012474 case EST_Dynamic:
12475 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012476 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012477 E != EEnd; ++E) {
12478 if (!Finder.TraverseType(*E))
12479 return true;
12480 }
12481 break;
12482 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012483
12484 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012485}
12486
12487bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12488 FindCXXThisExpr Finder(*this);
12489
12490 // Check attributes.
12491 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12492 A != AEnd; ++A) {
12493 // FIXME: This should be emitted by tblgen.
12494 Expr *Arg = 0;
12495 ArrayRef<Expr *> Args;
12496 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12497 Arg = G->getArg();
12498 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12499 Arg = G->getArg();
12500 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12501 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12502 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12503 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12504 else if (ExclusiveLockFunctionAttr *ELF
12505 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12506 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12507 else if (SharedLockFunctionAttr *SLF
12508 = dyn_cast<SharedLockFunctionAttr>(*A))
12509 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12510 else if (ExclusiveTrylockFunctionAttr *ETLF
12511 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12512 Arg = ETLF->getSuccessValue();
12513 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12514 } else if (SharedTrylockFunctionAttr *STLF
12515 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12516 Arg = STLF->getSuccessValue();
12517 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12518 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12519 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12520 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12521 Arg = LR->getArg();
12522 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12523 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12524 else if (ExclusiveLocksRequiredAttr *ELR
12525 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12526 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12527 else if (SharedLocksRequiredAttr *SLR
12528 = dyn_cast<SharedLocksRequiredAttr>(*A))
12529 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12530
12531 if (Arg && !Finder.TraverseStmt(Arg))
12532 return true;
12533
12534 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12535 if (!Finder.TraverseStmt(Args[I]))
12536 return true;
12537 }
12538 }
12539
12540 return false;
12541}
12542
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012543void
12544Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12545 ArrayRef<ParsedType> DynamicExceptions,
12546 ArrayRef<SourceRange> DynamicExceptionRanges,
12547 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012548 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012549 FunctionProtoType::ExtProtoInfo &EPI) {
12550 Exceptions.clear();
12551 EPI.ExceptionSpecType = EST;
12552 if (EST == EST_Dynamic) {
12553 Exceptions.reserve(DynamicExceptions.size());
12554 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12555 // FIXME: Preserve type source info.
12556 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12557
12558 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12559 collectUnexpandedParameterPacks(ET, Unexpanded);
12560 if (!Unexpanded.empty()) {
12561 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12562 UPPC_ExceptionType,
12563 Unexpanded);
12564 continue;
12565 }
12566
12567 // Check that the type is valid for an exception spec, and
12568 // drop it if not.
12569 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12570 Exceptions.push_back(ET);
12571 }
12572 EPI.NumExceptions = Exceptions.size();
12573 EPI.Exceptions = Exceptions.data();
12574 return;
12575 }
12576
12577 if (EST == EST_ComputedNoexcept) {
12578 // If an error occurred, there's no expression here.
12579 if (NoexceptExpr) {
12580 assert((NoexceptExpr->isTypeDependent() ||
12581 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12582 Context.BoolTy) &&
12583 "Parser should have made sure that the expression is boolean");
12584 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12585 EPI.ExceptionSpecType = EST_BasicNoexcept;
12586 return;
12587 }
12588
12589 if (!NoexceptExpr->isValueDependent())
12590 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012591 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012592 /*AllowFold*/ false).take();
12593 EPI.NoexceptExpr = NoexceptExpr;
12594 }
12595 return;
12596 }
12597}
12598
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012599/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12600Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12601 // Implicitly declared functions (e.g. copy constructors) are
12602 // __host__ __device__
12603 if (D->isImplicit())
12604 return CFT_HostDevice;
12605
12606 if (D->hasAttr<CUDAGlobalAttr>())
12607 return CFT_Global;
12608
12609 if (D->hasAttr<CUDADeviceAttr>()) {
12610 if (D->hasAttr<CUDAHostAttr>())
12611 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012612 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012613 }
12614
12615 return CFT_Host;
12616}
12617
12618bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12619 CUDAFunctionTarget CalleeTarget) {
12620 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12621 // Callable from the device only."
12622 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12623 return true;
12624
12625 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12626 // Callable from the host only."
12627 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12628 // Callable from the host only."
12629 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12630 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12631 return true;
12632
12633 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12634 return true;
12635
12636 return false;
12637}
John McCall76da55d2013-04-16 07:28:30 +000012638
12639/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12640///
12641MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12642 SourceLocation DeclStart,
12643 Declarator &D, Expr *BitWidth,
12644 InClassInitStyle InitStyle,
12645 AccessSpecifier AS,
12646 AttributeList *MSPropertyAttr) {
12647 IdentifierInfo *II = D.getIdentifier();
12648 if (!II) {
12649 Diag(DeclStart, diag::err_anonymous_property);
12650 return NULL;
12651 }
12652 SourceLocation Loc = D.getIdentifierLoc();
12653
12654 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12655 QualType T = TInfo->getType();
12656 if (getLangOpts().CPlusPlus) {
12657 CheckExtraCXXDefaultArguments(D);
12658
12659 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12660 UPPC_DataMemberType)) {
12661 D.setInvalidType();
12662 T = Context.IntTy;
12663 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12664 }
12665 }
12666
12667 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12668
12669 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12670 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12671 diag::err_invalid_thread)
12672 << DeclSpec::getSpecifierName(TSCS);
12673
12674 // Check to see if this name was declared as a member previously
12675 NamedDecl *PrevDecl = 0;
12676 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12677 LookupName(Previous, S);
12678 switch (Previous.getResultKind()) {
12679 case LookupResult::Found:
12680 case LookupResult::FoundUnresolvedValue:
12681 PrevDecl = Previous.getAsSingle<NamedDecl>();
12682 break;
12683
12684 case LookupResult::FoundOverloaded:
12685 PrevDecl = Previous.getRepresentativeDecl();
12686 break;
12687
12688 case LookupResult::NotFound:
12689 case LookupResult::NotFoundInCurrentInstantiation:
12690 case LookupResult::Ambiguous:
12691 break;
12692 }
12693
12694 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12695 // Maybe we will complain about the shadowed template parameter.
12696 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12697 // Just pretend that we didn't see the previous declaration.
12698 PrevDecl = 0;
12699 }
12700
12701 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12702 PrevDecl = 0;
12703
12704 SourceLocation TSSL = D.getLocStart();
12705 MSPropertyDecl *NewPD;
12706 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12707 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12708 II, T, TInfo, TSSL,
12709 Data.GetterId, Data.SetterId);
12710 ProcessDeclAttributes(TUScope, NewPD, D);
12711 NewPD->setAccess(AS);
12712
12713 if (NewPD->isInvalidDecl())
12714 Record->setInvalidDecl();
12715
12716 if (D.getDeclSpec().isModulePrivateSpecified())
12717 NewPD->setModulePrivate();
12718
12719 if (NewPD->isInvalidDecl() && PrevDecl) {
12720 // Don't introduce NewFD into scope; there's already something
12721 // with the same name in the same scope.
12722 } else if (II) {
12723 PushOnScopeChains(NewPD, S);
12724 } else
12725 Record->addDecl(NewPD);
12726
12727 return NewPD;
12728}