blob: 655c9e2c3d0d351d41b395c0edb266f241ac6bb7 [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
Anders Carlsson1d209272011-03-25 14:55:14 +00001373 // C++ [class]p3:
1374 // If a class is marked final and it appears as a base-type-specifier in
1375 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001376 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001377 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1378 << CXXBaseDecl->getDeclName();
1379 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1380 << CXXBaseDecl->getDeclName();
1381 return 0;
1382 }
1383
John McCall572fc622010-08-17 07:23:57 +00001384 if (BaseDecl->isInvalidDecl())
1385 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001386
1387 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001388 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001389 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001390 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001391}
1392
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001393/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1394/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001395/// example:
1396/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001397/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001398BaseResult
John McCalld226f652010-08-21 09:40:31 +00001399Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001400 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001401 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001402 ParsedType basetype, SourceLocation BaseLoc,
1403 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001404 if (!classdecl)
1405 return true;
1406
Douglas Gregor40808ce2009-03-09 23:48:35 +00001407 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001408 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001409 if (!Class)
1410 return true;
1411
Richard Smith05321402013-02-19 23:47:15 +00001412 // We do not support any C++11 attributes on base-specifiers yet.
1413 // Diagnose any attributes we see.
1414 if (!Attributes.empty()) {
1415 for (AttributeList *Attr = Attributes.getList(); Attr;
1416 Attr = Attr->getNext()) {
1417 if (Attr->isInvalid() ||
1418 Attr->getKind() == AttributeList::IgnoredAttribute)
1419 continue;
1420 Diag(Attr->getLoc(),
1421 Attr->getKind() == AttributeList::UnknownAttribute
1422 ? diag::warn_unknown_attribute_ignored
1423 : diag::err_base_specifier_attribute)
1424 << Attr->getName();
1425 }
1426 }
1427
Nick Lewycky56062202010-07-26 16:56:01 +00001428 TypeSourceInfo *TInfo = 0;
1429 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001430
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001431 if (EllipsisLoc.isInvalid() &&
1432 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001433 UPPC_BaseType))
1434 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001435
Douglas Gregor2943aed2009-03-03 04:44:36 +00001436 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001437 Virtual, Access, TInfo,
1438 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001439 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001440 else
1441 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Douglas Gregor2943aed2009-03-03 04:44:36 +00001443 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001444}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001445
Douglas Gregor2943aed2009-03-03 04:44:36 +00001446/// \brief Performs the actual work of attaching the given base class
1447/// specifiers to a C++ class.
1448bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1449 unsigned NumBases) {
1450 if (NumBases == 0)
1451 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001452
1453 // Used to keep track of which base types we have already seen, so
1454 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001455 // that the key is always the unqualified canonical type of the base
1456 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001457 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1458
1459 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001460 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001461 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001462 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001463 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001464 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001465 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001466
1467 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1468 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001469 // C++ [class.mi]p3:
1470 // A class shall not be specified as a direct base class of a
1471 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001472 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001473 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001474 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001475 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001476
1477 // Delete the duplicate base class specifier; we're going to
1478 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001479 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001480
1481 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001482 } else {
1483 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001484 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001485 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001486 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1487 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1488 if (Class->isInterface() &&
1489 (!RD->isInterface() ||
1490 KnownBase->getAccessSpecifier() != AS_public)) {
1491 // The Microsoft extension __interface does not permit bases that
1492 // are not themselves public interfaces.
1493 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1494 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1495 << RD->getSourceRange();
1496 Invalid = true;
1497 }
1498 if (RD->hasAttr<WeakAttr>())
1499 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1500 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001501 }
1502 }
1503
1504 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001505 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001506
1507 // Delete the remaining (good) base class specifiers, since their
1508 // data has been copied into the CXXRecordDecl.
1509 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001510 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001511
1512 return Invalid;
1513}
1514
1515/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1516/// class, after checking whether there are any duplicate base
1517/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001518void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001519 unsigned NumBases) {
1520 if (!ClassDecl || !Bases || !NumBases)
1521 return;
1522
1523 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001524 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001525}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001526
Douglas Gregora8f32e02009-10-06 17:59:45 +00001527/// \brief Determine whether the type \p Derived is a C++ class that is
1528/// derived from the type \p Base.
1529bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001530 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001531 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001532
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001533 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001534 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001535 return false;
1536
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001537 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001538 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001539 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001540
1541 // If either the base or the derived type is invalid, don't try to
1542 // check whether one is derived from the other.
1543 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1544 return false;
1545
John McCall86ff3082010-02-04 22:26:26 +00001546 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1547 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001548}
1549
1550/// \brief Determine whether the type \p Derived is a C++ class that is
1551/// derived from the type \p Base.
1552bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001553 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001554 return false;
1555
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001556 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001557 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001558 return false;
1559
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001560 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001561 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001562 return false;
1563
Douglas Gregora8f32e02009-10-06 17:59:45 +00001564 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1565}
1566
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001567void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001568 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001569 assert(BasePathArray.empty() && "Base path array must be empty!");
1570 assert(Paths.isRecordingPaths() && "Must record paths!");
1571
1572 const CXXBasePath &Path = Paths.front();
1573
1574 // We first go backward and check if we have a virtual base.
1575 // FIXME: It would be better if CXXBasePath had the base specifier for
1576 // the nearest virtual base.
1577 unsigned Start = 0;
1578 for (unsigned I = Path.size(); I != 0; --I) {
1579 if (Path[I - 1].Base->isVirtual()) {
1580 Start = I - 1;
1581 break;
1582 }
1583 }
1584
1585 // Now add all bases.
1586 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001587 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001588}
1589
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001590/// \brief Determine whether the given base path includes a virtual
1591/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001592bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1593 for (CXXCastPath::const_iterator B = BasePath.begin(),
1594 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001595 B != BEnd; ++B)
1596 if ((*B)->isVirtual())
1597 return true;
1598
1599 return false;
1600}
1601
Douglas Gregora8f32e02009-10-06 17:59:45 +00001602/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1603/// conversion (where Derived and Base are class types) is
1604/// well-formed, meaning that the conversion is unambiguous (and
1605/// that all of the base classes are accessible). Returns true
1606/// and emits a diagnostic if the code is ill-formed, returns false
1607/// otherwise. Loc is the location where this routine should point to
1608/// if there is an error, and Range is the source range to highlight
1609/// if there is an error.
1610bool
1611Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001612 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001613 unsigned AmbigiousBaseConvID,
1614 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001615 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001616 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001617 // First, determine whether the path from Derived to Base is
1618 // ambiguous. This is slightly more expensive than checking whether
1619 // the Derived to Base conversion exists, because here we need to
1620 // explore multiple paths to determine if there is an ambiguity.
1621 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1622 /*DetectVirtual=*/false);
1623 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1624 assert(DerivationOkay &&
1625 "Can only be used with a derived-to-base conversion");
1626 (void)DerivationOkay;
1627
1628 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001629 if (InaccessibleBaseID) {
1630 // Check that the base class can be accessed.
1631 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1632 InaccessibleBaseID)) {
1633 case AR_inaccessible:
1634 return true;
1635 case AR_accessible:
1636 case AR_dependent:
1637 case AR_delayed:
1638 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001639 }
John McCall6b2accb2010-02-10 09:31:12 +00001640 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001641
1642 // Build a base path if necessary.
1643 if (BasePath)
1644 BuildBasePathArray(Paths, *BasePath);
1645 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001646 }
1647
David Majnemer2f686692013-06-22 06:43:58 +00001648 if (AmbigiousBaseConvID) {
1649 // We know that the derived-to-base conversion is ambiguous, and
1650 // we're going to produce a diagnostic. Perform the derived-to-base
1651 // search just one more time to compute all of the possible paths so
1652 // that we can print them out. This is more expensive than any of
1653 // the previous derived-to-base checks we've done, but at this point
1654 // performance isn't as much of an issue.
1655 Paths.clear();
1656 Paths.setRecordingPaths(true);
1657 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1658 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1659 (void)StillOkay;
1660
1661 // Build up a textual representation of the ambiguous paths, e.g.,
1662 // D -> B -> A, that will be used to illustrate the ambiguous
1663 // conversions in the diagnostic. We only print one of the paths
1664 // to each base class subobject.
1665 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1666
1667 Diag(Loc, AmbigiousBaseConvID)
1668 << Derived << Base << PathDisplayStr << Range << Name;
1669 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001670 return true;
1671}
1672
1673bool
1674Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001675 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001676 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001677 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001678 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001679 IgnoreAccess ? 0
1680 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001681 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001682 Loc, Range, DeclarationName(),
1683 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001684}
1685
1686
1687/// @brief Builds a string representing ambiguous paths from a
1688/// specific derived class to different subobjects of the same base
1689/// class.
1690///
1691/// This function builds a string that can be used in error messages
1692/// to show the different paths that one can take through the
1693/// inheritance hierarchy to go from the derived class to different
1694/// subobjects of a base class. The result looks something like this:
1695/// @code
1696/// struct D -> struct B -> struct A
1697/// struct D -> struct C -> struct A
1698/// @endcode
1699std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1700 std::string PathDisplayStr;
1701 std::set<unsigned> DisplayedPaths;
1702 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1703 Path != Paths.end(); ++Path) {
1704 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1705 // We haven't displayed a path to this particular base
1706 // class subobject yet.
1707 PathDisplayStr += "\n ";
1708 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1709 for (CXXBasePath::const_iterator Element = Path->begin();
1710 Element != Path->end(); ++Element)
1711 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1712 }
1713 }
1714
1715 return PathDisplayStr;
1716}
1717
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001718//===----------------------------------------------------------------------===//
1719// C++ class member Handling
1720//===----------------------------------------------------------------------===//
1721
Abramo Bagnara6206d532010-06-05 05:09:32 +00001722/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001723bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1724 SourceLocation ASLoc,
1725 SourceLocation ColonLoc,
1726 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001727 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001728 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001729 ASLoc, ColonLoc);
1730 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001731 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001732}
1733
Richard Smitha4b39652012-08-06 03:25:17 +00001734/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmandae92712013-09-05 23:51:03 +00001735void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001736 if (D->isInvalidDecl())
1737 return;
1738
Eli Friedmandae92712013-09-05 23:51:03 +00001739 // We only care about "override" and "final" declarations.
1740 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1741 return;
Anders Carlsson9e682d92011-01-20 05:57:14 +00001742
Eli Friedmandae92712013-09-05 23:51:03 +00001743 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001744
Eli Friedmandae92712013-09-05 23:51:03 +00001745 // We can't check dependent instance methods.
1746 if (MD && MD->isInstance() &&
1747 (MD->getParent()->hasAnyDependentBases() ||
1748 MD->getType()->isDependentType()))
1749 return;
1750
1751 if (MD && !MD->isVirtual()) {
1752 // If we have a non-virtual method, check if if hides a virtual method.
1753 // (In that case, it's most likely the method has the wrong type.)
1754 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1755 FindHiddenVirtualMethods(MD, OverloadedMethods);
1756
1757 if (!OverloadedMethods.empty()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001758 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1759 Diag(OA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001760 diag::override_keyword_hides_virtual_member_function)
1761 << "override" << (OverloadedMethods.size() > 1);
1762 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001763 Diag(FA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001764 diag::override_keyword_hides_virtual_member_function)
1765 << "final" << (OverloadedMethods.size() > 1);
Richard Smitha4b39652012-08-06 03:25:17 +00001766 }
Eli Friedmandae92712013-09-05 23:51:03 +00001767 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1768 MD->setInvalidDecl();
1769 return;
1770 }
1771 // Fall through into the general case diagnostic.
1772 // FIXME: We might want to attempt typo correction here.
1773 }
1774
1775 if (!MD || !MD->isVirtual()) {
1776 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1777 Diag(OA->getLocation(),
1778 diag::override_keyword_only_allowed_on_virtual_member_functions)
1779 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1780 D->dropAttr<OverrideAttr>();
1781 }
1782 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1783 Diag(FA->getLocation(),
1784 diag::override_keyword_only_allowed_on_virtual_member_functions)
1785 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1786 D->dropAttr<FinalAttr>();
Richard Smitha4b39652012-08-06 03:25:17 +00001787 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001788 return;
1789 }
Richard Smitha4b39652012-08-06 03:25:17 +00001790
Richard Smitha4b39652012-08-06 03:25:17 +00001791 // C++11 [class.virtual]p5:
1792 // If a virtual function is marked with the virt-specifier override and
1793 // does not override a member function of a base class, the program is
1794 // ill-formed.
1795 bool HasOverriddenMethods =
1796 MD->begin_overridden_methods() != MD->end_overridden_methods();
1797 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1798 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1799 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001800}
1801
Richard Smitha4b39652012-08-06 03:25:17 +00001802/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001803/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001804/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001805bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1806 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001807 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001808 return false;
1809
1810 Diag(New->getLocation(), diag::err_final_function_overridden)
1811 << New->getDeclName();
1812 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1813 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001814}
1815
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001816static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001817 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1818 // FIXME: Destruction of ObjC lifetime types has side-effects.
1819 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1820 return !RD->isCompleteDefinition() ||
1821 !RD->hasTrivialDefaultConstructor() ||
1822 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001823 return false;
1824}
1825
John McCall76da55d2013-04-16 07:28:30 +00001826static AttributeList *getMSPropertyAttr(AttributeList *list) {
1827 for (AttributeList* it = list; it != 0; it = it->getNext())
1828 if (it->isDeclspecPropertyAttribute())
1829 return it;
1830 return 0;
1831}
1832
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001833/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1834/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001835/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001836/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1837/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001838NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001839Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001840 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001841 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001842 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001843 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001844 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1845 DeclarationName Name = NameInfo.getName();
1846 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001847
1848 // For anonymous bitfields, the location should point to the type.
1849 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001850 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001851
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001852 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001853
John McCall4bde1e12010-06-04 08:34:12 +00001854 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001855 assert(!DS.isFriendSpecified());
1856
Richard Smith1ab0d902011-06-25 02:28:38 +00001857 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001858
John McCalle402e722012-09-25 07:32:39 +00001859 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1860 // The Microsoft extension __interface only permits public member functions
1861 // and prohibits constructors, destructors, operators, non-public member
1862 // functions, static methods and data members.
1863 unsigned InvalidDecl;
1864 bool ShowDeclName = true;
1865 if (!isFunc)
1866 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1867 else if (AS != AS_public)
1868 InvalidDecl = 2;
1869 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1870 InvalidDecl = 3;
1871 else switch (Name.getNameKind()) {
1872 case DeclarationName::CXXConstructorName:
1873 InvalidDecl = 4;
1874 ShowDeclName = false;
1875 break;
1876
1877 case DeclarationName::CXXDestructorName:
1878 InvalidDecl = 5;
1879 ShowDeclName = false;
1880 break;
1881
1882 case DeclarationName::CXXOperatorName:
1883 case DeclarationName::CXXConversionFunctionName:
1884 InvalidDecl = 6;
1885 break;
1886
1887 default:
1888 InvalidDecl = 0;
1889 break;
1890 }
1891
1892 if (InvalidDecl) {
1893 if (ShowDeclName)
1894 Diag(Loc, diag::err_invalid_member_in_interface)
1895 << (InvalidDecl-1) << Name;
1896 else
1897 Diag(Loc, diag::err_invalid_member_in_interface)
1898 << (InvalidDecl-1) << "";
1899 return 0;
1900 }
1901 }
1902
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001903 // C++ 9.2p6: A member shall not be declared to have automatic storage
1904 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001905 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1906 // data members and cannot be applied to names declared const or static,
1907 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001908 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001909 case DeclSpec::SCS_unspecified:
1910 case DeclSpec::SCS_typedef:
1911 case DeclSpec::SCS_static:
1912 break;
1913 case DeclSpec::SCS_mutable:
1914 if (isFunc) {
1915 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Richard Smithec642442013-04-12 22:46:28 +00001917 // FIXME: It would be nicer if the keyword was ignored only for this
1918 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001919 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001920 }
1921 break;
1922 default:
1923 Diag(DS.getStorageClassSpecLoc(),
1924 diag::err_storageclass_invalid_for_member);
1925 D.getMutableDeclSpec().ClearStorageClassSpecs();
1926 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001927 }
1928
Sebastian Redl669d5d72008-11-14 23:42:31 +00001929 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1930 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001931 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001932
David Blaikie1d87fba2013-01-30 01:22:18 +00001933 if (DS.isConstexprSpecified() && isInstField) {
1934 SemaDiagnosticBuilder B =
1935 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1936 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1937 if (InitStyle == ICIS_NoInit) {
1938 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1939 D.getMutableDeclSpec().ClearConstexprSpec();
1940 const char *PrevSpec;
1941 unsigned DiagID;
1942 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1943 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001944 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001945 assert(!Failed && "Making a constexpr member const shouldn't fail");
1946 } else {
1947 B << 1;
1948 const char *PrevSpec;
1949 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001950 if (D.getMutableDeclSpec().SetStorageClassSpec(
1951 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001952 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001953 "This is the only DeclSpec that should fail to be applied");
1954 B << 1;
1955 } else {
1956 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1957 isInstField = false;
1958 }
1959 }
1960 }
1961
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001962 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001963 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001964 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001965
1966 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001967 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001968 Diag(Loc, diag::err_bad_variable_name)
1969 << Name;
1970 return 0;
1971 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001972
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001973 IdentifierInfo *II = Name.getAsIdentifierInfo();
1974
Douglas Gregorf2503652011-09-21 14:40:46 +00001975 // Member field could not be with "template" keyword.
1976 // So TemplateParameterLists should be empty in this case.
1977 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001978 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001979 if (TemplateParams->size()) {
1980 // There is no such thing as a member field template.
1981 Diag(D.getIdentifierLoc(), diag::err_template_member)
1982 << II
1983 << SourceRange(TemplateParams->getTemplateLoc(),
1984 TemplateParams->getRAngleLoc());
1985 } else {
1986 // There is an extraneous 'template<>' for this member.
1987 Diag(TemplateParams->getTemplateLoc(),
1988 diag::err_template_member_noparams)
1989 << II
1990 << SourceRange(TemplateParams->getTemplateLoc(),
1991 TemplateParams->getRAngleLoc());
1992 }
1993 return 0;
1994 }
1995
Douglas Gregor922fff22010-10-13 22:19:53 +00001996 if (SS.isSet() && !SS.isInvalid()) {
1997 // The user provided a superfluous scope specifier inside a class
1998 // definition:
1999 //
2000 // class X {
2001 // int X::member;
2002 // };
Douglas Gregor69605872012-03-28 16:01:27 +00002003 if (DeclContext *DC = computeDeclContext(SS, false))
2004 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00002005 else
2006 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2007 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00002008
Douglas Gregor922fff22010-10-13 22:19:53 +00002009 SS.clear();
2010 }
Douglas Gregorf2503652011-09-21 14:40:46 +00002011
John McCall76da55d2013-04-16 07:28:30 +00002012 AttributeList *MSPropertyAttr =
2013 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00002014 if (MSPropertyAttr) {
2015 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2016 BitWidth, InitStyle, AS, MSPropertyAttr);
2017 if (!Member)
2018 return 0;
2019 isInstField = false;
2020 } else {
2021 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2022 BitWidth, InitStyle, AS);
2023 assert(Member && "HandleField never returns null");
2024 }
2025 } else {
2026 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2027
2028 Member = HandleDeclarator(S, D, TemplateParameterLists);
2029 if (!Member)
2030 return 0;
2031
2032 // Non-instance-fields can't have a bitfield.
2033 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002034 if (Member->isInvalidDecl()) {
2035 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002036 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002037 // C++ 9.6p3: A bit-field shall not be a static member.
2038 // "static member 'A' cannot be a bit-field"
2039 Diag(Loc, diag::err_static_not_bitfield)
2040 << Name << BitWidth->getSourceRange();
2041 } else if (isa<TypedefDecl>(Member)) {
2042 // "typedef member 'x' cannot be a bit-field"
2043 Diag(Loc, diag::err_typedef_not_bitfield)
2044 << Name << BitWidth->getSourceRange();
2045 } else {
2046 // A function typedef ("typedef int f(); f a;").
2047 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2048 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00002049 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00002050 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00002051 }
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Chris Lattner8b963ef2009-03-05 23:01:03 +00002053 BitWidth = 0;
2054 Member->setInvalidDecl();
2055 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002056
2057 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Larisse Voufoef4579c2013-08-06 01:03:05 +00002059 // If we have declared a member function template or static data member
2060 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002061 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2062 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002063 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2064 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002065 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002066
Richard Smitha4b39652012-08-06 03:25:17 +00002067 if (VS.isOverrideSpecified())
2068 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2069 if (VS.isFinalSpecified())
2070 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002071
Douglas Gregorf5251602011-03-08 17:10:18 +00002072 if (VS.getLastLocation().isValid()) {
2073 // Update the end location of a method that has a virt-specifiers.
2074 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2075 MD->setRangeEnd(VS.getLastLocation());
2076 }
Richard Smitha4b39652012-08-06 03:25:17 +00002077
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002078 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002079
Douglas Gregor10bd3682008-11-17 22:58:34 +00002080 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002081
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002082 if (isInstField) {
2083 FieldDecl *FD = cast<FieldDecl>(Member);
2084 FieldCollector->Add(FD);
2085
2086 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2087 FD->getLocation())
2088 != DiagnosticsEngine::Ignored) {
2089 // Remember all explicit private FieldDecls that have a name, no side
2090 // effects and are not part of a dependent type declaration.
2091 if (!FD->isImplicit() && FD->getDeclName() &&
2092 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002093 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002094 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002095 !InitializationHasSideEffects(*FD))
2096 UnusedPrivateFields.insert(FD);
2097 }
2098 }
2099
John McCalld226f652010-08-21 09:40:31 +00002100 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002101}
2102
Hans Wennborg471f9852012-09-18 15:58:06 +00002103namespace {
2104 class UninitializedFieldVisitor
2105 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2106 Sema &S;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002107 // If VD is null, this visitor will only update the Decls set.
Hans Wennborg471f9852012-09-18 15:58:06 +00002108 ValueDecl *VD;
Richard Trieufbb08b52013-09-13 03:20:53 +00002109 bool isReferenceType;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002110 // List of Decls to generate a warning on.
2111 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
2112 bool WarnOnSelfReference;
2113 // If non-null, add a note to the warning pointing back to the constructor.
2114 const CXXConstructorDecl *Constructor;
Hans Wennborg471f9852012-09-18 15:58:06 +00002115 public:
2116 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002117 UninitializedFieldVisitor(Sema &S, ValueDecl *VD,
2118 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2119 bool WarnOnSelfReference,
2120 const CXXConstructorDecl *Constructor)
2121 : Inherited(S.Context), S(S), VD(VD), isReferenceType(false), Decls(Decls),
2122 WarnOnSelfReference(WarnOnSelfReference), Constructor(Constructor) {
2123 // When VD is null, this visitor is used to detect initialization of other
2124 // fields.
2125 if (VD) {
2126 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2127 this->VD = IFD->getAnonField();
2128 else
2129 this->VD = VD;
2130 isReferenceType = this->VD->getType()->isReferenceType();
2131 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002132 }
2133
Richard Trieu3ddec882013-09-16 20:46:50 +00002134 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002135 if (!VD)
2136 return;
2137
Richard Trieu3ddec882013-09-16 20:46:50 +00002138 if (CheckReferenceOnly && !isReferenceType)
2139 return;
2140
Richard Trieufbb08b52013-09-13 03:20:53 +00002141 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2142 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002143
Richard Trieufbb08b52013-09-13 03:20:53 +00002144 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2145 // or union.
2146 MemberExpr *FieldME = ME;
2147
2148 Expr *Base = ME;
2149 while (isa<MemberExpr>(Base)) {
2150 ME = cast<MemberExpr>(Base);
2151
2152 if (isa<VarDecl>(ME->getMemberDecl()))
2153 return;
2154
2155 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2156 if (!FD->isAnonymousStructOrUnion())
2157 FieldME = ME;
2158
2159 Base = ME->getBase();
2160 }
2161
Richard Trieu3ddec882013-09-16 20:46:50 +00002162 if (!isa<CXXThisExpr>(Base))
2163 return;
2164
Richard Trieuef8f90c2013-09-20 03:03:06 +00002165 ValueDecl* FoundVD = FieldME->getMemberDecl();
2166
2167 if (VD == FoundVD) {
2168 if (!WarnOnSelfReference)
2169 return;
2170
Richard Trieu3ddec882013-09-16 20:46:50 +00002171 unsigned diag = isReferenceType
Richard Trieufbb08b52013-09-13 03:20:53 +00002172 ? diag::warn_reference_field_is_uninit
2173 : diag::warn_field_is_uninit;
2174 S.Diag(FieldME->getExprLoc(), diag) << VD;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002175 if (Constructor)
2176 S.Diag(Constructor->getLocation(),
2177 diag::note_uninit_in_this_constructor);
2178 return;
2179 }
2180
2181 if (CheckReferenceOnly)
2182 return;
2183
2184 if (Decls.count(FoundVD)) {
2185 S.Diag(FieldME->getExprLoc(), diag::warn_field_is_uninit) << FoundVD;
2186 if (Constructor)
2187 S.Diag(Constructor->getLocation(),
2188 diag::note_uninit_in_this_constructor);
2189
Richard Trieufbb08b52013-09-13 03:20:53 +00002190 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002191 }
2192
2193 void HandleValue(Expr *E) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002194 if (!VD)
2195 return;
2196
Hans Wennborg471f9852012-09-18 15:58:06 +00002197 E = E->IgnoreParens();
2198
2199 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002200 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002201 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002202 }
2203
2204 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2205 HandleValue(CO->getTrueExpr());
2206 HandleValue(CO->getFalseExpr());
2207 return;
2208 }
2209
2210 if (BinaryConditionalOperator *BCO =
2211 dyn_cast<BinaryConditionalOperator>(E)) {
2212 HandleValue(BCO->getCommon());
2213 HandleValue(BCO->getFalseExpr());
2214 return;
2215 }
2216
2217 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2218 switch (BO->getOpcode()) {
2219 default:
2220 return;
2221 case(BO_PtrMemD):
2222 case(BO_PtrMemI):
2223 HandleValue(BO->getLHS());
2224 return;
2225 case(BO_Comma):
2226 HandleValue(BO->getRHS());
2227 return;
2228 }
2229 }
2230 }
2231
Richard Trieufbb08b52013-09-13 03:20:53 +00002232 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002233 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002234
2235 Inherited::VisitMemberExpr(ME);
2236 }
2237
Hans Wennborg471f9852012-09-18 15:58:06 +00002238 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2239 if (E->getCastKind() == CK_LValueToRValue)
2240 HandleValue(E->getSubExpr());
2241
2242 Inherited::VisitImplicitCastExpr(E);
2243 }
2244
Richard Trieufbb08b52013-09-13 03:20:53 +00002245 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002246 if (E->getConstructor()->isCopyConstructor())
Richard Trieufbb08b52013-09-13 03:20:53 +00002247 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2248 if (ICE->getCastKind() == CK_NoOp)
2249 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieu3ddec882013-09-16 20:46:50 +00002250 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002251
2252 Inherited::VisitCXXConstructExpr(E);
2253 }
2254
Hans Wennborg471f9852012-09-18 15:58:06 +00002255 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2256 Expr *Callee = E->getCallee();
2257 if (isa<MemberExpr>(Callee))
2258 HandleValue(Callee);
2259
2260 Inherited::VisitCXXMemberCallExpr(E);
2261 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002262
2263 void VisitBinaryOperator(BinaryOperator *E) {
2264 // If a field assignment is detected, remove the field from the
2265 // uninitiailized field set.
2266 if (E->getOpcode() == BO_Assign)
2267 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2268 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2269 Decls.erase(FD);
2270
2271 Inherited::VisitBinaryOperator(E);
2272 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002273 };
Richard Trieuef8f90c2013-09-20 03:03:06 +00002274 static void CheckInitExprContainsUninitializedFields(
2275 Sema &S, Expr *E, ValueDecl *VD, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2276 bool WarnOnSelfReference, const CXXConstructorDecl *Constructor = 0) {
2277 if (Decls.size() == 0 && !WarnOnSelfReference)
2278 return;
2279
Richard Trieufbb08b52013-09-13 03:20:53 +00002280 if (E)
Richard Trieuef8f90c2013-09-20 03:03:06 +00002281 UninitializedFieldVisitor(S, VD, Decls, WarnOnSelfReference, Constructor)
2282 .Visit(E);
Hans Wennborg471f9852012-09-18 15:58:06 +00002283 }
2284} // namespace
2285
Richard Smith7a614d82011-06-11 17:19:42 +00002286/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002287/// in-class initializer for a non-static C++ class member, and after
2288/// instantiating an in-class initializer in a class template. Such actions
2289/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002290void
Richard Smithca523302012-06-10 03:12:00 +00002291Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002292 Expr *InitExpr) {
2293 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002294 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2295 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002296
2297 if (!InitExpr) {
2298 FD->setInvalidDecl();
2299 FD->removeInClassInitializer();
2300 return;
2301 }
2302
Peter Collingbournefef21892011-10-23 18:59:44 +00002303 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2304 FD->setInvalidDecl();
2305 FD->removeInClassInitializer();
2306 return;
2307 }
2308
Richard Smith7a614d82011-06-11 17:19:42 +00002309 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002310 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002311 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002312 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002313 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002314 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002315 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2316 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002317 if (Init.isInvalid()) {
2318 FD->setInvalidDecl();
2319 return;
2320 }
Richard Smith7a614d82011-06-11 17:19:42 +00002321 }
2322
Richard Smith41956372013-01-14 22:39:08 +00002323 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002324 // The initialization of each base and member constitutes a
2325 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002326 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002327 if (Init.isInvalid()) {
2328 FD->setInvalidDecl();
2329 return;
2330 }
2331
2332 InitExpr = Init.release();
2333
2334 FD->setInClassInitializer(InitExpr);
2335}
2336
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002337/// \brief Find the direct and/or virtual base specifiers that
2338/// correspond to the given base type, for use in base initialization
2339/// within a constructor.
2340static bool FindBaseInitializer(Sema &SemaRef,
2341 CXXRecordDecl *ClassDecl,
2342 QualType BaseType,
2343 const CXXBaseSpecifier *&DirectBaseSpec,
2344 const CXXBaseSpecifier *&VirtualBaseSpec) {
2345 // First, check for a direct base class.
2346 DirectBaseSpec = 0;
2347 for (CXXRecordDecl::base_class_const_iterator Base
2348 = ClassDecl->bases_begin();
2349 Base != ClassDecl->bases_end(); ++Base) {
2350 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2351 // We found a direct base of this type. That's what we're
2352 // initializing.
2353 DirectBaseSpec = &*Base;
2354 break;
2355 }
2356 }
2357
2358 // Check for a virtual base class.
2359 // FIXME: We might be able to short-circuit this if we know in advance that
2360 // there are no virtual bases.
2361 VirtualBaseSpec = 0;
2362 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2363 // We haven't found a base yet; search the class hierarchy for a
2364 // virtual base class.
2365 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2366 /*DetectVirtual=*/false);
2367 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2368 BaseType, Paths)) {
2369 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2370 Path != Paths.end(); ++Path) {
2371 if (Path->back().Base->isVirtual()) {
2372 VirtualBaseSpec = Path->back().Base;
2373 break;
2374 }
2375 }
2376 }
2377 }
2378
2379 return DirectBaseSpec || VirtualBaseSpec;
2380}
2381
Sebastian Redl6df65482011-09-24 17:48:25 +00002382/// \brief Handle a C++ member initializer using braced-init-list syntax.
2383MemInitResult
2384Sema::ActOnMemInitializer(Decl *ConstructorD,
2385 Scope *S,
2386 CXXScopeSpec &SS,
2387 IdentifierInfo *MemberOrBase,
2388 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002389 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002390 SourceLocation IdLoc,
2391 Expr *InitList,
2392 SourceLocation EllipsisLoc) {
2393 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002394 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002395 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002396}
2397
2398/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002399MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002400Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002401 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002402 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002403 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002404 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002405 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002406 SourceLocation IdLoc,
2407 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002408 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002409 SourceLocation RParenLoc,
2410 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002411 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002412 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002413 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002414 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002415}
2416
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002417namespace {
2418
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002419// Callback to only accept typo corrections that can be a valid C++ member
2420// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002421class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002422public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002423 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2424 : ClassDecl(ClassDecl) {}
2425
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002426 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002427 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2428 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2429 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002430 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002431 }
2432 return false;
2433 }
2434
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002435private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002436 CXXRecordDecl *ClassDecl;
2437};
2438
2439}
2440
Sebastian Redl6df65482011-09-24 17:48:25 +00002441/// \brief Handle a C++ member initializer.
2442MemInitResult
2443Sema::BuildMemInitializer(Decl *ConstructorD,
2444 Scope *S,
2445 CXXScopeSpec &SS,
2446 IdentifierInfo *MemberOrBase,
2447 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002448 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002449 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002450 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002451 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002452 if (!ConstructorD)
2453 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002454
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002455 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002456
2457 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002458 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002459 if (!Constructor) {
2460 // The user wrote a constructor initializer on a function that is
2461 // not a C++ constructor. Ignore the error for now, because we may
2462 // have more member initializers coming; we'll diagnose it just
2463 // once in ActOnMemInitializers.
2464 return true;
2465 }
2466
2467 CXXRecordDecl *ClassDecl = Constructor->getParent();
2468
2469 // C++ [class.base.init]p2:
2470 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002471 // constructor's class and, if not found in that scope, are looked
2472 // up in the scope containing the constructor's definition.
2473 // [Note: if the constructor's class contains a member with the
2474 // same name as a direct or virtual base class of the class, a
2475 // mem-initializer-id naming the member or base class and composed
2476 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002477 // mem-initializer-id for the hidden base class may be specified
2478 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002479 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002480 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002481 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002482 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002483 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002484 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002485 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2486 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002487 if (EllipsisLoc.isValid())
2488 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002489 << MemberOrBase
2490 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002491
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002492 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002493 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002494 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002495 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002496 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002497 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002498 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002499
2500 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002501 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002502 } else if (DS.getTypeSpecType() == TST_decltype) {
2503 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002504 } else {
2505 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2506 LookupParsedName(R, S, &SS);
2507
2508 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2509 if (!TyD) {
2510 if (R.isAmbiguous()) return true;
2511
John McCallfd225442010-04-09 19:01:14 +00002512 // We don't want access-control diagnostics here.
2513 R.suppressDiagnostics();
2514
Douglas Gregor7a886e12010-01-19 06:46:48 +00002515 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2516 bool NotUnknownSpecialization = false;
2517 DeclContext *DC = computeDeclContext(SS, false);
2518 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2519 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2520
2521 if (!NotUnknownSpecialization) {
2522 // When the scope specifier can refer to a member of an unknown
2523 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002524 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2525 SS.getWithLocInContext(Context),
2526 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002527 if (BaseType.isNull())
2528 return true;
2529
Douglas Gregor7a886e12010-01-19 06:46:48 +00002530 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002531 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002532 }
2533 }
2534
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002535 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002536 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002537 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002538 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002539 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002540 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002541 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002542 // We have found a non-static data member with a similar
2543 // name to what was typed; complain and initialize that
2544 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002545 diagnoseTypo(Corr,
2546 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2547 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002548 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002549 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002550 const CXXBaseSpecifier *DirectBaseSpec;
2551 const CXXBaseSpecifier *VirtualBaseSpec;
2552 if (FindBaseInitializer(*this, ClassDecl,
2553 Context.getTypeDeclType(Type),
2554 DirectBaseSpec, VirtualBaseSpec)) {
2555 // We have found a direct or virtual base class with a
2556 // similar name to what was typed; complain and initialize
2557 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002558 diagnoseTypo(Corr,
2559 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2560 << MemberOrBase << false,
2561 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002562
Richard Smith2d670972013-08-17 00:46:16 +00002563 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2564 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002565 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002566 diag::note_base_class_specified_here)
2567 << BaseSpec->getType()
2568 << BaseSpec->getSourceRange();
2569
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002570 TyD = Type;
2571 }
2572 }
2573 }
2574
Douglas Gregor7a886e12010-01-19 06:46:48 +00002575 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002576 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002577 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002578 return true;
2579 }
John McCall2b194412009-12-21 10:41:20 +00002580 }
2581
Douglas Gregor7a886e12010-01-19 06:46:48 +00002582 if (BaseType.isNull()) {
2583 BaseType = Context.getTypeDeclType(TyD);
2584 if (SS.isSet()) {
2585 NestedNameSpecifier *Qualifier =
2586 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002587
Douglas Gregor7a886e12010-01-19 06:46:48 +00002588 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002589 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002590 }
John McCall2b194412009-12-21 10:41:20 +00002591 }
2592 }
Mike Stump1eb44332009-09-09 15:08:12 +00002593
John McCalla93c9342009-12-07 02:54:59 +00002594 if (!TInfo)
2595 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002596
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002597 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002598}
2599
Chandler Carruth81c64772011-09-03 01:14:15 +00002600/// Checks a member initializer expression for cases where reference (or
2601/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002602static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2603 Expr *Init,
2604 SourceLocation IdLoc) {
2605 QualType MemberTy = Member->getType();
2606
2607 // We only handle pointers and references currently.
2608 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2609 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2610 return;
2611
2612 const bool IsPointer = MemberTy->isPointerType();
2613 if (IsPointer) {
2614 if (const UnaryOperator *Op
2615 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2616 // The only case we're worried about with pointers requires taking the
2617 // address.
2618 if (Op->getOpcode() != UO_AddrOf)
2619 return;
2620
2621 Init = Op->getSubExpr();
2622 } else {
2623 // We only handle address-of expression initializers for pointers.
2624 return;
2625 }
2626 }
2627
Richard Smitha4bb99c2013-06-12 21:51:50 +00002628 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002629 // We only warn when referring to a non-reference parameter declaration.
2630 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2631 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002632 return;
2633
2634 S.Diag(Init->getExprLoc(),
2635 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2636 : diag::warn_bind_ref_member_to_parameter)
2637 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002638 } else {
2639 // Other initializers are fine.
2640 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002641 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002642
2643 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2644 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002645}
2646
John McCallf312b1e2010-08-26 23:41:50 +00002647MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002648Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002649 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002650 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2651 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2652 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002653 "Member must be a FieldDecl or IndirectFieldDecl");
2654
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002655 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002656 return true;
2657
Douglas Gregor464b2f02010-11-05 22:21:31 +00002658 if (Member->isInvalidDecl())
2659 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002660
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002661 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002662 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002663 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002664 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002665 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002666 } else {
2667 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002668 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002669 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002670
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002671 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002672
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002673 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002674 // Can't check initialization for a member of dependent type or when
2675 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002676 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002677 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002678 bool InitList = false;
2679 if (isa<InitListExpr>(Init)) {
2680 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002681 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002682 }
2683
Chandler Carruth894aed92010-12-06 09:23:57 +00002684 // Initialize the member.
2685 InitializedEntity MemberEntity =
2686 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2687 : InitializedEntity::InitializeMember(IndirectMember, 0);
2688 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002689 InitList ? InitializationKind::CreateDirectList(IdLoc)
2690 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2691 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002692
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002693 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2694 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002695 if (MemberInit.isInvalid())
2696 return true;
2697
Richard Smith8a07cd32013-06-12 20:42:33 +00002698 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2699
Richard Smith41956372013-01-14 22:39:08 +00002700 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002701 // The initialization of each base and member constitutes a
2702 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002703 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002704 if (MemberInit.isInvalid())
2705 return true;
2706
Richard Smithc83c2302012-12-19 01:39:02 +00002707 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002708 }
2709
Chandler Carruth894aed92010-12-06 09:23:57 +00002710 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002711 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2712 InitRange.getBegin(), Init,
2713 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002714 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002715 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2716 InitRange.getBegin(), Init,
2717 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002718 }
Eli Friedman59c04372009-07-29 19:44:27 +00002719}
2720
John McCallf312b1e2010-08-26 23:41:50 +00002721MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002722Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002723 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002724 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002725 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002726 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002727 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002728 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002729
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002730 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002731 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002732 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2733 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002734 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002735 }
2736
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002737 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002738 // Initialize the object.
2739 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2740 QualType(ClassDecl->getTypeForDecl(), 0));
2741 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002742 InitList ? InitializationKind::CreateDirectList(NameLoc)
2743 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2744 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002745 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002746 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002747 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002748 if (DelegationInit.isInvalid())
2749 return true;
2750
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002751 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2752 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002753
Richard Smith41956372013-01-14 22:39:08 +00002754 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002755 // The initialization of each base and member constitutes a
2756 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002757 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2758 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002759 if (DelegationInit.isInvalid())
2760 return true;
2761
Eli Friedmand21016f2012-05-19 23:35:23 +00002762 // If we are in a dependent context, template instantiation will
2763 // perform this type-checking again. Just save the arguments that we
2764 // received in a ParenListExpr.
2765 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2766 // of the information that we have about the base
2767 // initializer. However, deconstructing the ASTs is a dicey process,
2768 // and this approach is far more likely to get the corner cases right.
2769 if (CurContext->isDependentContext())
2770 DelegationInit = Owned(Init);
2771
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002772 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002773 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002774 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002775}
2776
2777MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002778Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002779 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002780 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002781 SourceLocation BaseLoc
2782 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002783
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002784 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2785 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2786 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2787
2788 // C++ [class.base.init]p2:
2789 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002790 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002791 // of that class, the mem-initializer is ill-formed. A
2792 // mem-initializer-list can initialize a base class using any
2793 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002794 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002795
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002796 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002797 if (EllipsisLoc.isValid()) {
2798 // This is a pack expansion.
2799 if (!BaseType->containsUnexpandedParameterPack()) {
2800 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002801 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002802
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002803 EllipsisLoc = SourceLocation();
2804 }
2805 } else {
2806 // Check for any unexpanded parameter packs.
2807 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2808 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002809
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002810 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002811 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002812 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002813
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002814 // Check for direct and virtual base classes.
2815 const CXXBaseSpecifier *DirectBaseSpec = 0;
2816 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2817 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002818 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2819 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002820 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002821
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002822 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2823 VirtualBaseSpec);
2824
2825 // C++ [base.class.init]p2:
2826 // Unless the mem-initializer-id names a nonstatic data member of the
2827 // constructor's class or a direct or virtual base of that class, the
2828 // mem-initializer is ill-formed.
2829 if (!DirectBaseSpec && !VirtualBaseSpec) {
2830 // If the class has any dependent bases, then it's possible that
2831 // one of those types will resolve to the same type as
2832 // BaseType. Therefore, just treat this as a dependent base
2833 // class initialization. FIXME: Should we try to check the
2834 // initialization anyway? It seems odd.
2835 if (ClassDecl->hasAnyDependentBases())
2836 Dependent = true;
2837 else
2838 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2839 << BaseType << Context.getTypeDeclType(ClassDecl)
2840 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2841 }
2842 }
2843
2844 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002845 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002846
Sebastian Redl6df65482011-09-24 17:48:25 +00002847 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2848 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002849 InitRange.getBegin(), Init,
2850 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002851 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002852
2853 // C++ [base.class.init]p2:
2854 // If a mem-initializer-id is ambiguous because it designates both
2855 // a direct non-virtual base class and an inherited virtual base
2856 // class, the mem-initializer is ill-formed.
2857 if (DirectBaseSpec && VirtualBaseSpec)
2858 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002859 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002860
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002861 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002862 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002863 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002864
2865 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002866 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002867 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002868 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002869 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002870 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002871 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002872
2873 InitializedEntity BaseEntity =
2874 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2875 InitializationKind Kind =
2876 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2877 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2878 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002879 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2880 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002881 if (BaseInit.isInvalid())
2882 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002883
Richard Smith41956372013-01-14 22:39:08 +00002884 // C++11 [class.base.init]p7:
2885 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002886 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002887 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002888 if (BaseInit.isInvalid())
2889 return true;
2890
2891 // If we are in a dependent context, template instantiation will
2892 // perform this type-checking again. Just save the arguments that we
2893 // received in a ParenListExpr.
2894 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2895 // of the information that we have about the base
2896 // initializer. However, deconstructing the ASTs is a dicey process,
2897 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002898 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002899 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002900
Sean Huntcbb67482011-01-08 20:30:50 +00002901 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002902 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002903 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002904 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002905 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002906}
2907
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002908// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002909static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2910 if (T.isNull()) T = E->getType();
2911 QualType TargetType = SemaRef.BuildReferenceType(
2912 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002913 SourceLocation ExprLoc = E->getLocStart();
2914 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2915 TargetType, ExprLoc);
2916
2917 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2918 SourceRange(ExprLoc, ExprLoc),
2919 E->getSourceRange()).take();
2920}
2921
Anders Carlssone5ef7402010-04-23 03:10:23 +00002922/// ImplicitInitializerKind - How an implicit base or member initializer should
2923/// initialize its base or member.
2924enum ImplicitInitializerKind {
2925 IIK_Default,
2926 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002927 IIK_Move,
2928 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002929};
2930
Anders Carlssondefefd22010-04-23 02:00:02 +00002931static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002932BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002933 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002934 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002935 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002936 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002937 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002938 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2939 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002940
John McCall60d7b3a2010-08-24 06:29:42 +00002941 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002942
2943 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002944 case IIK_Inherit: {
2945 const CXXRecordDecl *Inherited =
2946 Constructor->getInheritedConstructor()->getParent();
2947 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2948 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2949 // C++11 [class.inhctor]p8:
2950 // Each expression in the expression-list is of the form
2951 // static_cast<T&&>(p), where p is the name of the corresponding
2952 // constructor parameter and T is the declared type of p.
2953 SmallVector<Expr*, 16> Args;
2954 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2955 ParmVarDecl *PD = Constructor->getParamDecl(I);
2956 ExprResult ArgExpr =
2957 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2958 VK_LValue, SourceLocation());
2959 if (ArgExpr.isInvalid())
2960 return true;
2961 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2962 }
2963
2964 InitializationKind InitKind = InitializationKind::CreateDirect(
2965 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002966 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002967 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2968 break;
2969 }
2970 }
2971 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002972 case IIK_Default: {
2973 InitializationKind InitKind
2974 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002975 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2976 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002977 break;
2978 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002979
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002980 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002981 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002982 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002983 ParmVarDecl *Param = Constructor->getParamDecl(0);
2984 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002985
Anders Carlssone5ef7402010-04-23 03:10:23 +00002986 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002987 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002988 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002989 Constructor->getLocation(), ParamType,
2990 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002991
Eli Friedman5f2987c2012-02-02 03:46:19 +00002992 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2993
Anders Carlssonc7957502010-04-24 22:02:54 +00002994 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002995 QualType ArgTy =
2996 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2997 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002998
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002999 if (Moving) {
3000 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3001 }
3002
John McCallf871d0c2010-08-07 06:22:56 +00003003 CXXCastPath BasePath;
3004 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00003005 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3006 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003007 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003008 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00003009
Anders Carlssone5ef7402010-04-23 03:10:23 +00003010 InitializationKind InitKind
3011 = InitializationKind::CreateDirect(Constructor->getLocation(),
3012 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003013 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3014 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003015 break;
3016 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00003017 }
John McCall9ae2f072010-08-23 23:25:46 +00003018
Douglas Gregor53c374f2010-12-07 00:41:46 +00003019 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00003020 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00003021 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00003022
Anders Carlssondefefd22010-04-23 02:00:02 +00003023 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00003024 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00003025 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3026 SourceLocation()),
3027 BaseSpec->isVirtual(),
3028 SourceLocation(),
3029 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003030 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00003031 SourceLocation());
3032
Anders Carlssondefefd22010-04-23 02:00:02 +00003033 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00003034}
3035
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003036static bool RefersToRValueRef(Expr *MemRef) {
3037 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3038 return Referenced->getType()->isRValueReferenceType();
3039}
3040
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003041static bool
3042BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003043 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003044 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00003045 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003046 if (Field->isInvalidDecl())
3047 return true;
3048
Chandler Carruthf186b542010-06-29 23:50:44 +00003049 SourceLocation Loc = Constructor->getLocation();
3050
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003051 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3052 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003053 ParmVarDecl *Param = Constructor->getParamDecl(0);
3054 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00003055
3056 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003057 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3058 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00003059
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003060 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003061 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003062 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00003063 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003064
Eli Friedman5f2987c2012-02-02 03:46:19 +00003065 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3066
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003067 if (Moving) {
3068 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3069 }
3070
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003071 // Build a reference to this field within the parameter.
3072 CXXScopeSpec SS;
3073 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3074 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003075 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3076 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003077 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00003078 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00003079 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003080 ParamType, Loc,
3081 /*IsArrow=*/false,
3082 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003083 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003084 /*FirstQualifierInScope=*/0,
3085 MemberLookup,
3086 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003087 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003088 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003089
3090 // C++11 [class.copy]p15:
3091 // - if a member m has rvalue reference type T&&, it is direct-initialized
3092 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003093 if (RefersToRValueRef(CtorArg.get())) {
3094 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003095 }
3096
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003097 // When the field we are copying is an array, create index variables for
3098 // each dimension of the array. We use these index variables to subscript
3099 // the source array, and other clients (e.g., CodeGen) will perform the
3100 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003101 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003102 QualType BaseType = Field->getType();
3103 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003104 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003105 while (const ConstantArrayType *Array
3106 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003107 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003108 // Create the iteration variable for this array index.
3109 IdentifierInfo *IterationVarName = 0;
3110 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003111 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003112 llvm::raw_svector_ostream OS(Str);
3113 OS << "__i" << IndexVariables.size();
3114 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3115 }
3116 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003117 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003118 IterationVarName, SizeType,
3119 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003120 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003121 IndexVariables.push_back(IterationVar);
3122
3123 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003124 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003125 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003126 assert(!IterationVarRef.isInvalid() &&
3127 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003128 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3129 assert(!IterationVarRef.isInvalid() &&
3130 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003131
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003132 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003133 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003134 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003135 Loc);
3136 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003137 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003138
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003139 BaseType = Array->getElementType();
3140 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003141
3142 // The array subscript expression is an lvalue, which is wrong for moving.
3143 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003144 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003145
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003146 // Construct the entity that we will be initializing. For an array, this
3147 // will be first element in the array, which may require several levels
3148 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003149 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003150 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003151 if (Indirect)
3152 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3153 else
3154 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003155 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3156 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3157 0,
3158 Entities.back()));
3159
3160 // Direct-initialize to use the copy constructor.
3161 InitializationKind InitKind =
3162 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3163
Sebastian Redl74e611a2011-09-04 18:14:28 +00003164 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003165 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003166
John McCall60d7b3a2010-08-24 06:29:42 +00003167 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003168 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003169 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003170 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003171 if (MemberInit.isInvalid())
3172 return true;
3173
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003174 if (Indirect) {
3175 assert(IndexVariables.size() == 0 &&
3176 "Indirect field improperly initialized");
3177 CXXMemberInit
3178 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3179 Loc, Loc,
3180 MemberInit.takeAs<Expr>(),
3181 Loc);
3182 } else
3183 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3184 Loc, MemberInit.takeAs<Expr>(),
3185 Loc,
3186 IndexVariables.data(),
3187 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003188 return false;
3189 }
3190
Richard Smith07b0fdc2013-03-18 21:12:30 +00003191 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3192 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003193
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003194 QualType FieldBaseElementType =
3195 SemaRef.Context.getBaseElementType(Field->getType());
3196
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003197 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003198 InitializedEntity InitEntity
3199 = Indirect? InitializedEntity::InitializeMember(Indirect)
3200 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003201 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003202 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003203
3204 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3205 ExprResult MemberInit =
3206 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003207
Douglas Gregor53c374f2010-12-07 00:41:46 +00003208 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003209 if (MemberInit.isInvalid())
3210 return true;
3211
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003212 if (Indirect)
3213 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3214 Indirect, Loc,
3215 Loc,
3216 MemberInit.get(),
3217 Loc);
3218 else
3219 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3220 Field, Loc, Loc,
3221 MemberInit.get(),
3222 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003223 return false;
3224 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003225
Sean Hunt1f2f3842011-05-17 00:19:05 +00003226 if (!Field->getParent()->isUnion()) {
3227 if (FieldBaseElementType->isReferenceType()) {
3228 SemaRef.Diag(Constructor->getLocation(),
3229 diag::err_uninitialized_member_in_ctor)
3230 << (int)Constructor->isImplicit()
3231 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3232 << 0 << Field->getDeclName();
3233 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3234 return true;
3235 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003236
Sean Hunt1f2f3842011-05-17 00:19:05 +00003237 if (FieldBaseElementType.isConstQualified()) {
3238 SemaRef.Diag(Constructor->getLocation(),
3239 diag::err_uninitialized_member_in_ctor)
3240 << (int)Constructor->isImplicit()
3241 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3242 << 1 << Field->getDeclName();
3243 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3244 return true;
3245 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003246 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003247
David Blaikie4e4d0842012-03-11 07:00:24 +00003248 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003249 FieldBaseElementType->isObjCRetainableType() &&
3250 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3251 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003252 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003253 // Default-initialize Objective-C pointers to NULL.
3254 CXXMemberInit
3255 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3256 Loc, Loc,
3257 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3258 Loc);
3259 return false;
3260 }
3261
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003262 // Nothing to initialize.
3263 CXXMemberInit = 0;
3264 return false;
3265}
John McCallf1860e52010-05-20 23:23:51 +00003266
3267namespace {
3268struct BaseAndFieldInfo {
3269 Sema &S;
3270 CXXConstructorDecl *Ctor;
3271 bool AnyErrorsInInits;
3272 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003273 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003274 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003275
3276 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3277 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003278 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3279 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003280 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003281 else if (Generated && Ctor->isMoveConstructor())
3282 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003283 else if (Ctor->getInheritedConstructor())
3284 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003285 else
3286 IIK = IIK_Default;
3287 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003288
3289 bool isImplicitCopyOrMove() const {
3290 switch (IIK) {
3291 case IIK_Copy:
3292 case IIK_Move:
3293 return true;
3294
3295 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003296 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003297 return false;
3298 }
David Blaikie30263482012-01-20 21:50:17 +00003299
3300 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003301 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003302
3303 bool addFieldInitializer(CXXCtorInitializer *Init) {
3304 AllToInit.push_back(Init);
3305
3306 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003307 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003308 S.UnusedPrivateFields.remove(Init->getAnyMember());
3309
3310 return false;
3311 }
John McCallf1860e52010-05-20 23:23:51 +00003312};
3313}
3314
Richard Smitha4950662011-09-19 13:34:43 +00003315/// \brief Determine whether the given indirect field declaration is somewhere
3316/// within an anonymous union.
3317static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3318 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3319 CEnd = F->chain_end();
3320 C != CEnd; ++C)
3321 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3322 if (Record->isUnion())
3323 return true;
3324
3325 return false;
3326}
3327
Douglas Gregorddb21472011-11-02 23:04:16 +00003328/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3329/// array type.
3330static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3331 if (T->isIncompleteArrayType())
3332 return true;
3333
3334 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3335 if (!ArrayT->getSize())
3336 return true;
3337
3338 T = ArrayT->getElementType();
3339 }
3340
3341 return false;
3342}
3343
Richard Smith7a614d82011-06-11 17:19:42 +00003344static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003345 FieldDecl *Field,
3346 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003347 if (Field->isInvalidDecl())
3348 return false;
John McCallf1860e52010-05-20 23:23:51 +00003349
Chandler Carruthe861c602010-06-30 02:59:29 +00003350 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003351 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3352 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003353
Richard Smith0b8220a2012-08-07 21:30:42 +00003354 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003355 // has a brace-or-equal-initializer, the entity is initialized as specified
3356 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003357 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003358 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3359 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003360 CXXCtorInitializer *Init;
3361 if (Indirect)
3362 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3363 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003364 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003365 SourceLocation());
3366 else
3367 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3368 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003369 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003370 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003371 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003372 }
3373
Richard Smithc115f632011-09-18 11:14:50 +00003374 // Don't build an implicit initializer for union members if none was
3375 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003376 if (Field->getParent()->isUnion() ||
3377 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003378 return false;
3379
Douglas Gregorddb21472011-11-02 23:04:16 +00003380 // Don't initialize incomplete or zero-length arrays.
3381 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3382 return false;
3383
John McCallf1860e52010-05-20 23:23:51 +00003384 // Don't try to build an implicit initializer if there were semantic
3385 // errors in any of the initializers (and therefore we might be
3386 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003387 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003388 return false;
3389
Sean Huntcbb67482011-01-08 20:30:50 +00003390 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003391 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3392 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003393 return true;
John McCallf1860e52010-05-20 23:23:51 +00003394
Richard Smith0b8220a2012-08-07 21:30:42 +00003395 if (!Init)
3396 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003397
Richard Smith0b8220a2012-08-07 21:30:42 +00003398 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003399}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003400
3401bool
3402Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3403 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003404 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003405 Constructor->setNumCtorInitializers(1);
3406 CXXCtorInitializer **initializer =
3407 new (Context) CXXCtorInitializer*[1];
3408 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3409 Constructor->setCtorInitializers(initializer);
3410
Sean Huntb76af9c2011-05-03 23:05:34 +00003411 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003412 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003413 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3414 }
3415
Sean Huntc1598702011-05-05 00:05:47 +00003416 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003417
Sean Hunt059ce0d2011-05-01 07:04:31 +00003418 return false;
3419}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003420
David Blaikie93c86172013-01-17 05:26:25 +00003421bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3422 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003423 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003424 // Just store the initializers as written, they will be checked during
3425 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003426 if (!Initializers.empty()) {
3427 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003428 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003429 new (Context) CXXCtorInitializer*[Initializers.size()];
3430 memcpy(baseOrMemberInitializers, Initializers.data(),
3431 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003432 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003433 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003434
3435 // Let template instantiation know whether we had errors.
3436 if (AnyErrors)
3437 Constructor->setInvalidDecl();
3438
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003439 return false;
3440 }
3441
John McCallf1860e52010-05-20 23:23:51 +00003442 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003443
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003444 // We need to build the initializer AST according to order of construction
3445 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003446 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003447 if (!ClassDecl)
3448 return true;
3449
Eli Friedman80c30da2009-11-09 19:20:36 +00003450 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003451
David Blaikie93c86172013-01-17 05:26:25 +00003452 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003453 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003454
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003455 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003456 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003457 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003458 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003459 }
3460
Anders Carlsson711f34a2010-04-21 19:52:01 +00003461 // Keep track of the direct virtual bases.
3462 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3463 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3464 E = ClassDecl->bases_end(); I != E; ++I) {
3465 if (I->isVirtual())
3466 DirectVBases.insert(I);
3467 }
3468
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003469 // Push virtual bases before others.
3470 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3471 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3472
Sean Huntcbb67482011-01-08 20:30:50 +00003473 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003474 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003475 // [class.base.init]p7, per DR257:
3476 // A mem-initializer where the mem-initializer-id names a virtual base
3477 // class is ignored during execution of a constructor of any class that
3478 // is not the most derived class.
3479 if (ClassDecl->isAbstract()) {
3480 // FIXME: Provide a fixit to remove the base specifier. This requires
3481 // tracking the location of the associated comma for a base specifier.
3482 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3483 << VBase->getType() << ClassDecl;
3484 DiagnoseAbstractType(ClassDecl);
3485 }
3486
John McCallf1860e52010-05-20 23:23:51 +00003487 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003488 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3489 // [class.base.init]p8, per DR257:
3490 // If a given [...] base class is not named by a mem-initializer-id
3491 // [...] and the entity is not a virtual base class of an abstract
3492 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003493 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003494 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003495 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003496 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003497 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003498 HadError = true;
3499 continue;
3500 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003501
John McCallf1860e52010-05-20 23:23:51 +00003502 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003503 }
3504 }
Mike Stump1eb44332009-09-09 15:08:12 +00003505
John McCallf1860e52010-05-20 23:23:51 +00003506 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003507 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3508 E = ClassDecl->bases_end(); Base != E; ++Base) {
3509 // Virtuals are in the virtual base list and already constructed.
3510 if (Base->isVirtual())
3511 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003512
Sean Huntcbb67482011-01-08 20:30:50 +00003513 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003514 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3515 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003516 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003517 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003518 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003519 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003520 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003521 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003522 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003523 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003524
John McCallf1860e52010-05-20 23:23:51 +00003525 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003526 }
3527 }
Mike Stump1eb44332009-09-09 15:08:12 +00003528
John McCallf1860e52010-05-20 23:23:51 +00003529 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003530 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3531 MemEnd = ClassDecl->decls_end();
3532 Mem != MemEnd; ++Mem) {
3533 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003534 // C++ [class.bit]p2:
3535 // A declaration for a bit-field that omits the identifier declares an
3536 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3537 // initialized.
3538 if (F->isUnnamedBitfield())
3539 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003540
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003541 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003542 // handle anonymous struct/union fields based on their individual
3543 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003544 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003545 continue;
3546
3547 if (CollectFieldInitializer(*this, Info, F))
3548 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003549 continue;
3550 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003551
3552 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003553 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003554 continue;
3555
3556 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3557 if (F->getType()->isIncompleteArrayType()) {
3558 assert(ClassDecl->hasFlexibleArrayMember() &&
3559 "Incomplete array type is not valid");
3560 continue;
3561 }
3562
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003563 // Initialize each field of an anonymous struct individually.
3564 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3565 HadError = true;
3566
3567 continue;
3568 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003569 }
Mike Stump1eb44332009-09-09 15:08:12 +00003570
David Blaikie93c86172013-01-17 05:26:25 +00003571 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003572 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003573 Constructor->setNumCtorInitializers(NumInitializers);
3574 CXXCtorInitializer **baseOrMemberInitializers =
3575 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003576 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003577 NumInitializers * sizeof(CXXCtorInitializer*));
3578 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003579
John McCallef027fe2010-03-16 21:39:52 +00003580 // Constructors implicitly reference the base and member
3581 // destructors.
3582 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3583 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003584 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003585
3586 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003587}
3588
David Blaikieee000bb2013-01-17 08:49:22 +00003589static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003590 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003591 const RecordDecl *RD = RT->getDecl();
3592 if (RD->isAnonymousStructOrUnion()) {
3593 for (RecordDecl::field_iterator Field = RD->field_begin(),
3594 E = RD->field_end(); Field != E; ++Field)
3595 PopulateKeysForFields(*Field, IdealInits);
3596 return;
3597 }
Eli Friedman6347f422009-07-21 19:28:10 +00003598 }
David Blaikieee000bb2013-01-17 08:49:22 +00003599 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003600}
3601
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003602static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3603 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003604}
3605
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003606static const void *GetKeyForMember(ASTContext &Context,
3607 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003608 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003609 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003610
David Blaikieee000bb2013-01-17 08:49:22 +00003611 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003612}
3613
David Blaikie93c86172013-01-17 05:26:25 +00003614static void DiagnoseBaseOrMemInitializerOrder(
3615 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3616 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003617 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003618 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003619
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003620 // Don't check initializers order unless the warning is enabled at the
3621 // location of at least one initializer.
3622 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003623 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003624 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003625 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3626 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003627 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003628 ShouldCheckOrder = true;
3629 break;
3630 }
3631 }
3632 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003633 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003634
John McCalld6ca8da2010-04-10 07:37:23 +00003635 // Build the list of bases and members in the order that they'll
3636 // actually be initialized. The explicit initializers should be in
3637 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003638 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003639
Anders Carlsson071d6102010-04-02 03:38:04 +00003640 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3641
John McCalld6ca8da2010-04-10 07:37:23 +00003642 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003643 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003644 ClassDecl->vbases_begin(),
3645 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003646 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003647
John McCalld6ca8da2010-04-10 07:37:23 +00003648 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003649 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003650 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003651 if (Base->isVirtual())
3652 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003653 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003654 }
Mike Stump1eb44332009-09-09 15:08:12 +00003655
John McCalld6ca8da2010-04-10 07:37:23 +00003656 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003657 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003658 E = ClassDecl->field_end(); Field != E; ++Field) {
3659 if (Field->isUnnamedBitfield())
3660 continue;
3661
David Blaikieee000bb2013-01-17 08:49:22 +00003662 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003663 }
3664
John McCalld6ca8da2010-04-10 07:37:23 +00003665 unsigned NumIdealInits = IdealInitKeys.size();
3666 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003667
Sean Huntcbb67482011-01-08 20:30:50 +00003668 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003669 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003670 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003671 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003672
3673 // Scan forward to try to find this initializer in the idealized
3674 // initializers list.
3675 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3676 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003677 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003678
3679 // If we didn't find this initializer, it must be because we
3680 // scanned past it on a previous iteration. That can only
3681 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003682 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003683 Sema::SemaDiagnosticBuilder D =
3684 SemaRef.Diag(PrevInit->getSourceLocation(),
3685 diag::warn_initializer_out_of_order);
3686
Francois Pichet00eb3f92010-12-04 09:14:42 +00003687 if (PrevInit->isAnyMemberInitializer())
3688 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003689 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003690 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003691
Francois Pichet00eb3f92010-12-04 09:14:42 +00003692 if (Init->isAnyMemberInitializer())
3693 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003694 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003695 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003696
3697 // Move back to the initializer's location in the ideal list.
3698 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3699 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003700 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003701
3702 assert(IdealIndex != NumIdealInits &&
3703 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003704 }
John McCalld6ca8da2010-04-10 07:37:23 +00003705
3706 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003707 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003708}
3709
John McCall3c3ccdb2010-04-10 09:28:51 +00003710namespace {
3711bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003712 CXXCtorInitializer *Init,
3713 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003714 if (!PrevInit) {
3715 PrevInit = Init;
3716 return false;
3717 }
3718
Douglas Gregordc392c12013-03-25 23:28:23 +00003719 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003720 S.Diag(Init->getSourceLocation(),
3721 diag::err_multiple_mem_initialization)
3722 << Field->getDeclName()
3723 << Init->getSourceRange();
3724 else {
John McCallf4c73712011-01-19 06:33:43 +00003725 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003726 assert(BaseClass && "neither field nor base");
3727 S.Diag(Init->getSourceLocation(),
3728 diag::err_multiple_base_initialization)
3729 << QualType(BaseClass, 0)
3730 << Init->getSourceRange();
3731 }
3732 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3733 << 0 << PrevInit->getSourceRange();
3734
3735 return true;
3736}
3737
Sean Huntcbb67482011-01-08 20:30:50 +00003738typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003739typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3740
3741bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003742 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003743 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003744 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003745 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003746 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003747
3748 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003749 if (Parent->isUnion()) {
3750 UnionEntry &En = Unions[Parent];
3751 if (En.first && En.first != Child) {
3752 S.Diag(Init->getSourceLocation(),
3753 diag::err_multiple_mem_union_initialization)
3754 << Field->getDeclName()
3755 << Init->getSourceRange();
3756 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3757 << 0 << En.second->getSourceRange();
3758 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003759 }
3760 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003761 En.first = Child;
3762 En.second = Init;
3763 }
David Blaikie6fe29652011-11-17 06:01:57 +00003764 if (!Parent->isAnonymousStructOrUnion())
3765 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003766 }
3767
3768 Child = Parent;
3769 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003770 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003771
3772 return false;
3773}
3774}
3775
Richard Trieu225e9822013-09-16 21:54:53 +00003776// Diagnose value-uses of fields to initialize themselves, e.g.
3777// foo(foo)
3778// where foo is not also a parameter to the constructor.
Richard Trieuef8f90c2013-09-20 03:03:06 +00003779// Also diagnose across field uninitialized use such as
3780// x(y), y(x)
Richard Trieu225e9822013-09-16 21:54:53 +00003781// TODO: implement -Wuninitialized and fold this into that framework.
Richard Trieu225e9822013-09-16 21:54:53 +00003782static void DiagnoseUnitializedFields(
3783 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3784
3785 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
3786 Constructor->getLocation())
3787 == DiagnosticsEngine::Ignored) {
3788 return;
3789 }
3790
Richard Trieuef8f90c2013-09-20 03:03:06 +00003791 const CXXRecordDecl *RD = Constructor->getParent();
3792
3793 // Holds fields that are uninitialized.
3794 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3795
3796 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
3797 I != E; ++I) {
3798 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
3799 UninitializedFields.insert(FD);
3800 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
3801 UninitializedFields.insert(IFD->getAnonField());
3802 }
3803 }
3804
3805 // Fields already checked when processing the in class initializers.
3806 llvm::SmallPtrSet<ValueDecl*, 4>
3807 InClassUninitializedFields = UninitializedFields;
3808
3809 for (CXXConstructorDecl::init_const_iterator FieldInit =
3810 Constructor->init_begin(),
Richard Trieu225e9822013-09-16 21:54:53 +00003811 FieldInitEnd = Constructor->init_end();
3812 FieldInit != FieldInitEnd; ++FieldInit) {
3813
Richard Trieuef8f90c2013-09-20 03:03:06 +00003814 FieldDecl *Field = (*FieldInit)->getAnyMember();
Richard Trieu225e9822013-09-16 21:54:53 +00003815 Expr *InitExpr = (*FieldInit)->getInit();
3816
Richard Trieuef8f90c2013-09-20 03:03:06 +00003817 if (!Field) {
3818 CheckInitExprContainsUninitializedFields(
3819 SemaRef, InitExpr, 0, UninitializedFields,
3820 false/*WarnOnSelfReference*/);
3821 continue;
Richard Trieu225e9822013-09-16 21:54:53 +00003822 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00003823
3824 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3825 // This field is initialized with an in-class initailzer. Remove the
3826 // fields already checked to prevent duplicate warnings.
3827 llvm::SmallPtrSet<ValueDecl*, 4> DiffSet = UninitializedFields;
3828 for (llvm::SmallPtrSet<ValueDecl*, 4>::iterator
3829 I = InClassUninitializedFields.begin(),
3830 E = InClassUninitializedFields.end();
3831 I != E; ++I) {
3832 DiffSet.erase(*I);
3833 }
3834 CheckInitExprContainsUninitializedFields(
3835 SemaRef, Default->getExpr(), Field, DiffSet,
3836 DiffSet.count(Field), Constructor);
3837
3838 // Update the unitialized field sets.
3839 CheckInitExprContainsUninitializedFields(
3840 SemaRef, Default->getExpr(), 0, UninitializedFields,
3841 false);
3842 CheckInitExprContainsUninitializedFields(
3843 SemaRef, Default->getExpr(), 0, InClassUninitializedFields,
3844 false);
3845 } else {
3846 CheckInitExprContainsUninitializedFields(
3847 SemaRef, InitExpr, Field, UninitializedFields,
3848 UninitializedFields.count(Field));
3849 if (Expr* InClassInit = Field->getInClassInitializer()) {
3850 CheckInitExprContainsUninitializedFields(
3851 SemaRef, InClassInit, 0, InClassUninitializedFields,
3852 false);
3853 }
3854 }
3855 UninitializedFields.erase(Field);
3856 InClassUninitializedFields.erase(Field);
Richard Trieu225e9822013-09-16 21:54:53 +00003857 }
3858}
3859
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003860/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003861void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003862 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003863 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003864 bool AnyErrors) {
3865 if (!ConstructorDecl)
3866 return;
3867
3868 AdjustDeclIfTemplate(ConstructorDecl);
3869
3870 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003871 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003872
3873 if (!Constructor) {
3874 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3875 return;
3876 }
3877
John McCall3c3ccdb2010-04-10 09:28:51 +00003878 // Mapping for the duplicate initializers check.
3879 // For member initializers, this is keyed with a FieldDecl*.
3880 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003881 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003882
3883 // Mapping for the inconsistent anonymous-union initializers check.
3884 RedundantUnionMap MemberUnions;
3885
Anders Carlssonea356fb2010-04-02 05:42:15 +00003886 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003887 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003888 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003889
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003890 // Set the source order index.
3891 Init->setSourceOrder(i);
3892
Francois Pichet00eb3f92010-12-04 09:14:42 +00003893 if (Init->isAnyMemberInitializer()) {
3894 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003895 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3896 CheckRedundantUnionInit(*this, Init, MemberUnions))
3897 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003898 } else if (Init->isBaseInitializer()) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003899 const void *Key =
3900 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall3c3ccdb2010-04-10 09:28:51 +00003901 if (CheckRedundantInit(*this, Init, Members[Key]))
3902 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003903 } else {
3904 assert(Init->isDelegatingInitializer());
3905 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003906 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003907 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003908 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003909 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003910 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003911 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003912 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003913 // Return immediately as the initializer is set.
3914 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003915 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003916 }
3917
Anders Carlssonea356fb2010-04-02 05:42:15 +00003918 if (HadError)
3919 return;
3920
David Blaikie93c86172013-01-17 05:26:25 +00003921 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003922
David Blaikie93c86172013-01-17 05:26:25 +00003923 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu225e9822013-09-16 21:54:53 +00003924
3925 DiagnoseUnitializedFields(*this, Constructor);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003926}
3927
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003928void
John McCallef027fe2010-03-16 21:39:52 +00003929Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3930 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003931 // Ignore dependent contexts. Also ignore unions, since their members never
3932 // have destructors implicitly called.
3933 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003934 return;
John McCall58e6f342010-03-16 05:22:47 +00003935
3936 // FIXME: all the access-control diagnostics are positioned on the
3937 // field/base declaration. That's probably good; that said, the
3938 // user might reasonably want to know why the destructor is being
3939 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003940
Anders Carlsson9f853df2009-11-17 04:44:12 +00003941 // Non-static data members.
3942 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3943 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003944 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003945 if (Field->isInvalidDecl())
3946 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003947
3948 // Don't destroy incomplete or zero-length arrays.
3949 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3950 continue;
3951
Anders Carlsson9f853df2009-11-17 04:44:12 +00003952 QualType FieldType = Context.getBaseElementType(Field->getType());
3953
3954 const RecordType* RT = FieldType->getAs<RecordType>();
3955 if (!RT)
3956 continue;
3957
3958 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003959 if (FieldClassDecl->isInvalidDecl())
3960 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003961 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003962 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003963 // The destructor for an implicit anonymous union member is never invoked.
3964 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3965 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003966
Douglas Gregordb89f282010-07-01 22:47:18 +00003967 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003968 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003969 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003970 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003971 << Field->getDeclName()
3972 << FieldType);
3973
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003974 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003975 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003976 }
3977
John McCall58e6f342010-03-16 05:22:47 +00003978 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3979
Anders Carlsson9f853df2009-11-17 04:44:12 +00003980 // Bases.
3981 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3982 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003983 // Bases are always records in a well-formed non-dependent class.
3984 const RecordType *RT = Base->getType()->getAs<RecordType>();
3985
3986 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003987 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003988 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003989
John McCall58e6f342010-03-16 05:22:47 +00003990 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003991 // If our base class is invalid, we probably can't get its dtor anyway.
3992 if (BaseClassDecl->isInvalidDecl())
3993 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003994 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003995 continue;
John McCall58e6f342010-03-16 05:22:47 +00003996
Douglas Gregordb89f282010-07-01 22:47:18 +00003997 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003998 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003999
4000 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00004001 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004002 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00004003 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00004004 << Base->getSourceRange(),
4005 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00004006
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004007 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004008 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00004009 }
4010
4011 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004012 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
4013 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00004014
4015 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00004016 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00004017
4018 // Ignore direct virtual bases.
4019 if (DirectVirtualBases.count(RT))
4020 continue;
4021
John McCall58e6f342010-03-16 05:22:47 +00004022 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004023 // If our base class is invalid, we probably can't get its dtor anyway.
4024 if (BaseClassDecl->isInvalidDecl())
4025 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004026 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004027 continue;
John McCall58e6f342010-03-16 05:22:47 +00004028
Douglas Gregordb89f282010-07-01 22:47:18 +00004029 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004030 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00004031 if (CheckDestructorAccess(
4032 ClassDecl->getLocation(), Dtor,
4033 PDiag(diag::err_access_dtor_vbase)
4034 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
4035 Context.getTypeDeclType(ClassDecl)) ==
4036 AR_accessible) {
4037 CheckDerivedToBaseConversion(
4038 Context.getTypeDeclType(ClassDecl), VBase->getType(),
4039 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4040 SourceRange(), DeclarationName(), 0);
4041 }
John McCall58e6f342010-03-16 05:22:47 +00004042
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004043 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004044 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004045 }
4046}
4047
John McCalld226f652010-08-21 09:40:31 +00004048void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00004049 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004050 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004051
Mike Stump1eb44332009-09-09 15:08:12 +00004052 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00004053 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00004054 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004055}
4056
Mike Stump1eb44332009-09-09 15:08:12 +00004057bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00004058 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004059 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4060 unsigned DiagID;
4061 AbstractDiagSelID SelID;
4062
4063 public:
4064 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4065 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004066
4067 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman2217f852012-08-14 02:06:07 +00004068 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004069 if (SelID == -1)
4070 S.Diag(Loc, DiagID) << T;
4071 else
4072 S.Diag(Loc, DiagID) << SelID << T;
4073 }
4074 } Diagnoser(DiagID, SelID);
4075
4076 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004077}
4078
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00004079bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004080 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004081 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004082 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004083
Anders Carlsson11f21a02009-03-23 19:10:31 +00004084 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004085 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004086
Ted Kremenek6217b802009-07-29 21:53:49 +00004087 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004088 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004089 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004090 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00004091
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004092 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004093 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004094 }
Mike Stump1eb44332009-09-09 15:08:12 +00004095
Ted Kremenek6217b802009-07-29 21:53:49 +00004096 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004097 if (!RT)
4098 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004099
John McCall86ff3082010-02-04 22:26:26 +00004100 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004101
John McCall94c3b562010-08-18 09:41:07 +00004102 // We can't answer whether something is abstract until it has a
4103 // definition. If it's currently being defined, we'll walk back
4104 // over all the declarations when we have a full definition.
4105 const CXXRecordDecl *Def = RD->getDefinition();
4106 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00004107 return false;
4108
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004109 if (!RD->isAbstract())
4110 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004111
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004112 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00004113 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00004114
John McCall94c3b562010-08-18 09:41:07 +00004115 return true;
4116}
4117
4118void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4119 // Check if we've already emitted the list of pure virtual functions
4120 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004121 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00004122 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004123
Richard Smithcbc820a2013-07-22 02:56:56 +00004124 // If the diagnostic is suppressed, don't emit the notes. We're only
4125 // going to emit them once, so try to attach them to a diagnostic we're
4126 // actually going to show.
4127 if (Diags.isLastDiagnosticIgnored())
4128 return;
4129
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004130 CXXFinalOverriderMap FinalOverriders;
4131 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00004132
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004133 // Keep a set of seen pure methods so we won't diagnose the same method
4134 // more than once.
4135 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4136
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004137 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4138 MEnd = FinalOverriders.end();
4139 M != MEnd;
4140 ++M) {
4141 for (OverridingMethods::iterator SO = M->second.begin(),
4142 SOEnd = M->second.end();
4143 SO != SOEnd; ++SO) {
4144 // C++ [class.abstract]p4:
4145 // A class is abstract if it contains or inherits at least one
4146 // pure virtual function for which the final overrider is pure
4147 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00004148
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004149 //
4150 if (SO->second.size() != 1)
4151 continue;
4152
4153 if (!SO->second.front().Method->isPure())
4154 continue;
4155
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004156 if (!SeenPureMethods.insert(SO->second.front().Method))
4157 continue;
4158
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004159 Diag(SO->second.front().Method->getLocation(),
4160 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00004161 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004162 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004163 }
4164
4165 if (!PureVirtualClassDiagSet)
4166 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4167 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004168}
4169
Anders Carlsson8211eff2009-03-24 01:19:16 +00004170namespace {
John McCall94c3b562010-08-18 09:41:07 +00004171struct AbstractUsageInfo {
4172 Sema &S;
4173 CXXRecordDecl *Record;
4174 CanQualType AbstractType;
4175 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00004176
John McCall94c3b562010-08-18 09:41:07 +00004177 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4178 : S(S), Record(Record),
4179 AbstractType(S.Context.getCanonicalType(
4180 S.Context.getTypeDeclType(Record))),
4181 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00004182
John McCall94c3b562010-08-18 09:41:07 +00004183 void DiagnoseAbstractType() {
4184 if (Invalid) return;
4185 S.DiagnoseAbstractType(Record);
4186 Invalid = true;
4187 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00004188
John McCall94c3b562010-08-18 09:41:07 +00004189 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4190};
4191
4192struct CheckAbstractUsage {
4193 AbstractUsageInfo &Info;
4194 const NamedDecl *Ctx;
4195
4196 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4197 : Info(Info), Ctx(Ctx) {}
4198
4199 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4200 switch (TL.getTypeLocClass()) {
4201#define ABSTRACT_TYPELOC(CLASS, PARENT)
4202#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004203 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004204#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004205 }
John McCall94c3b562010-08-18 09:41:07 +00004206 }
Mike Stump1eb44332009-09-09 15:08:12 +00004207
John McCall94c3b562010-08-18 09:41:07 +00004208 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4209 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4210 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00004211 if (!TL.getArg(I))
4212 continue;
4213
John McCall94c3b562010-08-18 09:41:07 +00004214 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4215 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004216 }
John McCall94c3b562010-08-18 09:41:07 +00004217 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004218
John McCall94c3b562010-08-18 09:41:07 +00004219 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4220 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4221 }
Mike Stump1eb44332009-09-09 15:08:12 +00004222
John McCall94c3b562010-08-18 09:41:07 +00004223 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4224 // Visit the type parameters from a permissive context.
4225 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4226 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4227 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4228 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4229 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4230 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004231 }
John McCall94c3b562010-08-18 09:41:07 +00004232 }
Mike Stump1eb44332009-09-09 15:08:12 +00004233
John McCall94c3b562010-08-18 09:41:07 +00004234 // Visit pointee types from a permissive context.
4235#define CheckPolymorphic(Type) \
4236 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4237 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4238 }
4239 CheckPolymorphic(PointerTypeLoc)
4240 CheckPolymorphic(ReferenceTypeLoc)
4241 CheckPolymorphic(MemberPointerTypeLoc)
4242 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004243 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004244
John McCall94c3b562010-08-18 09:41:07 +00004245 /// Handle all the types we haven't given a more specific
4246 /// implementation for above.
4247 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4248 // Every other kind of type that we haven't called out already
4249 // that has an inner type is either (1) sugar or (2) contains that
4250 // inner type in some way as a subobject.
4251 if (TypeLoc Next = TL.getNextTypeLoc())
4252 return Visit(Next, Sel);
4253
4254 // If there's no inner type and we're in a permissive context,
4255 // don't diagnose.
4256 if (Sel == Sema::AbstractNone) return;
4257
4258 // Check whether the type matches the abstract type.
4259 QualType T = TL.getType();
4260 if (T->isArrayType()) {
4261 Sel = Sema::AbstractArrayType;
4262 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004263 }
John McCall94c3b562010-08-18 09:41:07 +00004264 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4265 if (CT != Info.AbstractType) return;
4266
4267 // It matched; do some magic.
4268 if (Sel == Sema::AbstractArrayType) {
4269 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4270 << T << TL.getSourceRange();
4271 } else {
4272 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4273 << Sel << T << TL.getSourceRange();
4274 }
4275 Info.DiagnoseAbstractType();
4276 }
4277};
4278
4279void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4280 Sema::AbstractDiagSelID Sel) {
4281 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4282}
4283
4284}
4285
4286/// Check for invalid uses of an abstract type in a method declaration.
4287static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4288 CXXMethodDecl *MD) {
4289 // No need to do the check on definitions, which require that
4290 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004291 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004292 return;
4293
4294 // For safety's sake, just ignore it if we don't have type source
4295 // information. This should never happen for non-implicit methods,
4296 // but...
4297 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4298 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4299}
4300
4301/// Check for invalid uses of an abstract type within a class definition.
4302static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4303 CXXRecordDecl *RD) {
4304 for (CXXRecordDecl::decl_iterator
4305 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4306 Decl *D = *I;
4307 if (D->isImplicit()) continue;
4308
4309 // Methods and method templates.
4310 if (isa<CXXMethodDecl>(D)) {
4311 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4312 } else if (isa<FunctionTemplateDecl>(D)) {
4313 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4314 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4315
4316 // Fields and static variables.
4317 } else if (isa<FieldDecl>(D)) {
4318 FieldDecl *FD = cast<FieldDecl>(D);
4319 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4320 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4321 } else if (isa<VarDecl>(D)) {
4322 VarDecl *VD = cast<VarDecl>(D);
4323 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4324 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4325
4326 // Nested classes and class templates.
4327 } else if (isa<CXXRecordDecl>(D)) {
4328 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4329 } else if (isa<ClassTemplateDecl>(D)) {
4330 CheckAbstractClassUsage(Info,
4331 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4332 }
4333 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004334}
4335
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004336/// \brief Perform semantic checks on a class definition that has been
4337/// completing, introducing implicitly-declared members, checking for
4338/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004339void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004340 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004341 return;
4342
John McCall94c3b562010-08-18 09:41:07 +00004343 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4344 AbstractUsageInfo Info(*this, Record);
4345 CheckAbstractClassUsage(Info, Record);
4346 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004347
4348 // If this is not an aggregate type and has no user-declared constructor,
4349 // complain about any non-static data members of reference or const scalar
4350 // type, since they will never get initializers.
4351 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004352 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4353 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004354 bool Complained = false;
4355 for (RecordDecl::field_iterator F = Record->field_begin(),
4356 FEnd = Record->field_end();
4357 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004358 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004359 continue;
4360
Douglas Gregor325e5932010-04-15 00:00:53 +00004361 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004362 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004363 if (!Complained) {
4364 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4365 << Record->getTagKind() << Record;
4366 Complained = true;
4367 }
4368
4369 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4370 << F->getType()->isReferenceType()
4371 << F->getDeclName();
4372 }
4373 }
4374 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004375
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004376 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004377 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004378
4379 if (Record->getIdentifier()) {
4380 // C++ [class.mem]p13:
4381 // If T is the name of a class, then each of the following shall have a
4382 // name different from T:
4383 // - every member of every anonymous union that is a member of class T.
4384 //
4385 // C++ [class.mem]p14:
4386 // In addition, if class T has a user-declared constructor (12.1), every
4387 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004388 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4389 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4390 ++I) {
4391 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004392 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4393 isa<IndirectFieldDecl>(D)) {
4394 Diag(D->getLocation(), diag::err_member_name_of_class)
4395 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004396 break;
4397 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004398 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004399 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004400
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004401 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004402 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004403 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004404 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004405 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4406 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4407 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004408
David Blaikieb6b5b972012-09-21 03:21:07 +00004409 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4410 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4411 DiagnoseAbstractType(Record);
4412 }
4413
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004414 if (!Record->isDependentType()) {
4415 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4416 MEnd = Record->method_end();
4417 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004418 // See if a method overloads virtual methods in a base
4419 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004420 if (!M->isStatic())
Eli Friedmandae92712013-09-05 23:51:03 +00004421 DiagnoseHiddenVirtualMethods(*M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004422
4423 // Check whether the explicitly-defaulted special members are valid.
4424 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4425 CheckExplicitlyDefaultedSpecialMember(*M);
4426
4427 // For an explicitly defaulted or deleted special member, we defer
4428 // determining triviality until the class is complete. That time is now!
4429 if (!M->isImplicit() && !M->isUserProvided()) {
4430 CXXSpecialMember CSM = getSpecialMember(*M);
4431 if (CSM != CXXInvalid) {
4432 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4433
4434 // Inform the class that we've finished declaring this member.
4435 Record->finishedDefaultedOrDeletedMember(*M);
4436 }
4437 }
4438 }
4439 }
4440
4441 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4442 // function that is not a constructor declares that member function to be
4443 // const. [...] The class of which that function is a member shall be
4444 // a literal type.
4445 //
4446 // If the class has virtual bases, any constexpr members will already have
4447 // been diagnosed by the checks performed on the member declaration, so
4448 // suppress this (less useful) diagnostic.
4449 //
4450 // We delay this until we know whether an explicitly-defaulted (or deleted)
4451 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004452 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004453 !Record->isLiteral() && !Record->getNumVBases()) {
4454 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4455 MEnd = Record->method_end();
4456 M != MEnd; ++M) {
4457 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4458 switch (Record->getTemplateSpecializationKind()) {
4459 case TSK_ImplicitInstantiation:
4460 case TSK_ExplicitInstantiationDeclaration:
4461 case TSK_ExplicitInstantiationDefinition:
4462 // If a template instantiates to a non-literal type, but its members
4463 // instantiate to constexpr functions, the template is technically
4464 // ill-formed, but we allow it for sanity.
4465 continue;
4466
4467 case TSK_Undeclared:
4468 case TSK_ExplicitSpecialization:
4469 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4470 diag::err_constexpr_method_non_literal);
4471 break;
4472 }
4473
4474 // Only produce one error per class.
4475 break;
4476 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004477 }
4478 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004479
Warren Huntb2969b12013-10-11 20:19:00 +00004480 // Check to see if we're trying to lay out a struct using the ms_struct
4481 // attribute that is dynamic.
4482 if (Record->isMsStruct(Context) && Record->isDynamicClass()) {
4483 Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed);
4484 Record->dropAttr<MsStructAttr>();
4485 }
4486
Richard Smith07b0fdc2013-03-18 21:12:30 +00004487 // Declare inheriting constructors. We do this eagerly here because:
4488 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004489 // constructors from different classes.
4490 // - The lazy declaration of the other implicit constructors is so as to not
4491 // waste space and performance on classes that are not meant to be
4492 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004493 // have inheriting constructors.
4494 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004495}
4496
Richard Smith7756afa2012-06-10 05:43:50 +00004497/// Is the special member function which would be selected to perform the
4498/// specified operation on the specified class type a constexpr constructor?
4499static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4500 Sema::CXXSpecialMember CSM,
4501 bool ConstArg) {
4502 Sema::SpecialMemberOverloadResult *SMOR =
4503 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4504 false, false, false, false);
4505 if (!SMOR || !SMOR->getMethod())
4506 // A constructor we wouldn't select can't be "involved in initializing"
4507 // anything.
4508 return true;
4509 return SMOR->getMethod()->isConstexpr();
4510}
4511
4512/// Determine whether the specified special member function would be constexpr
4513/// if it were implicitly defined.
4514static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4515 Sema::CXXSpecialMember CSM,
4516 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004517 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004518 return false;
4519
4520 // C++11 [dcl.constexpr]p4:
4521 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004522 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004523 switch (CSM) {
4524 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004525 // Since default constructor lookup is essentially trivial (and cannot
4526 // involve, for instance, template instantiation), we compute whether a
4527 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4528 //
4529 // This is important for performance; we need to know whether the default
4530 // constructor is constexpr to determine whether the type is a literal type.
4531 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4532
Richard Smith7756afa2012-06-10 05:43:50 +00004533 case Sema::CXXCopyConstructor:
4534 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004535 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004536 break;
4537
4538 case Sema::CXXCopyAssignment:
4539 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004540 if (!S.getLangOpts().CPlusPlus1y)
4541 return false;
4542 // In C++1y, we need to perform overload resolution.
4543 Ctor = false;
4544 break;
4545
Richard Smith7756afa2012-06-10 05:43:50 +00004546 case Sema::CXXDestructor:
4547 case Sema::CXXInvalid:
4548 return false;
4549 }
4550
4551 // -- if the class is a non-empty union, or for each non-empty anonymous
4552 // union member of a non-union class, exactly one non-static data member
4553 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004554 //
4555 // If we squint, this is guaranteed, since exactly one non-static data member
4556 // will be initialized (if the constructor isn't deleted), we just don't know
4557 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004558 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004559 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004560
4561 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004562 if (Ctor && ClassDecl->getNumVBases())
4563 return false;
4564
4565 // C++1y [class.copy]p26:
4566 // -- [the class] is a literal type, and
4567 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004568 return false;
4569
4570 // -- every constructor involved in initializing [...] base class
4571 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004572 // -- the assignment operator selected to copy/move each direct base
4573 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004574 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4575 BEnd = ClassDecl->bases_end();
4576 B != BEnd; ++B) {
4577 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4578 if (!BaseType) continue;
4579
4580 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4581 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4582 return false;
4583 }
4584
4585 // -- every constructor involved in initializing non-static data members
4586 // [...] shall be a constexpr constructor;
4587 // -- every non-static data member and base class sub-object shall be
4588 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004589 // -- for each non-stastic data member of X that is of class type (or array
4590 // thereof), the assignment operator selected to copy/move that member is
4591 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004592 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4593 FEnd = ClassDecl->field_end();
4594 F != FEnd; ++F) {
4595 if (F->isInvalidDecl())
4596 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004597 if (const RecordType *RecordTy =
4598 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004599 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4600 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4601 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004602 }
4603 }
4604
4605 // All OK, it's constexpr!
4606 return true;
4607}
4608
Richard Smithb9d0b762012-07-27 04:22:15 +00004609static Sema::ImplicitExceptionSpecification
4610computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4611 switch (S.getSpecialMember(MD)) {
4612 case Sema::CXXDefaultConstructor:
4613 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4614 case Sema::CXXCopyConstructor:
4615 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4616 case Sema::CXXCopyAssignment:
4617 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4618 case Sema::CXXMoveConstructor:
4619 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4620 case Sema::CXXMoveAssignment:
4621 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4622 case Sema::CXXDestructor:
4623 return S.ComputeDefaultedDtorExceptionSpec(MD);
4624 case Sema::CXXInvalid:
4625 break;
4626 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004627 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4628 "only special members have implicit exception specs");
4629 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004630}
4631
Richard Smithdd25e802012-07-30 23:48:14 +00004632static void
4633updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4634 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4635 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4636 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004637 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4638 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004639}
4640
Reid Kleckneref072032013-08-27 23:08:25 +00004641static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4642 CXXMethodDecl *MD) {
4643 FunctionProtoType::ExtProtoInfo EPI;
4644
4645 // Build an exception specification pointing back at this member.
4646 EPI.ExceptionSpecType = EST_Unevaluated;
4647 EPI.ExceptionSpecDecl = MD;
4648
4649 // Set the calling convention to the default for C++ instance methods.
4650 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4651 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4652 /*IsCXXMethod=*/true));
4653 return EPI;
4654}
4655
Richard Smithb9d0b762012-07-27 04:22:15 +00004656void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4657 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4658 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4659 return;
4660
Richard Smithdd25e802012-07-30 23:48:14 +00004661 // Evaluate the exception specification.
4662 ImplicitExceptionSpecification ExceptSpec =
4663 computeImplicitExceptionSpec(*this, Loc, MD);
4664
4665 // Update the type of the special member to use it.
4666 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4667
4668 // A user-provided destructor can be defined outside the class. When that
4669 // happens, be sure to update the exception specification on both
4670 // declarations.
4671 const FunctionProtoType *CanonicalFPT =
4672 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4673 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4674 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4675 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004676}
4677
Richard Smith3003e1d2012-05-15 04:39:51 +00004678void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4679 CXXRecordDecl *RD = MD->getParent();
4680 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004681
Richard Smith3003e1d2012-05-15 04:39:51 +00004682 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4683 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004684
4685 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004686 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004687 bool First = MD == MD->getCanonicalDecl();
4688
4689 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004690
4691 // C++11 [dcl.fct.def.default]p1:
4692 // A function that is explicitly defaulted shall
4693 // -- be a special member function (checked elsewhere),
4694 // -- have the same type (except for ref-qualifiers, and except that a
4695 // copy operation can take a non-const reference) as an implicit
4696 // declaration, and
4697 // -- not have default arguments.
4698 unsigned ExpectedParams = 1;
4699 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4700 ExpectedParams = 0;
4701 if (MD->getNumParams() != ExpectedParams) {
4702 // This also checks for default arguments: a copy or move constructor with a
4703 // default argument is classified as a default constructor, and assignment
4704 // operations and destructors can't have default arguments.
4705 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4706 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004707 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004708 } else if (MD->isVariadic()) {
4709 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4710 << CSM << MD->getSourceRange();
4711 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004712 }
4713
Richard Smith3003e1d2012-05-15 04:39:51 +00004714 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004715
Richard Smith7756afa2012-06-10 05:43:50 +00004716 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004717 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004718 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004719 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004720 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004721
Richard Smith3003e1d2012-05-15 04:39:51 +00004722 QualType ReturnType = Context.VoidTy;
4723 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4724 // Check for return type matching.
4725 ReturnType = Type->getResultType();
4726 QualType ExpectedReturnType =
4727 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4728 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4729 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4730 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4731 HadError = true;
4732 }
4733
4734 // A defaulted special member cannot have cv-qualifiers.
4735 if (Type->getTypeQuals()) {
4736 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004737 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004738 HadError = true;
4739 }
4740 }
4741
4742 // Check for parameter type matching.
4743 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004744 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004745 if (ExpectedParams && ArgType->isReferenceType()) {
4746 // Argument must be reference to possibly-const T.
4747 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004748 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004749
4750 if (ReferentType.isVolatileQualified()) {
4751 Diag(MD->getLocation(),
4752 diag::err_defaulted_special_member_volatile_param) << CSM;
4753 HadError = true;
4754 }
4755
Richard Smith7756afa2012-06-10 05:43:50 +00004756 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004757 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4758 Diag(MD->getLocation(),
4759 diag::err_defaulted_special_member_copy_const_param)
4760 << (CSM == CXXCopyAssignment);
4761 // FIXME: Explain why this special member can't be const.
4762 } else {
4763 Diag(MD->getLocation(),
4764 diag::err_defaulted_special_member_move_const_param)
4765 << (CSM == CXXMoveAssignment);
4766 }
4767 HadError = true;
4768 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004769 } else if (ExpectedParams) {
4770 // A copy assignment operator can take its argument by value, but a
4771 // defaulted one cannot.
4772 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004773 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004774 HadError = true;
4775 }
Sean Huntbe631222011-05-17 20:44:43 +00004776
Richard Smith61802452011-12-22 02:22:31 +00004777 // C++11 [dcl.fct.def.default]p2:
4778 // An explicitly-defaulted function may be declared constexpr only if it
4779 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004780 // Do not apply this rule to members of class templates, since core issue 1358
4781 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004782 // functions which cannot be constexpr (for non-constructors in C++11 and for
4783 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004784 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4785 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004786 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4787 : isa<CXXConstructorDecl>(MD)) &&
4788 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004789 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4790 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004791 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004792 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004793 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004794
Richard Smith61802452011-12-22 02:22:31 +00004795 // and may have an explicit exception-specification only if it is compatible
4796 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004797 if (Type->hasExceptionSpec()) {
4798 // Delay the check if this is the first declaration of the special member,
4799 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004800 if (First) {
4801 // If the exception specification needs to be instantiated, do so now,
4802 // before we clobber it with an EST_Unevaluated specification below.
4803 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4804 InstantiateExceptionSpec(MD->getLocStart(), MD);
4805 Type = MD->getType()->getAs<FunctionProtoType>();
4806 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004807 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004808 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004809 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4810 }
Richard Smith61802452011-12-22 02:22:31 +00004811
4812 // If a function is explicitly defaulted on its first declaration,
4813 if (First) {
4814 // -- it is implicitly considered to be constexpr if the implicit
4815 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004816 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004817
Richard Smith3003e1d2012-05-15 04:39:51 +00004818 // -- it is implicitly considered to have the same exception-specification
4819 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004820 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4821 EPI.ExceptionSpecType = EST_Unevaluated;
4822 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004823 MD->setType(Context.getFunctionType(ReturnType,
4824 ArrayRef<QualType>(&ArgType,
4825 ExpectedParams),
4826 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004827 }
4828
Richard Smith3003e1d2012-05-15 04:39:51 +00004829 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004830 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004831 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004832 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004833 // C++11 [dcl.fct.def.default]p4:
4834 // [For a] user-provided explicitly-defaulted function [...] if such a
4835 // function is implicitly defined as deleted, the program is ill-formed.
4836 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4837 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004838 }
4839 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004840
Richard Smith3003e1d2012-05-15 04:39:51 +00004841 if (HadError)
4842 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004843}
4844
Richard Smith1d28caf2012-12-11 01:14:52 +00004845/// Check whether the exception specification provided for an
4846/// explicitly-defaulted special member matches the exception specification
4847/// that would have been generated for an implicit special member, per
4848/// C++11 [dcl.fct.def.default]p2.
4849void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4850 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4851 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00004852 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4853 /*IsCXXMethod=*/true);
4854 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith1d28caf2012-12-11 01:14:52 +00004855 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4856 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004857 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004858
4859 // Ensure that it matches.
4860 CheckEquivalentExceptionSpec(
4861 PDiag(diag::err_incorrect_defaulted_exception_spec)
4862 << getSpecialMember(MD), PDiag(),
4863 ImplicitType, SourceLocation(),
4864 SpecifiedType, MD->getLocation());
4865}
4866
4867void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4868 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4869 I != N; ++I)
4870 CheckExplicitlyDefaultedMemberExceptionSpec(
4871 DelayedDefaultedMemberExceptionSpecs[I].first,
4872 DelayedDefaultedMemberExceptionSpecs[I].second);
4873
4874 DelayedDefaultedMemberExceptionSpecs.clear();
4875}
4876
Richard Smith7d5088a2012-02-18 02:02:13 +00004877namespace {
4878struct SpecialMemberDeletionInfo {
4879 Sema &S;
4880 CXXMethodDecl *MD;
4881 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004882 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004883
4884 // Properties of the special member, computed for convenience.
4885 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4886 SourceLocation Loc;
4887
4888 bool AllFieldsAreConst;
4889
4890 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004891 Sema::CXXSpecialMember CSM, bool Diagnose)
4892 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004893 IsConstructor(false), IsAssignment(false), IsMove(false),
4894 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4895 AllFieldsAreConst(true) {
4896 switch (CSM) {
4897 case Sema::CXXDefaultConstructor:
4898 case Sema::CXXCopyConstructor:
4899 IsConstructor = true;
4900 break;
4901 case Sema::CXXMoveConstructor:
4902 IsConstructor = true;
4903 IsMove = true;
4904 break;
4905 case Sema::CXXCopyAssignment:
4906 IsAssignment = true;
4907 break;
4908 case Sema::CXXMoveAssignment:
4909 IsAssignment = true;
4910 IsMove = true;
4911 break;
4912 case Sema::CXXDestructor:
4913 break;
4914 case Sema::CXXInvalid:
4915 llvm_unreachable("invalid special member kind");
4916 }
4917
4918 if (MD->getNumParams()) {
4919 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4920 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4921 }
4922 }
4923
4924 bool inUnion() const { return MD->getParent()->isUnion(); }
4925
4926 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004927 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4928 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004929 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004930 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4931 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4932 Quals = 0;
4933 return S.LookupSpecialMember(Class, CSM,
4934 ConstArg || (Quals & Qualifiers::Const),
4935 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004936 MD->getRefQualifier() == RQ_RValue,
4937 TQ & Qualifiers::Const,
4938 TQ & Qualifiers::Volatile);
4939 }
4940
Richard Smith6c4c36c2012-03-30 20:53:28 +00004941 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004942
Richard Smith6c4c36c2012-03-30 20:53:28 +00004943 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004944 bool shouldDeleteForField(FieldDecl *FD);
4945 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004946
Richard Smith517bb842012-07-18 03:51:16 +00004947 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4948 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004949 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4950 Sema::SpecialMemberOverloadResult *SMOR,
4951 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004952
4953 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004954};
4955}
4956
John McCall12d8d802012-04-09 20:53:23 +00004957/// Is the given special member inaccessible when used on the given
4958/// sub-object.
4959bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4960 CXXMethodDecl *target) {
4961 /// If we're operating on a base class, the object type is the
4962 /// type of this special member.
4963 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004964 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004965 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4966 objectTy = S.Context.getTypeDeclType(MD->getParent());
4967 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4968
4969 // If we're operating on a field, the object type is the type of the field.
4970 } else {
4971 objectTy = S.Context.getTypeDeclType(target->getParent());
4972 }
4973
4974 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4975}
4976
Richard Smith6c4c36c2012-03-30 20:53:28 +00004977/// Check whether we should delete a special member due to the implicit
4978/// definition containing a call to a special member of a subobject.
4979bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4980 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4981 bool IsDtorCallInCtor) {
4982 CXXMethodDecl *Decl = SMOR->getMethod();
4983 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4984
4985 int DiagKind = -1;
4986
4987 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4988 DiagKind = !Decl ? 0 : 1;
4989 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4990 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004991 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004992 DiagKind = 3;
4993 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4994 !Decl->isTrivial()) {
4995 // A member of a union must have a trivial corresponding special member.
4996 // As a weird special case, a destructor call from a union's constructor
4997 // must be accessible and non-deleted, but need not be trivial. Such a
4998 // destructor is never actually called, but is semantically checked as
4999 // if it were.
5000 DiagKind = 4;
5001 }
5002
5003 if (DiagKind == -1)
5004 return false;
5005
5006 if (Diagnose) {
5007 if (Field) {
5008 S.Diag(Field->getLocation(),
5009 diag::note_deleted_special_member_class_subobject)
5010 << CSM << MD->getParent() << /*IsField*/true
5011 << Field << DiagKind << IsDtorCallInCtor;
5012 } else {
5013 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
5014 S.Diag(Base->getLocStart(),
5015 diag::note_deleted_special_member_class_subobject)
5016 << CSM << MD->getParent() << /*IsField*/false
5017 << Base->getType() << DiagKind << IsDtorCallInCtor;
5018 }
5019
5020 if (DiagKind == 1)
5021 S.NoteDeletedFunction(Decl);
5022 // FIXME: Explain inaccessibility if DiagKind == 3.
5023 }
5024
5025 return true;
5026}
5027
Richard Smith9a561d52012-02-26 09:11:52 +00005028/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00005029/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00005030bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00005031 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005032 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00005033
5034 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00005035 // -- any direct or virtual base class, or non-static data member with no
5036 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00005037 // either M has no default constructor or overload resolution as applied
5038 // to M's default constructor results in an ambiguity or in a function
5039 // that is deleted or inaccessible
5040 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5041 // -- a direct or virtual base class B that cannot be copied/moved because
5042 // overload resolution, as applied to B's corresponding special member,
5043 // results in an ambiguity or a function that is deleted or inaccessible
5044 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00005045 // C++11 [class.dtor]p5:
5046 // -- any direct or virtual base class [...] has a type with a destructor
5047 // that is deleted or inaccessible
5048 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00005049 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00005050 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00005051 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005052
Richard Smith6c4c36c2012-03-30 20:53:28 +00005053 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5054 // -- any direct or virtual base class or non-static data member has a
5055 // type with a destructor that is deleted or inaccessible
5056 if (IsConstructor) {
5057 Sema::SpecialMemberOverloadResult *SMOR =
5058 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5059 false, false, false, false, false);
5060 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5061 return true;
5062 }
5063
Richard Smith9a561d52012-02-26 09:11:52 +00005064 return false;
5065}
5066
5067/// Check whether we should delete a special member function due to the class
5068/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005069bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00005070 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00005071 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00005072}
5073
5074/// Check whether we should delete a special member function due to the class
5075/// having a particular non-static data member.
5076bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5077 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5078 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5079
5080 if (CSM == Sema::CXXDefaultConstructor) {
5081 // For a default constructor, all references must be initialized in-class
5082 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005083 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5084 if (Diagnose)
5085 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5086 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005087 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005088 }
Richard Smith79363f52012-02-27 06:07:25 +00005089 // C++11 [class.ctor]p5: any non-variant non-static data member of
5090 // const-qualified type (or array thereof) with no
5091 // brace-or-equal-initializer does not have a user-provided default
5092 // constructor.
5093 if (!inUnion() && FieldType.isConstQualified() &&
5094 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005095 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5096 if (Diagnose)
5097 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005098 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00005099 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005100 }
5101
5102 if (inUnion() && !FieldType.isConstQualified())
5103 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005104 } else if (CSM == Sema::CXXCopyConstructor) {
5105 // For a copy constructor, data members must not be of rvalue reference
5106 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005107 if (FieldType->isRValueReferenceType()) {
5108 if (Diagnose)
5109 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5110 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00005111 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005112 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005113 } else if (IsAssignment) {
5114 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005115 if (FieldType->isReferenceType()) {
5116 if (Diagnose)
5117 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5118 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005119 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005120 }
5121 if (!FieldRecord && FieldType.isConstQualified()) {
5122 // C++11 [class.copy]p23:
5123 // -- a non-static data member of const non-class type (or array thereof)
5124 if (Diagnose)
5125 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005126 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005127 return true;
5128 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005129 }
5130
5131 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005132 // Some additional restrictions exist on the variant members.
5133 if (!inUnion() && FieldRecord->isUnion() &&
5134 FieldRecord->isAnonymousStructOrUnion()) {
5135 bool AllVariantFieldsAreConst = true;
5136
Richard Smithdf8dc862012-03-29 19:00:10 +00005137 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00005138 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5139 UE = FieldRecord->field_end();
5140 UI != UE; ++UI) {
5141 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00005142
5143 if (!UnionFieldType.isConstQualified())
5144 AllVariantFieldsAreConst = false;
5145
Richard Smith9a561d52012-02-26 09:11:52 +00005146 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5147 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00005148 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5149 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00005150 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005151 }
5152
5153 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00005154 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005155 FieldRecord->field_begin() != FieldRecord->field_end()) {
5156 if (Diagnose)
5157 S.Diag(FieldRecord->getLocation(),
5158 diag::note_deleted_default_ctor_all_const)
5159 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00005160 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005161 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005162
Richard Smithdf8dc862012-03-29 19:00:10 +00005163 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00005164 // This is technically non-conformant, but sanity demands it.
5165 return false;
5166 }
5167
Richard Smith517bb842012-07-18 03:51:16 +00005168 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5169 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00005170 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005171 }
5172
5173 return false;
5174}
5175
5176/// C++11 [class.ctor] p5:
5177/// A defaulted default constructor for a class X is defined as deleted if
5178/// X is a union and all of its variant members are of const-qualified type.
5179bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00005180 // This is a silly definition, because it gives an empty union a deleted
5181 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005182 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5183 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5184 if (Diagnose)
5185 S.Diag(MD->getParent()->getLocation(),
5186 diag::note_deleted_default_ctor_all_const)
5187 << MD->getParent() << /*not anonymous union*/0;
5188 return true;
5189 }
5190 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005191}
5192
5193/// Determine whether a defaulted special member function should be defined as
5194/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5195/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005196bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5197 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00005198 if (MD->isInvalidDecl())
5199 return false;
Sean Hunte16da072011-10-10 06:18:57 +00005200 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00005201 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00005202 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005203 return false;
5204
Richard Smith7d5088a2012-02-18 02:02:13 +00005205 // C++11 [expr.lambda.prim]p19:
5206 // The closure type associated with a lambda-expression has a
5207 // deleted (8.4.3) default constructor and a deleted copy
5208 // assignment operator.
5209 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005210 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5211 if (Diagnose)
5212 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005213 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005214 }
5215
Richard Smith5bdaac52012-04-02 20:59:25 +00005216 // For an anonymous struct or union, the copy and assignment special members
5217 // will never be used, so skip the check. For an anonymous union declared at
5218 // namespace scope, the constructor and destructor are used.
5219 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5220 RD->isAnonymousStructOrUnion())
5221 return false;
5222
Richard Smith6c4c36c2012-03-30 20:53:28 +00005223 // C++11 [class.copy]p7, p18:
5224 // If the class definition declares a move constructor or move assignment
5225 // operator, an implicitly declared copy constructor or copy assignment
5226 // operator is defined as deleted.
5227 if (MD->isImplicit() &&
5228 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5229 CXXMethodDecl *UserDeclaredMove = 0;
5230
5231 // In Microsoft mode, a user-declared move only causes the deletion of the
5232 // corresponding copy operation, not both copy operations.
5233 if (RD->hasUserDeclaredMoveConstructor() &&
5234 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5235 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005236
5237 // Find any user-declared move constructor.
5238 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5239 E = RD->ctor_end(); I != E; ++I) {
5240 if (I->isMoveConstructor()) {
5241 UserDeclaredMove = *I;
5242 break;
5243 }
5244 }
Richard Smith1c931be2012-04-02 18:40:40 +00005245 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005246 } else if (RD->hasUserDeclaredMoveAssignment() &&
5247 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5248 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005249
5250 // Find any user-declared move assignment operator.
5251 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5252 E = RD->method_end(); I != E; ++I) {
5253 if (I->isMoveAssignmentOperator()) {
5254 UserDeclaredMove = *I;
5255 break;
5256 }
5257 }
Richard Smith1c931be2012-04-02 18:40:40 +00005258 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005259 }
5260
5261 if (UserDeclaredMove) {
5262 Diag(UserDeclaredMove->getLocation(),
5263 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005264 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005265 << UserDeclaredMove->isMoveAssignmentOperator();
5266 return true;
5267 }
5268 }
Sean Hunte16da072011-10-10 06:18:57 +00005269
Richard Smith5bdaac52012-04-02 20:59:25 +00005270 // Do access control from the special member function
5271 ContextRAII MethodContext(*this, MD);
5272
Richard Smith9a561d52012-02-26 09:11:52 +00005273 // C++11 [class.dtor]p5:
5274 // -- for a virtual destructor, lookup of the non-array deallocation function
5275 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005276 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005277 FunctionDecl *OperatorDelete = 0;
5278 DeclarationName Name =
5279 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5280 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005281 OperatorDelete, false)) {
5282 if (Diagnose)
5283 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005284 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005285 }
Richard Smith9a561d52012-02-26 09:11:52 +00005286 }
5287
Richard Smith6c4c36c2012-03-30 20:53:28 +00005288 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005289
Sean Huntcdee3fe2011-05-11 22:34:38 +00005290 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005291 BE = RD->bases_end(); BI != BE; ++BI)
5292 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005293 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005294 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005295
Richard Smithe0883602013-07-22 18:06:23 +00005296 // Per DR1611, do not consider virtual bases of constructors of abstract
5297 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005298 if (!RD->isAbstract() || !SMI.IsConstructor) {
5299 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5300 BE = RD->vbases_end();
5301 BI != BE; ++BI)
5302 if (SMI.shouldDeleteForBase(BI))
5303 return true;
5304 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005305
5306 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005307 FE = RD->field_end(); FI != FE; ++FI)
5308 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005309 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005310 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005311
Richard Smith7d5088a2012-02-18 02:02:13 +00005312 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005313 return true;
5314
5315 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005316}
5317
Richard Smithac713512012-12-08 02:53:02 +00005318/// Perform lookup for a special member of the specified kind, and determine
5319/// whether it is trivial. If the triviality can be determined without the
5320/// lookup, skip it. This is intended for use when determining whether a
5321/// special member of a containing object is trivial, and thus does not ever
5322/// perform overload resolution for default constructors.
5323///
5324/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5325/// member that was most likely to be intended to be trivial, if any.
5326static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5327 Sema::CXXSpecialMember CSM, unsigned Quals,
5328 CXXMethodDecl **Selected) {
5329 if (Selected)
5330 *Selected = 0;
5331
5332 switch (CSM) {
5333 case Sema::CXXInvalid:
5334 llvm_unreachable("not a special member");
5335
5336 case Sema::CXXDefaultConstructor:
5337 // C++11 [class.ctor]p5:
5338 // A default constructor is trivial if:
5339 // - all the [direct subobjects] have trivial default constructors
5340 //
5341 // Note, no overload resolution is performed in this case.
5342 if (RD->hasTrivialDefaultConstructor())
5343 return true;
5344
5345 if (Selected) {
5346 // If there's a default constructor which could have been trivial, dig it
5347 // out. Otherwise, if there's any user-provided default constructor, point
5348 // to that as an example of why there's not a trivial one.
5349 CXXConstructorDecl *DefCtor = 0;
5350 if (RD->needsImplicitDefaultConstructor())
5351 S.DeclareImplicitDefaultConstructor(RD);
5352 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5353 CE = RD->ctor_end(); CI != CE; ++CI) {
5354 if (!CI->isDefaultConstructor())
5355 continue;
5356 DefCtor = *CI;
5357 if (!DefCtor->isUserProvided())
5358 break;
5359 }
5360
5361 *Selected = DefCtor;
5362 }
5363
5364 return false;
5365
5366 case Sema::CXXDestructor:
5367 // C++11 [class.dtor]p5:
5368 // A destructor is trivial if:
5369 // - all the direct [subobjects] have trivial destructors
5370 if (RD->hasTrivialDestructor())
5371 return true;
5372
5373 if (Selected) {
5374 if (RD->needsImplicitDestructor())
5375 S.DeclareImplicitDestructor(RD);
5376 *Selected = RD->getDestructor();
5377 }
5378
5379 return false;
5380
5381 case Sema::CXXCopyConstructor:
5382 // C++11 [class.copy]p12:
5383 // A copy constructor is trivial if:
5384 // - the constructor selected to copy each direct [subobject] is trivial
5385 if (RD->hasTrivialCopyConstructor()) {
5386 if (Quals == Qualifiers::Const)
5387 // We must either select the trivial copy constructor or reach an
5388 // ambiguity; no need to actually perform overload resolution.
5389 return true;
5390 } else if (!Selected) {
5391 return false;
5392 }
5393 // In C++98, we are not supposed to perform overload resolution here, but we
5394 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5395 // cases like B as having a non-trivial copy constructor:
5396 // struct A { template<typename T> A(T&); };
5397 // struct B { mutable A a; };
5398 goto NeedOverloadResolution;
5399
5400 case Sema::CXXCopyAssignment:
5401 // C++11 [class.copy]p25:
5402 // A copy assignment operator is trivial if:
5403 // - the assignment operator selected to copy each direct [subobject] is
5404 // trivial
5405 if (RD->hasTrivialCopyAssignment()) {
5406 if (Quals == Qualifiers::Const)
5407 return true;
5408 } else if (!Selected) {
5409 return false;
5410 }
5411 // In C++98, we are not supposed to perform overload resolution here, but we
5412 // treat that as a language defect.
5413 goto NeedOverloadResolution;
5414
5415 case Sema::CXXMoveConstructor:
5416 case Sema::CXXMoveAssignment:
5417 NeedOverloadResolution:
5418 Sema::SpecialMemberOverloadResult *SMOR =
5419 S.LookupSpecialMember(RD, CSM,
5420 Quals & Qualifiers::Const,
5421 Quals & Qualifiers::Volatile,
5422 /*RValueThis*/false, /*ConstThis*/false,
5423 /*VolatileThis*/false);
5424
5425 // The standard doesn't describe how to behave if the lookup is ambiguous.
5426 // We treat it as not making the member non-trivial, just like the standard
5427 // mandates for the default constructor. This should rarely matter, because
5428 // the member will also be deleted.
5429 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5430 return true;
5431
5432 if (!SMOR->getMethod()) {
5433 assert(SMOR->getKind() ==
5434 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5435 return false;
5436 }
5437
5438 // We deliberately don't check if we found a deleted special member. We're
5439 // not supposed to!
5440 if (Selected)
5441 *Selected = SMOR->getMethod();
5442 return SMOR->getMethod()->isTrivial();
5443 }
5444
5445 llvm_unreachable("unknown special method kind");
5446}
5447
Benjamin Kramera574c892013-02-15 12:30:38 +00005448static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005449 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5450 CI != CE; ++CI)
5451 if (!CI->isImplicit())
5452 return *CI;
5453
5454 // Look for constructor templates.
5455 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5456 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5457 if (CXXConstructorDecl *CD =
5458 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5459 return CD;
5460 }
5461
5462 return 0;
5463}
5464
5465/// The kind of subobject we are checking for triviality. The values of this
5466/// enumeration are used in diagnostics.
5467enum TrivialSubobjectKind {
5468 /// The subobject is a base class.
5469 TSK_BaseClass,
5470 /// The subobject is a non-static data member.
5471 TSK_Field,
5472 /// The object is actually the complete object.
5473 TSK_CompleteObject
5474};
5475
5476/// Check whether the special member selected for a given type would be trivial.
5477static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5478 QualType SubType,
5479 Sema::CXXSpecialMember CSM,
5480 TrivialSubobjectKind Kind,
5481 bool Diagnose) {
5482 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5483 if (!SubRD)
5484 return true;
5485
5486 CXXMethodDecl *Selected;
5487 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5488 Diagnose ? &Selected : 0))
5489 return true;
5490
5491 if (Diagnose) {
5492 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5493 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5494 << Kind << SubType.getUnqualifiedType();
5495 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5496 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5497 } else if (!Selected)
5498 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5499 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5500 else if (Selected->isUserProvided()) {
5501 if (Kind == TSK_CompleteObject)
5502 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5503 << Kind << SubType.getUnqualifiedType() << CSM;
5504 else {
5505 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5506 << Kind << SubType.getUnqualifiedType() << CSM;
5507 S.Diag(Selected->getLocation(), diag::note_declared_at);
5508 }
5509 } else {
5510 if (Kind != TSK_CompleteObject)
5511 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5512 << Kind << SubType.getUnqualifiedType() << CSM;
5513
5514 // Explain why the defaulted or deleted special member isn't trivial.
5515 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5516 }
5517 }
5518
5519 return false;
5520}
5521
5522/// Check whether the members of a class type allow a special member to be
5523/// trivial.
5524static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5525 Sema::CXXSpecialMember CSM,
5526 bool ConstArg, bool Diagnose) {
5527 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5528 FE = RD->field_end(); FI != FE; ++FI) {
5529 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5530 continue;
5531
5532 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5533
5534 // Pretend anonymous struct or union members are members of this class.
5535 if (FI->isAnonymousStructOrUnion()) {
5536 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5537 CSM, ConstArg, Diagnose))
5538 return false;
5539 continue;
5540 }
5541
5542 // C++11 [class.ctor]p5:
5543 // A default constructor is trivial if [...]
5544 // -- no non-static data member of its class has a
5545 // brace-or-equal-initializer
5546 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5547 if (Diagnose)
5548 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5549 return false;
5550 }
5551
5552 // Objective C ARC 4.3.5:
5553 // [...] nontrivally ownership-qualified types are [...] not trivially
5554 // default constructible, copy constructible, move constructible, copy
5555 // assignable, move assignable, or destructible [...]
5556 if (S.getLangOpts().ObjCAutoRefCount &&
5557 FieldType.hasNonTrivialObjCLifetime()) {
5558 if (Diagnose)
5559 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5560 << RD << FieldType.getObjCLifetime();
5561 return false;
5562 }
5563
5564 if (ConstArg && !FI->isMutable())
5565 FieldType.addConst();
5566 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5567 TSK_Field, Diagnose))
5568 return false;
5569 }
5570
5571 return true;
5572}
5573
5574/// Diagnose why the specified class does not have a trivial special member of
5575/// the given kind.
5576void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5577 QualType Ty = Context.getRecordType(RD);
5578 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5579 Ty.addConst();
5580
5581 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5582 TSK_CompleteObject, /*Diagnose*/true);
5583}
5584
5585/// Determine whether a defaulted or deleted special member function is trivial,
5586/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5587/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5588bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5589 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005590 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5591
5592 CXXRecordDecl *RD = MD->getParent();
5593
5594 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005595
5596 // C++11 [class.copy]p12, p25:
5597 // A [special member] is trivial if its declared parameter type is the same
5598 // as if it had been implicitly declared [...]
5599 switch (CSM) {
5600 case CXXDefaultConstructor:
5601 case CXXDestructor:
5602 // Trivial default constructors and destructors cannot have parameters.
5603 break;
5604
5605 case CXXCopyConstructor:
5606 case CXXCopyAssignment: {
5607 // Trivial copy operations always have const, non-volatile parameter types.
5608 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005609 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005610 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5611 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5612 if (Diagnose)
5613 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5614 << Param0->getSourceRange() << Param0->getType()
5615 << Context.getLValueReferenceType(
5616 Context.getRecordType(RD).withConst());
5617 return false;
5618 }
5619 break;
5620 }
5621
5622 case CXXMoveConstructor:
5623 case CXXMoveAssignment: {
5624 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005625 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005626 const RValueReferenceType *RT =
5627 Param0->getType()->getAs<RValueReferenceType>();
5628 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5629 if (Diagnose)
5630 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5631 << Param0->getSourceRange() << Param0->getType()
5632 << Context.getRValueReferenceType(Context.getRecordType(RD));
5633 return false;
5634 }
5635 break;
5636 }
5637
5638 case CXXInvalid:
5639 llvm_unreachable("not a special member");
5640 }
5641
5642 // FIXME: We require that the parameter-declaration-clause is equivalent to
5643 // that of an implicit declaration, not just that the declared parameter type
5644 // matches, in order to prevent absuridities like a function simultaneously
5645 // being a trivial copy constructor and a non-trivial default constructor.
5646 // This issue has not yet been assigned a core issue number.
5647 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5648 if (Diagnose)
5649 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5650 diag::note_nontrivial_default_arg)
5651 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5652 return false;
5653 }
5654 if (MD->isVariadic()) {
5655 if (Diagnose)
5656 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5657 return false;
5658 }
5659
5660 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5661 // A copy/move [constructor or assignment operator] is trivial if
5662 // -- the [member] selected to copy/move each direct base class subobject
5663 // is trivial
5664 //
5665 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5666 // A [default constructor or destructor] is trivial if
5667 // -- all the direct base classes have trivial [default constructors or
5668 // destructors]
5669 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5670 BE = RD->bases_end(); BI != BE; ++BI)
5671 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5672 ConstArg ? BI->getType().withConst()
5673 : BI->getType(),
5674 CSM, TSK_BaseClass, Diagnose))
5675 return false;
5676
5677 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5678 // A copy/move [constructor or assignment operator] for a class X is
5679 // trivial if
5680 // -- for each non-static data member of X that is of class type (or array
5681 // thereof), the constructor selected to copy/move that member is
5682 // trivial
5683 //
5684 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5685 // A [default constructor or destructor] is trivial if
5686 // -- for all of the non-static data members of its class that are of class
5687 // type (or array thereof), each such class has a trivial [default
5688 // constructor or destructor]
5689 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5690 return false;
5691
5692 // C++11 [class.dtor]p5:
5693 // A destructor is trivial if [...]
5694 // -- the destructor is not virtual
5695 if (CSM == CXXDestructor && MD->isVirtual()) {
5696 if (Diagnose)
5697 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5698 return false;
5699 }
5700
5701 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5702 // A [special member] for class X is trivial if [...]
5703 // -- class X has no virtual functions and no virtual base classes
5704 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5705 if (!Diagnose)
5706 return false;
5707
5708 if (RD->getNumVBases()) {
5709 // Check for virtual bases. We already know that the corresponding
5710 // member in all bases is trivial, so vbases must all be direct.
5711 CXXBaseSpecifier &BS = *RD->vbases_begin();
5712 assert(BS.isVirtual());
5713 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5714 return false;
5715 }
5716
5717 // Must have a virtual method.
5718 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5719 ME = RD->method_end(); MI != ME; ++MI) {
5720 if (MI->isVirtual()) {
5721 SourceLocation MLoc = MI->getLocStart();
5722 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5723 return false;
5724 }
5725 }
5726
5727 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5728 }
5729
5730 // Looks like it's trivial!
5731 return true;
5732}
5733
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005734/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005735namespace {
5736 struct FindHiddenVirtualMethodData {
5737 Sema *S;
5738 CXXMethodDecl *Method;
5739 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005740 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005741 };
5742}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005743
David Blaikie5f750682012-10-19 00:53:08 +00005744/// \brief Check whether any most overriden method from MD in Methods
5745static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5746 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5747 if (MD->size_overridden_methods() == 0)
5748 return Methods.count(MD->getCanonicalDecl());
5749 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5750 E = MD->end_overridden_methods();
5751 I != E; ++I)
5752 if (CheckMostOverridenMethods(*I, Methods))
5753 return true;
5754 return false;
5755}
5756
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005757/// \brief Member lookup function that determines whether a given C++
5758/// method overloads virtual methods in a base class without overriding any,
5759/// to be used with CXXRecordDecl::lookupInBases().
5760static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5761 CXXBasePath &Path,
5762 void *UserData) {
5763 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5764
5765 FindHiddenVirtualMethodData &Data
5766 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5767
5768 DeclarationName Name = Data.Method->getDeclName();
5769 assert(Name.getNameKind() == DeclarationName::Identifier);
5770
5771 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005772 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005773 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005774 !Path.Decls.empty();
5775 Path.Decls = Path.Decls.slice(1)) {
5776 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005777 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005778 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005779 foundSameNameMethod = true;
5780 // Interested only in hidden virtual methods.
5781 if (!MD->isVirtual())
5782 continue;
5783 // If the method we are checking overrides a method from its base
5784 // don't warn about the other overloaded methods.
5785 if (!Data.S->IsOverload(Data.Method, MD, false))
5786 return true;
5787 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005788 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005789 overloadedMethods.push_back(MD);
5790 }
5791 }
5792
5793 if (foundSameNameMethod)
5794 Data.OverloadedMethods.append(overloadedMethods.begin(),
5795 overloadedMethods.end());
5796 return foundSameNameMethod;
5797}
5798
David Blaikie5f750682012-10-19 00:53:08 +00005799/// \brief Add the most overriden methods from MD to Methods
5800static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5801 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5802 if (MD->size_overridden_methods() == 0)
5803 Methods.insert(MD->getCanonicalDecl());
5804 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5805 E = MD->end_overridden_methods();
5806 I != E; ++I)
5807 AddMostOverridenMethods(*I, Methods);
5808}
5809
Eli Friedmandae92712013-09-05 23:51:03 +00005810/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005811/// overriding any.
Eli Friedmandae92712013-09-05 23:51:03 +00005812void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5813 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramerc4704422012-05-19 16:03:58 +00005814 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005815 return;
5816
5817 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5818 /*bool RecordPaths=*/false,
5819 /*bool DetectVirtual=*/false);
5820 FindHiddenVirtualMethodData Data;
5821 Data.Method = MD;
5822 Data.S = this;
5823
5824 // Keep the base methods that were overriden or introduced in the subclass
5825 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmandae92712013-09-05 23:51:03 +00005826 CXXRecordDecl *DC = MD->getParent();
David Blaikie3bc93e32012-12-19 00:45:41 +00005827 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5828 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5829 NamedDecl *ND = *I;
5830 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005831 ND = shad->getTargetDecl();
5832 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5833 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005834 }
5835
Eli Friedmandae92712013-09-05 23:51:03 +00005836 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5837 OverloadedMethods = Data.OverloadedMethods;
5838}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005839
Eli Friedmandae92712013-09-05 23:51:03 +00005840void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5841 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5842 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5843 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5844 PartialDiagnostic PD = PDiag(
5845 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5846 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5847 Diag(overloadedMD->getLocation(), PD);
5848 }
5849}
5850
5851/// \brief Diagnose methods which overload virtual methods in a base class
5852/// without overriding any.
5853void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5854 if (MD->isInvalidDecl())
5855 return;
5856
5857 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5858 MD->getLocation()) == DiagnosticsEngine::Ignored)
5859 return;
5860
5861 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5862 FindHiddenVirtualMethods(MD, OverloadedMethods);
5863 if (!OverloadedMethods.empty()) {
5864 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5865 << MD << (OverloadedMethods.size() > 1);
5866
5867 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005868 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005869}
5870
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005871void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005872 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005873 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005874 SourceLocation RBrac,
5875 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005876 if (!TagDecl)
5877 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005878
Douglas Gregor42af25f2009-05-11 19:58:34 +00005879 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005880
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005881 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5882 if (l->getKind() != AttributeList::AT_Visibility)
5883 continue;
5884 l->setInvalid();
5885 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5886 l->getName();
5887 }
5888
David Blaikie77b6de02011-09-22 02:58:26 +00005889 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005890 // strict aliasing violation!
5891 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005892 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005893
Douglas Gregor23c94db2010-07-02 17:43:08 +00005894 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005895 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005896}
5897
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005898/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5899/// special functions, such as the default constructor, copy
5900/// constructor, or destructor, to the given C++ class (C++
5901/// [special]p1). This routine can only be executed just before the
5902/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005903void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005904 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005905 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005906
Richard Smithbc2a35d2012-12-08 08:32:28 +00005907 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005908 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005909
Richard Smithbc2a35d2012-12-08 08:32:28 +00005910 // If the properties or semantics of the copy constructor couldn't be
5911 // determined while the class was being declared, force a declaration
5912 // of it now.
5913 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5914 DeclareImplicitCopyConstructor(ClassDecl);
5915 }
5916
Richard Smith80ad52f2013-01-02 11:42:31 +00005917 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005918 ++ASTContext::NumImplicitMoveConstructors;
5919
Richard Smithbc2a35d2012-12-08 08:32:28 +00005920 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5921 DeclareImplicitMoveConstructor(ClassDecl);
5922 }
5923
Douglas Gregora376d102010-07-02 21:50:04 +00005924 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5925 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005926
5927 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005928 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005929 // it shows up in the right place in the vtable and that we diagnose
5930 // problems with the implicit exception specification.
5931 if (ClassDecl->isDynamicClass() ||
5932 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005933 DeclareImplicitCopyAssignment(ClassDecl);
5934 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005935
Richard Smith80ad52f2013-01-02 11:42:31 +00005936 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005937 ++ASTContext::NumImplicitMoveAssignmentOperators;
5938
5939 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005940 if (ClassDecl->isDynamicClass() ||
5941 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005942 DeclareImplicitMoveAssignment(ClassDecl);
5943 }
5944
Douglas Gregor4923aa22010-07-02 20:37:36 +00005945 if (!ClassDecl->hasUserDeclaredDestructor()) {
5946 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005947
5948 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005949 // have to declare the destructor immediately. This ensures that, e.g., it
5950 // shows up in the right place in the vtable and that we diagnose problems
5951 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005952 if (ClassDecl->isDynamicClass() ||
5953 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005954 DeclareImplicitDestructor(ClassDecl);
5955 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005956}
5957
Francois Pichet8387e2a2011-04-22 22:18:13 +00005958void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5959 if (!D)
5960 return;
5961
5962 int NumParamList = D->getNumTemplateParameterLists();
5963 for (int i = 0; i < NumParamList; i++) {
5964 TemplateParameterList* Params = D->getTemplateParameterList(i);
5965 for (TemplateParameterList::iterator Param = Params->begin(),
5966 ParamEnd = Params->end();
5967 Param != ParamEnd; ++Param) {
5968 NamedDecl *Named = cast<NamedDecl>(*Param);
5969 if (Named->getDeclName()) {
5970 S->AddDecl(Named);
5971 IdResolver.AddDecl(Named);
5972 }
5973 }
5974 }
5975}
5976
John McCalld226f652010-08-21 09:40:31 +00005977void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005978 if (!D)
5979 return;
5980
5981 TemplateParameterList *Params = 0;
5982 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5983 Params = Template->getTemplateParameters();
5984 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5985 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5986 Params = PartialSpec->getTemplateParameters();
5987 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005988 return;
5989
Douglas Gregor6569d682009-05-27 23:11:45 +00005990 for (TemplateParameterList::iterator Param = Params->begin(),
5991 ParamEnd = Params->end();
5992 Param != ParamEnd; ++Param) {
5993 NamedDecl *Named = cast<NamedDecl>(*Param);
5994 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005995 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005996 IdResolver.AddDecl(Named);
5997 }
5998 }
5999}
6000
John McCalld226f652010-08-21 09:40:31 +00006001void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00006002 if (!RecordD) return;
6003 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00006004 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00006005 PushDeclContext(S, Record);
6006}
6007
John McCalld226f652010-08-21 09:40:31 +00006008void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00006009 if (!RecordD) return;
6010 PopDeclContext();
6011}
6012
Douglas Gregor72b505b2008-12-16 21:30:33 +00006013/// ActOnStartDelayedCXXMethodDeclaration - We have completed
6014/// parsing a top-level (non-nested) C++ class, and we are now
6015/// parsing those parts of the given Method declaration that could
6016/// not be parsed earlier (C++ [class.mem]p2), such as default
6017/// arguments. This action should enter the scope of the given
6018/// Method declaration as if we had just parsed the qualified method
6019/// name. However, it should not bring the parameters into scope;
6020/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00006021void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006022}
6023
6024/// ActOnDelayedCXXMethodParameter - We've already started a delayed
6025/// C++ method declaration. We're (re-)introducing the given
6026/// function parameter into scope for use in parsing later parts of
6027/// the method declaration. For example, we could see an
6028/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00006029void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006030 if (!ParamD)
6031 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006032
John McCalld226f652010-08-21 09:40:31 +00006033 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00006034
6035 // If this parameter has an unparsed default argument, clear it out
6036 // to make way for the parsed default argument.
6037 if (Param->hasUnparsedDefaultArg())
6038 Param->setDefaultArg(0);
6039
John McCalld226f652010-08-21 09:40:31 +00006040 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006041 if (Param->getDeclName())
6042 IdResolver.AddDecl(Param);
6043}
6044
6045/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6046/// processing the delayed method declaration for Method. The method
6047/// declaration is now considered finished. There may be a separate
6048/// ActOnStartOfFunctionDef action later (not necessarily
6049/// immediately!) for this method, if it was also defined inside the
6050/// class body.
John McCalld226f652010-08-21 09:40:31 +00006051void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006052 if (!MethodD)
6053 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006054
Douglas Gregorefd5bda2009-08-24 11:57:43 +00006055 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00006056
John McCalld226f652010-08-21 09:40:31 +00006057 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006058
6059 // Now that we have our default arguments, check the constructor
6060 // again. It could produce additional diagnostics or affect whether
6061 // the class has implicitly-declared destructors, among other
6062 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00006063 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6064 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006065
6066 // Check the default arguments, which we may have added.
6067 if (!Method->isInvalidDecl())
6068 CheckCXXDefaultArguments(Method);
6069}
6070
Douglas Gregor42a552f2008-11-05 20:51:48 +00006071/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00006072/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00006073/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006074/// emit diagnostics and set the invalid bit to true. In any case, the type
6075/// will be updated to reflect a well-formed type for the constructor and
6076/// returned.
6077QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006078 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006079 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006080
6081 // C++ [class.ctor]p3:
6082 // A constructor shall not be virtual (10.3) or static (9.4). A
6083 // constructor can be invoked for a const, volatile or const
6084 // volatile object. A constructor shall not be declared const,
6085 // volatile, or const volatile (9.3.2).
6086 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00006087 if (!D.isInvalidType())
6088 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6089 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6090 << SourceRange(D.getIdentifierLoc());
6091 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006092 }
John McCalld931b082010-08-26 03:08:43 +00006093 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006094 if (!D.isInvalidType())
6095 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6096 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6097 << SourceRange(D.getIdentifierLoc());
6098 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006099 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006100 }
Mike Stump1eb44332009-09-09 15:08:12 +00006101
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006102 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006103 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00006104 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006105 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6106 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006107 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006108 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6109 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006110 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006111 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6112 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00006113 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006114 }
Mike Stump1eb44332009-09-09 15:08:12 +00006115
Douglas Gregorc938c162011-01-26 05:01:58 +00006116 // C++0x [class.ctor]p4:
6117 // A constructor shall not be declared with a ref-qualifier.
6118 if (FTI.hasRefQualifier()) {
6119 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6120 << FTI.RefQualifierIsLValueRef
6121 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6122 D.setInvalidType();
6123 }
6124
Douglas Gregor42a552f2008-11-05 20:51:48 +00006125 // Rebuild the function type "R" without any type qualifiers (in
6126 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00006127 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00006128 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006129 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6130 return R;
6131
6132 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6133 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006134 EPI.RefQualifier = RQ_None;
6135
Richard Smith07b0fdc2013-03-18 21:12:30 +00006136 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006137}
6138
Douglas Gregor72b505b2008-12-16 21:30:33 +00006139/// CheckConstructor - Checks a fully-formed constructor for
6140/// well-formedness, issuing any diagnostics required. Returns true if
6141/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00006142void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00006143 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00006144 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6145 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00006146 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006147
6148 // C++ [class.copy]p3:
6149 // A declaration of a constructor for a class X is ill-formed if
6150 // its first parameter is of type (optionally cv-qualified) X and
6151 // either there are no other parameters or else all other
6152 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00006153 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006154 ((Constructor->getNumParams() == 1) ||
6155 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00006156 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6157 Constructor->getTemplateSpecializationKind()
6158 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006159 QualType ParamType = Constructor->getParamDecl(0)->getType();
6160 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6161 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00006162 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006163 const char *ConstRef
6164 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6165 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00006166 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006167 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00006168
6169 // FIXME: Rather that making the constructor invalid, we should endeavor
6170 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00006171 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006172 }
6173 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00006174}
6175
John McCall15442822010-08-04 01:04:25 +00006176/// CheckDestructor - Checks a fully-formed destructor definition for
6177/// well-formedness, issuing any diagnostics required. Returns true
6178/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006179bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006180 CXXRecordDecl *RD = Destructor->getParent();
6181
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006182 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006183 SourceLocation Loc;
6184
6185 if (!Destructor->isImplicit())
6186 Loc = Destructor->getLocation();
6187 else
6188 Loc = RD->getLocation();
6189
6190 // If we have a virtual destructor, look up the deallocation function
6191 FunctionDecl *OperatorDelete = 0;
6192 DeclarationName Name =
6193 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006194 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00006195 return true;
John McCall5efd91a2010-07-03 18:33:00 +00006196
Eli Friedman5f2987c2012-02-02 03:46:19 +00006197 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00006198
6199 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00006200 }
Anders Carlsson37909802009-11-30 21:24:50 +00006201
6202 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00006203}
6204
Mike Stump1eb44332009-09-09 15:08:12 +00006205static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006206FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6207 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6208 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006209 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006210}
6211
Douglas Gregor42a552f2008-11-05 20:51:48 +00006212/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6213/// the well-formednes of the destructor declarator @p D with type @p
6214/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006215/// emit diagnostics and set the declarator to invalid. Even if this happens,
6216/// will be updated to reflect a well-formed type for the destructor and
6217/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00006218QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006219 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006220 // C++ [class.dtor]p1:
6221 // [...] A typedef-name that names a class is a class-name
6222 // (7.1.3); however, a typedef-name that names a class shall not
6223 // be used as the identifier in the declarator for a destructor
6224 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006225 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006226 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006227 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006228 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006229 else if (const TemplateSpecializationType *TST =
6230 DeclaratorType->getAs<TemplateSpecializationType>())
6231 if (TST->isTypeAlias())
6232 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6233 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006234
6235 // C++ [class.dtor]p2:
6236 // A destructor is used to destroy objects of its class type. A
6237 // destructor takes no parameters, and no return type can be
6238 // specified for it (not even void). The address of a destructor
6239 // shall not be taken. A destructor shall not be static. A
6240 // destructor can be invoked for a const, volatile or const
6241 // volatile object. A destructor shall not be declared const,
6242 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006243 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006244 if (!D.isInvalidType())
6245 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6246 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006247 << SourceRange(D.getIdentifierLoc())
6248 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6249
John McCalld931b082010-08-26 03:08:43 +00006250 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006251 }
Chris Lattner65401802009-04-25 08:28:21 +00006252 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006253 // Destructors don't have return types, but the parser will
6254 // happily parse something like:
6255 //
6256 // class X {
6257 // float ~X();
6258 // };
6259 //
6260 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006261 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6262 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6263 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006264 }
Mike Stump1eb44332009-09-09 15:08:12 +00006265
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006266 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006267 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006268 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006269 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6270 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006271 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006272 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6273 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006274 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006275 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6276 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006277 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006278 }
6279
Douglas Gregorc938c162011-01-26 05:01:58 +00006280 // C++0x [class.dtor]p2:
6281 // A destructor shall not be declared with a ref-qualifier.
6282 if (FTI.hasRefQualifier()) {
6283 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6284 << FTI.RefQualifierIsLValueRef
6285 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6286 D.setInvalidType();
6287 }
6288
Douglas Gregor42a552f2008-11-05 20:51:48 +00006289 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006290 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006291 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6292
6293 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006294 FTI.freeArgs();
6295 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006296 }
6297
Mike Stump1eb44332009-09-09 15:08:12 +00006298 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006299 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006300 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006301 D.setInvalidType();
6302 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006303
6304 // Rebuild the function type "R" without any type qualifiers or
6305 // parameters (in case any of the errors above fired) and with
6306 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006307 // types.
John McCalle23cf432010-12-14 08:05:40 +00006308 if (!D.isInvalidType())
6309 return R;
6310
Douglas Gregord92ec472010-07-01 05:10:53 +00006311 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006312 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6313 EPI.Variadic = false;
6314 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006315 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006316 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006317}
6318
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006319/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6320/// well-formednes of the conversion function declarator @p D with
6321/// type @p R. If there are any errors in the declarator, this routine
6322/// will emit diagnostics and return true. Otherwise, it will return
6323/// false. Either way, the type @p R will be updated to reflect a
6324/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006325void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006326 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006327 // C++ [class.conv.fct]p1:
6328 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006329 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006330 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006331 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006332 if (!D.isInvalidType())
6333 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006334 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6335 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006336 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006337 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006338 }
John McCalla3f81372010-04-13 00:04:31 +00006339
6340 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6341
Chris Lattner6e475012009-04-25 08:35:12 +00006342 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006343 // Conversion functions don't have return types, but the parser will
6344 // happily parse something like:
6345 //
6346 // class X {
6347 // float operator bool();
6348 // };
6349 //
6350 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006351 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6352 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6353 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006354 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006355 }
6356
John McCalla3f81372010-04-13 00:04:31 +00006357 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6358
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006359 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006360 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006361 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6362
6363 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006364 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006365 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006366 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006367 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006368 D.setInvalidType();
6369 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006370
John McCalla3f81372010-04-13 00:04:31 +00006371 // Diagnose "&operator bool()" and other such nonsense. This
6372 // is actually a gcc extension which we don't support.
6373 if (Proto->getResultType() != ConvType) {
6374 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6375 << Proto->getResultType();
6376 D.setInvalidType();
6377 ConvType = Proto->getResultType();
6378 }
6379
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006380 // C++ [class.conv.fct]p4:
6381 // The conversion-type-id shall not represent a function type nor
6382 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006383 if (ConvType->isArrayType()) {
6384 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6385 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006386 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006387 } else if (ConvType->isFunctionType()) {
6388 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6389 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006390 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006391 }
6392
6393 // Rebuild the function type "R" without any parameters (in case any
6394 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006395 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006396 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006397 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006398
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006399 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006400 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006401 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006402 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006403 diag::warn_cxx98_compat_explicit_conversion_functions :
6404 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006405 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006406}
6407
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006408/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6409/// the declaration of the given C++ conversion function. This routine
6410/// is responsible for recording the conversion function in the C++
6411/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006412Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006413 assert(Conversion && "Expected to receive a conversion function declaration");
6414
Douglas Gregor9d350972008-12-12 08:25:50 +00006415 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006416
6417 // Make sure we aren't redeclaring the conversion function.
6418 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006419
6420 // C++ [class.conv.fct]p1:
6421 // [...] A conversion function is never used to convert a
6422 // (possibly cv-qualified) object to the (possibly cv-qualified)
6423 // same object type (or a reference to it), to a (possibly
6424 // cv-qualified) base class of that type (or a reference to it),
6425 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006426 // FIXME: Suppress this warning if the conversion function ends up being a
6427 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006428 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006429 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006430 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006431 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006432 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6433 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006434 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006435 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006436 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6437 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006438 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006439 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006440 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006441 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006442 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006443 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006444 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006445 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006446 }
6447
Douglas Gregore80622f2010-09-29 04:25:11 +00006448 if (FunctionTemplateDecl *ConversionTemplate
6449 = Conversion->getDescribedFunctionTemplate())
6450 return ConversionTemplate;
6451
John McCalld226f652010-08-21 09:40:31 +00006452 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006453}
6454
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006455//===----------------------------------------------------------------------===//
6456// Namespace Handling
6457//===----------------------------------------------------------------------===//
6458
Richard Smithd1a55a62012-10-04 22:13:39 +00006459/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6460/// reopened.
6461static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6462 SourceLocation Loc,
6463 IdentifierInfo *II, bool *IsInline,
6464 NamespaceDecl *PrevNS) {
6465 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006466
Richard Smithc969e6a2012-10-05 01:46:25 +00006467 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6468 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6469 // inline namespaces, with the intention of bringing names into namespace std.
6470 //
6471 // We support this just well enough to get that case working; this is not
6472 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006473 if (*IsInline && II && II->getName().startswith("__atomic") &&
6474 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006475 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006476 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6477 NS = NS->getPreviousDecl())
6478 NS->setInline(*IsInline);
6479 // Patch up the lookup table for the containing namespace. This isn't really
6480 // correct, but it's good enough for this particular case.
6481 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6482 E = PrevNS->decls_end(); I != E; ++I)
6483 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6484 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6485 return;
6486 }
6487
6488 if (PrevNS->isInline())
6489 // The user probably just forgot the 'inline', so suggest that it
6490 // be added back.
6491 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6492 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6493 else
6494 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6495 << IsInline;
6496
6497 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6498 *IsInline = PrevNS->isInline();
6499}
John McCallea318642010-08-26 09:15:37 +00006500
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006501/// ActOnStartNamespaceDef - This is called at the start of a namespace
6502/// definition.
John McCalld226f652010-08-21 09:40:31 +00006503Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006504 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006505 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006506 SourceLocation IdentLoc,
6507 IdentifierInfo *II,
6508 SourceLocation LBrace,
6509 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006510 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6511 // For anonymous namespace, take the location of the left brace.
6512 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006513 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006514 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006515 bool IsStd = false;
6516 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006517 Scope *DeclRegionScope = NamespcScope->getParent();
6518
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006519 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006520 if (II) {
6521 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006522 // The identifier in an original-namespace-definition shall not
6523 // have been previously defined in the declarative region in
6524 // which the original-namespace-definition appears. The
6525 // identifier in an original-namespace-definition is the name of
6526 // the namespace. Subsequently in that declarative region, it is
6527 // treated as an original-namespace-name.
6528 //
6529 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006530 // look through using directives, just look for any ordinary names.
6531
6532 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006533 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6534 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006535 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006536 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6537 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6538 ++I) {
6539 if ((*I)->getIdentifierNamespace() & IDNS) {
6540 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006541 break;
6542 }
6543 }
6544
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006545 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6546
6547 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006548 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006549 if (IsInline != PrevNS->isInline())
6550 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6551 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006552 } else if (PrevDecl) {
6553 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006554 Diag(Loc, diag::err_redefinition_different_kind)
6555 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006556 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006557 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006558 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006559 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006560 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006561 // This is the first "real" definition of the namespace "std", so update
6562 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006563 PrevNS = getStdNamespace();
6564 IsStd = true;
6565 AddToKnown = !IsInline;
6566 } else {
6567 // We've seen this namespace for the first time.
6568 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006569 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006570 } else {
John McCall9aeed322009-10-01 00:25:31 +00006571 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006572
6573 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006574 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006575 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006576 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006577 } else {
6578 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006579 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006580 }
6581
Richard Smithd1a55a62012-10-04 22:13:39 +00006582 if (PrevNS && IsInline != PrevNS->isInline())
6583 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6584 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006585 }
6586
6587 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6588 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006589 if (IsInvalid)
6590 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006591
6592 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006593
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006594 // FIXME: Should we be merging attributes?
6595 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006596 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006597
6598 if (IsStd)
6599 StdNamespace = Namespc;
6600 if (AddToKnown)
6601 KnownNamespaces[Namespc] = false;
6602
6603 if (II) {
6604 PushOnScopeChains(Namespc, DeclRegionScope);
6605 } else {
6606 // Link the anonymous namespace into its parent.
6607 DeclContext *Parent = CurContext->getRedeclContext();
6608 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6609 TU->setAnonymousNamespace(Namespc);
6610 } else {
6611 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006612 }
John McCall9aeed322009-10-01 00:25:31 +00006613
Douglas Gregora4181472010-03-24 00:46:35 +00006614 CurContext->addDecl(Namespc);
6615
John McCall9aeed322009-10-01 00:25:31 +00006616 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6617 // behaves as if it were replaced by
6618 // namespace unique { /* empty body */ }
6619 // using namespace unique;
6620 // namespace unique { namespace-body }
6621 // where all occurrences of 'unique' in a translation unit are
6622 // replaced by the same identifier and this identifier differs
6623 // from all other identifiers in the entire program.
6624
6625 // We just create the namespace with an empty name and then add an
6626 // implicit using declaration, just like the standard suggests.
6627 //
6628 // CodeGen enforces the "universally unique" aspect by giving all
6629 // declarations semantically contained within an anonymous
6630 // namespace internal linkage.
6631
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006632 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006633 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006634 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006635 /* 'using' */ LBrace,
6636 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006637 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006638 /* identifier */ SourceLocation(),
6639 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006640 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006641 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006642 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006643 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006644 }
6645
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006646 ActOnDocumentableDecl(Namespc);
6647
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006648 // Although we could have an invalid decl (i.e. the namespace name is a
6649 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006650 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6651 // for the namespace has the declarations that showed up in that particular
6652 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006653 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006654 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006655}
6656
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006657/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6658/// is a namespace alias, returns the namespace it points to.
6659static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6660 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6661 return AD->getNamespace();
6662 return dyn_cast_or_null<NamespaceDecl>(D);
6663}
6664
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006665/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6666/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006667void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006668 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6669 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006670 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006671 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006672 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006673 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006674}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006675
John McCall384aff82010-08-25 07:42:41 +00006676CXXRecordDecl *Sema::getStdBadAlloc() const {
6677 return cast_or_null<CXXRecordDecl>(
6678 StdBadAlloc.get(Context.getExternalSource()));
6679}
6680
6681NamespaceDecl *Sema::getStdNamespace() const {
6682 return cast_or_null<NamespaceDecl>(
6683 StdNamespace.get(Context.getExternalSource()));
6684}
6685
Douglas Gregor66992202010-06-29 17:53:46 +00006686/// \brief Retrieve the special "std" namespace, which may require us to
6687/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006688NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006689 if (!StdNamespace) {
6690 // The "std" namespace has not yet been defined, so build one implicitly.
6691 StdNamespace = NamespaceDecl::Create(Context,
6692 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006693 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006694 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006695 &PP.getIdentifierTable().get("std"),
6696 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006697 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006698 }
6699
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006700 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006701}
6702
Sebastian Redl395e04d2012-01-17 22:49:33 +00006703bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006704 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006705 "Looking for std::initializer_list outside of C++.");
6706
6707 // We're looking for implicit instantiations of
6708 // template <typename E> class std::initializer_list.
6709
6710 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6711 return false;
6712
Sebastian Redl84760e32012-01-17 22:49:58 +00006713 ClassTemplateDecl *Template = 0;
6714 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006715
Sebastian Redl84760e32012-01-17 22:49:58 +00006716 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006717
Sebastian Redl84760e32012-01-17 22:49:58 +00006718 ClassTemplateSpecializationDecl *Specialization =
6719 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6720 if (!Specialization)
6721 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006722
Sebastian Redl84760e32012-01-17 22:49:58 +00006723 Template = Specialization->getSpecializedTemplate();
6724 Arguments = Specialization->getTemplateArgs().data();
6725 } else if (const TemplateSpecializationType *TST =
6726 Ty->getAs<TemplateSpecializationType>()) {
6727 Template = dyn_cast_or_null<ClassTemplateDecl>(
6728 TST->getTemplateName().getAsTemplateDecl());
6729 Arguments = TST->getArgs();
6730 }
6731 if (!Template)
6732 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006733
6734 if (!StdInitializerList) {
6735 // Haven't recognized std::initializer_list yet, maybe this is it.
6736 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6737 if (TemplateClass->getIdentifier() !=
6738 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006739 !getStdNamespace()->InEnclosingNamespaceSetOf(
6740 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006741 return false;
6742 // This is a template called std::initializer_list, but is it the right
6743 // template?
6744 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006745 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006746 return false;
6747 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6748 return false;
6749
6750 // It's the right template.
6751 StdInitializerList = Template;
6752 }
6753
6754 if (Template != StdInitializerList)
6755 return false;
6756
6757 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006758 if (Element)
6759 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006760 return true;
6761}
6762
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006763static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6764 NamespaceDecl *Std = S.getStdNamespace();
6765 if (!Std) {
6766 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6767 return 0;
6768 }
6769
6770 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6771 Loc, Sema::LookupOrdinaryName);
6772 if (!S.LookupQualifiedName(Result, Std)) {
6773 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6774 return 0;
6775 }
6776 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6777 if (!Template) {
6778 Result.suppressDiagnostics();
6779 // We found something weird. Complain about the first thing we found.
6780 NamedDecl *Found = *Result.begin();
6781 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6782 return 0;
6783 }
6784
6785 // We found some template called std::initializer_list. Now verify that it's
6786 // correct.
6787 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006788 if (Params->getMinRequiredArguments() != 1 ||
6789 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006790 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6791 return 0;
6792 }
6793
6794 return Template;
6795}
6796
6797QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6798 if (!StdInitializerList) {
6799 StdInitializerList = LookupStdInitializerList(*this, Loc);
6800 if (!StdInitializerList)
6801 return QualType();
6802 }
6803
6804 TemplateArgumentListInfo Args(Loc, Loc);
6805 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6806 Context.getTrivialTypeSourceInfo(Element,
6807 Loc)));
6808 return Context.getCanonicalType(
6809 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6810}
6811
Sebastian Redl98d36062012-01-17 22:50:14 +00006812bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6813 // C++ [dcl.init.list]p2:
6814 // A constructor is an initializer-list constructor if its first parameter
6815 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6816 // std::initializer_list<E> for some type E, and either there are no other
6817 // parameters or else all other parameters have default arguments.
6818 if (Ctor->getNumParams() < 1 ||
6819 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6820 return false;
6821
6822 QualType ArgType = Ctor->getParamDecl(0)->getType();
6823 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6824 ArgType = RT->getPointeeType().getUnqualifiedType();
6825
6826 return isStdInitializerList(ArgType, 0);
6827}
6828
Douglas Gregor9172aa62011-03-26 22:25:30 +00006829/// \brief Determine whether a using statement is in a context where it will be
6830/// apply in all contexts.
6831static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6832 switch (CurContext->getDeclKind()) {
6833 case Decl::TranslationUnit:
6834 return true;
6835 case Decl::LinkageSpec:
6836 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6837 default:
6838 return false;
6839 }
6840}
6841
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006842namespace {
6843
6844// Callback to only accept typo corrections that are namespaces.
6845class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006846public:
6847 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6848 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006849 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006850 return false;
6851 }
6852};
6853
6854}
6855
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006856static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6857 CXXScopeSpec &SS,
6858 SourceLocation IdentLoc,
6859 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006860 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006861 R.clear();
6862 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006863 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006864 Validator)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006865 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00006866 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6867 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006868 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00006869 S.diagnoseTypo(Corrected,
6870 S.PDiag(diag::err_using_directive_member_suggest)
6871 << Ident << DC << DroppedSpecifier << SS.getRange(),
6872 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006873 } else {
Richard Smith2d670972013-08-17 00:46:16 +00006874 S.diagnoseTypo(Corrected,
6875 S.PDiag(diag::err_using_directive_suggest) << Ident,
6876 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006877 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006878 R.addDecl(Corrected.getCorrectionDecl());
6879 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006880 }
6881 return false;
6882}
6883
John McCalld226f652010-08-21 09:40:31 +00006884Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006885 SourceLocation UsingLoc,
6886 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006887 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006888 SourceLocation IdentLoc,
6889 IdentifierInfo *NamespcName,
6890 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006891 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6892 assert(NamespcName && "Invalid NamespcName.");
6893 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006894
6895 // This can only happen along a recovery path.
6896 while (S->getFlags() & Scope::TemplateParamScope)
6897 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006898 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006899
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006900 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006901 NestedNameSpecifier *Qualifier = 0;
6902 if (SS.isSet())
6903 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6904
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006905 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006906 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6907 LookupParsedName(R, S, &SS);
6908 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006909 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006910
Douglas Gregor66992202010-06-29 17:53:46 +00006911 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006912 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006913 // Allow "using namespace std;" or "using namespace ::std;" even if
6914 // "std" hasn't been defined yet, for GCC compatibility.
6915 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6916 NamespcName->isStr("std")) {
6917 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006918 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006919 R.resolveKind();
6920 }
6921 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006922 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006923 }
6924
John McCallf36e02d2009-10-09 21:13:30 +00006925 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006926 NamedDecl *Named = R.getFoundDecl();
6927 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6928 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006929 // C++ [namespace.udir]p1:
6930 // A using-directive specifies that the names in the nominated
6931 // namespace can be used in the scope in which the
6932 // using-directive appears after the using-directive. During
6933 // unqualified name lookup (3.4.1), the names appear as if they
6934 // were declared in the nearest enclosing namespace which
6935 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006936 // namespace. [Note: in this context, "contains" means "contains
6937 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006938
6939 // Find enclosing context containing both using-directive and
6940 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006941 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006942 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6943 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6944 CommonAncestor = CommonAncestor->getParent();
6945
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006946 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006947 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006948 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006949
Douglas Gregor9172aa62011-03-26 22:25:30 +00006950 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00006951 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006952 Diag(IdentLoc, diag::warn_using_directive_in_header);
6953 }
6954
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006955 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006956 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006957 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006958 }
6959
Richard Smith6b3d3e52013-02-20 19:22:51 +00006960 if (UDir)
6961 ProcessDeclAttributeList(S, UDir, AttrList);
6962
John McCalld226f652010-08-21 09:40:31 +00006963 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006964}
6965
6966void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006967 // If the scope has an associated entity and the using directive is at
6968 // namespace or translation unit scope, add the UsingDirectiveDecl into
6969 // its lookup structure so qualified name lookup can find it.
Ted Kremenekf0d58612013-10-08 17:08:03 +00006970 DeclContext *Ctx = S->getEntity();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006971 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006972 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006973 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006974 // Otherwise, it is at block sope. The using-directives will affect lookup
6975 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006976 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006977}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006978
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006979
John McCalld226f652010-08-21 09:40:31 +00006980Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006981 AccessSpecifier AS,
6982 bool HasUsingKeyword,
6983 SourceLocation UsingLoc,
6984 CXXScopeSpec &SS,
6985 UnqualifiedId &Name,
6986 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006987 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00006988 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006989 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006990
Douglas Gregor12c118a2009-11-04 16:30:06 +00006991 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006992 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006993 case UnqualifiedId::IK_Identifier:
6994 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006995 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006996 case UnqualifiedId::IK_ConversionFunctionId:
6997 break;
6998
6999 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00007000 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00007001 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00007002 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00007003 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00007004 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00007005 diag::err_using_decl_constructor)
7006 << SS.getRange();
7007
Richard Smith80ad52f2013-01-02 11:42:31 +00007008 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00007009
John McCalld226f652010-08-21 09:40:31 +00007010 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00007011
7012 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00007013 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00007014 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007015 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00007016
7017 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00007018 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00007019 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00007020 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00007021 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007022
7023 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7024 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00007025 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00007026 return 0;
John McCall604e7f12009-12-08 07:46:18 +00007027
Richard Smith07b0fdc2013-03-18 21:12:30 +00007028 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00007029 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00007030 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00007031 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7032 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00007033 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00007034 }
7035
Douglas Gregor56c04582010-12-16 00:46:58 +00007036 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7037 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7038 return 0;
7039
John McCall9488ea12009-11-17 05:59:44 +00007040 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007041 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007042 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007043 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00007044 if (UD)
7045 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00007046
John McCalld226f652010-08-21 09:40:31 +00007047 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00007048}
7049
Douglas Gregor09acc982010-07-07 23:08:52 +00007050/// \brief Determine whether a using declaration considers the given
7051/// declarations as "equivalent", e.g., if they are redeclarations of
7052/// the same entity or are both typedefs of the same type.
7053static bool
7054IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
7055 bool &SuppressRedeclaration) {
7056 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
7057 SuppressRedeclaration = false;
7058 return true;
7059 }
7060
Richard Smith162e1c12011-04-15 14:24:37 +00007061 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7062 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00007063 SuppressRedeclaration = true;
7064 return Context.hasSameType(TD1->getUnderlyingType(),
7065 TD2->getUnderlyingType());
7066 }
7067
7068 return false;
7069}
7070
7071
John McCall9f54ad42009-12-10 09:41:52 +00007072/// Determines whether to create a using shadow decl for a particular
7073/// decl, given the set of decls existing prior to this using lookup.
7074bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7075 const LookupResult &Previous) {
7076 // Diagnose finding a decl which is not from a base class of the
7077 // current class. We do this now because there are cases where this
7078 // function will silently decide not to build a shadow decl, which
7079 // will pre-empt further diagnostics.
7080 //
7081 // We don't need to do this in C++0x because we do the check once on
7082 // the qualifier.
7083 //
7084 // FIXME: diagnose the following if we care enough:
7085 // struct A { int foo; };
7086 // struct B : A { using A::foo; };
7087 // template <class T> struct C : A {};
7088 // template <class T> struct D : C<T> { using B::foo; } // <---
7089 // This is invalid (during instantiation) in C++03 because B::foo
7090 // resolves to the using decl in B, which is not a base class of D<T>.
7091 // We can't diagnose it immediately because C<T> is an unknown
7092 // specialization. The UsingShadowDecl in D<T> then points directly
7093 // to A::foo, which will look well-formed when we instantiate.
7094 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00007095 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00007096 DeclContext *OrigDC = Orig->getDeclContext();
7097
7098 // Handle enums and anonymous structs.
7099 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7100 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7101 while (OrigRec->isAnonymousStructOrUnion())
7102 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7103
7104 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7105 if (OrigDC == CurContext) {
7106 Diag(Using->getLocation(),
7107 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007108 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007109 Diag(Orig->getLocation(), diag::note_using_decl_target);
7110 return true;
7111 }
7112
Douglas Gregordc355712011-02-25 00:36:19 +00007113 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00007114 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007115 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00007116 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00007117 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007118 Diag(Orig->getLocation(), diag::note_using_decl_target);
7119 return true;
7120 }
7121 }
7122
7123 if (Previous.empty()) return false;
7124
7125 NamedDecl *Target = Orig;
7126 if (isa<UsingShadowDecl>(Target))
7127 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7128
John McCalld7533ec2009-12-11 02:33:26 +00007129 // If the target happens to be one of the previous declarations, we
7130 // don't have a conflict.
7131 //
7132 // FIXME: but we might be increasing its access, in which case we
7133 // should redeclare it.
7134 NamedDecl *NonTag = 0, *Tag = 0;
7135 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7136 I != E; ++I) {
7137 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00007138 bool Result;
7139 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
7140 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00007141
7142 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7143 }
7144
John McCall9f54ad42009-12-10 09:41:52 +00007145 if (Target->isFunctionOrFunctionTemplate()) {
7146 FunctionDecl *FD;
7147 if (isa<FunctionTemplateDecl>(Target))
7148 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7149 else
7150 FD = cast<FunctionDecl>(Target);
7151
7152 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00007153 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00007154 case Ovl_Overload:
7155 return false;
7156
7157 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00007158 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007159 break;
7160
7161 // We found a decl with the exact signature.
7162 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007163 // If we're in a record, we want to hide the target, so we
7164 // return true (without a diagnostic) to tell the caller not to
7165 // build a shadow decl.
7166 if (CurContext->isRecord())
7167 return true;
7168
7169 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00007170 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007171 break;
7172 }
7173
7174 Diag(Target->getLocation(), diag::note_using_decl_target);
7175 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7176 return true;
7177 }
7178
7179 // Target is not a function.
7180
John McCall9f54ad42009-12-10 09:41:52 +00007181 if (isa<TagDecl>(Target)) {
7182 // No conflict between a tag and a non-tag.
7183 if (!Tag) return false;
7184
John McCall41ce66f2009-12-10 19:51:03 +00007185 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007186 Diag(Target->getLocation(), diag::note_using_decl_target);
7187 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7188 return true;
7189 }
7190
7191 // No conflict between a tag and a non-tag.
7192 if (!NonTag) return false;
7193
John McCall41ce66f2009-12-10 19:51:03 +00007194 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007195 Diag(Target->getLocation(), diag::note_using_decl_target);
7196 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7197 return true;
7198}
7199
John McCall9488ea12009-11-17 05:59:44 +00007200/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00007201UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00007202 UsingDecl *UD,
7203 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00007204
7205 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00007206 NamedDecl *Target = Orig;
7207 if (isa<UsingShadowDecl>(Target)) {
7208 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7209 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00007210 }
7211
7212 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00007213 = UsingShadowDecl::Create(Context, CurContext,
7214 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00007215 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00007216
7217 Shadow->setAccess(UD->getAccess());
7218 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7219 Shadow->setInvalidDecl();
7220
John McCall9488ea12009-11-17 05:59:44 +00007221 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007222 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007223 else
John McCall604e7f12009-12-08 07:46:18 +00007224 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007225
John McCall604e7f12009-12-08 07:46:18 +00007226
John McCall9f54ad42009-12-10 09:41:52 +00007227 return Shadow;
7228}
John McCall604e7f12009-12-08 07:46:18 +00007229
John McCall9f54ad42009-12-10 09:41:52 +00007230/// Hides a using shadow declaration. This is required by the current
7231/// using-decl implementation when a resolvable using declaration in a
7232/// class is followed by a declaration which would hide or override
7233/// one or more of the using decl's targets; for example:
7234///
7235/// struct Base { void foo(int); };
7236/// struct Derived : Base {
7237/// using Base::foo;
7238/// void foo(int);
7239/// };
7240///
7241/// The governing language is C++03 [namespace.udecl]p12:
7242///
7243/// When a using-declaration brings names from a base class into a
7244/// derived class scope, member functions in the derived class
7245/// override and/or hide member functions with the same name and
7246/// parameter types in a base class (rather than conflicting).
7247///
7248/// There are two ways to implement this:
7249/// (1) optimistically create shadow decls when they're not hidden
7250/// by existing declarations, or
7251/// (2) don't create any shadow decls (or at least don't make them
7252/// visible) until we've fully parsed/instantiated the class.
7253/// The problem with (1) is that we might have to retroactively remove
7254/// a shadow decl, which requires several O(n) operations because the
7255/// decl structures are (very reasonably) not designed for removal.
7256/// (2) avoids this but is very fiddly and phase-dependent.
7257void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007258 if (Shadow->getDeclName().getNameKind() ==
7259 DeclarationName::CXXConversionFunctionName)
7260 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7261
John McCall9f54ad42009-12-10 09:41:52 +00007262 // Remove it from the DeclContext...
7263 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007264
John McCall9f54ad42009-12-10 09:41:52 +00007265 // ...and the scope, if applicable...
7266 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007267 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007268 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007269 }
7270
John McCall9f54ad42009-12-10 09:41:52 +00007271 // ...and the using decl.
7272 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7273
7274 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007275 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007276}
7277
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007278namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007279class UsingValidatorCCC : public CorrectionCandidateCallback {
7280public:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007281 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation)
7282 : HasTypenameKeyword(HasTypenameKeyword),
7283 IsInstantiation(IsInstantiation) {}
7284
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007285 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7286 NamedDecl *ND = Candidate.getCorrectionDecl();
7287
7288 // Keywords are not valid here.
7289 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007290 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007291
7292 // Completely unqualified names are invalid for a 'using' declaration.
7293 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7294 return false;
7295
7296 if (isa<TypeDecl>(ND))
7297 return HasTypenameKeyword || !IsInstantiation;
7298
7299 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007300 }
7301
7302private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007303 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007304 bool IsInstantiation;
7305};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007306} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007307
John McCall7ba107a2009-11-18 02:36:19 +00007308/// Builds a using declaration.
7309///
7310/// \param IsInstantiation - Whether this call arises from an
7311/// instantiation of an unresolved using declaration. We treat
7312/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007313NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7314 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007315 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007316 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007317 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007318 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007319 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007320 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007321 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007322 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007323 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007324
Anders Carlsson550b14b2009-08-28 05:49:21 +00007325 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007326
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007327 if (SS.isEmpty()) {
7328 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007329 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007330 }
Mike Stump1eb44332009-09-09 15:08:12 +00007331
John McCall9f54ad42009-12-10 09:41:52 +00007332 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007333 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007334 ForRedeclaration);
7335 Previous.setHideTags(false);
7336 if (S) {
7337 LookupName(Previous, S);
7338
7339 // It is really dumb that we have to do this.
7340 LookupResult::Filter F = Previous.makeFilter();
7341 while (F.hasNext()) {
7342 NamedDecl *D = F.next();
7343 if (!isDeclInScope(D, CurContext, S))
7344 F.erase();
7345 }
7346 F.done();
7347 } else {
7348 assert(IsInstantiation && "no scope in non-instantiation");
7349 assert(CurContext->isRecord() && "scope not record in instantiation");
7350 LookupQualifiedName(Previous, CurContext);
7351 }
7352
John McCall9f54ad42009-12-10 09:41:52 +00007353 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007354 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7355 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007356 return 0;
7357
7358 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007359 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7360 return 0;
7361
John McCallaf8e6ed2009-11-12 03:15:40 +00007362 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007363 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007364 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007365 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007366 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007367 // FIXME: not all declaration name kinds are legal here
7368 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7369 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007370 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007371 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007372 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007373 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7374 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007375 }
John McCalled976492009-12-04 22:46:56 +00007376 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007377 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007378 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007379 }
John McCalled976492009-12-04 22:46:56 +00007380 D->setAccess(AS);
7381 CurContext->addDecl(D);
7382
7383 if (!LookupContext) return D;
7384 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007385
John McCall77bb1aa2010-05-01 00:40:08 +00007386 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007387 UD->setInvalidDecl();
7388 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007389 }
7390
Richard Smithc5a89a12012-04-02 01:30:27 +00007391 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007392 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007393 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007394 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007395 return UD;
7396 }
7397
7398 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007399
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007400 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007401
John McCall604e7f12009-12-08 07:46:18 +00007402 // Unlike most lookups, we don't always want to hide tag
7403 // declarations: tag names are visible through the using declaration
7404 // even if hidden by ordinary names, *except* in a dependent context
7405 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007406 if (!IsInstantiation)
7407 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007408
John McCallb9abd8722012-04-07 03:04:20 +00007409 // For the purposes of this lookup, we have a base object type
7410 // equal to that of the current context.
7411 if (CurContext->isRecord()) {
7412 R.setBaseObjectType(
7413 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7414 }
7415
John McCalla24dc2e2009-11-17 02:14:36 +00007416 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007417
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007418 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007419 if (R.empty()) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007420 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation);
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007421 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7422 R.getLookupKind(), S, &SS, CCC)){
7423 // We reject any correction for which ND would be NULL.
7424 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007425 R.setLookupName(Corrected.getCorrection());
7426 R.addDecl(ND);
Richard Smith2d670972013-08-17 00:46:16 +00007427 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007428 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007429 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7430 << NameInfo.getName() << LookupContext << 0
7431 << SS.getRange());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007432 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007433 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007434 << NameInfo.getName() << LookupContext << SS.getRange();
7435 UD->setInvalidDecl();
7436 return UD;
7437 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007438 }
7439
John McCalled976492009-12-04 22:46:56 +00007440 if (R.isAmbiguous()) {
7441 UD->setInvalidDecl();
7442 return UD;
7443 }
Mike Stump1eb44332009-09-09 15:08:12 +00007444
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007445 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007446 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007447 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007448 Diag(IdentLoc, diag::err_using_typename_non_type);
7449 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7450 Diag((*I)->getUnderlyingDecl()->getLocation(),
7451 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 }
7455 } else {
7456 // If we asked for a non-typename and we got a type, error out,
7457 // but only if this is an instantiation of an unresolved using
7458 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007459 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007460 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7461 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007462 UD->setInvalidDecl();
7463 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007464 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007465 }
7466
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007467 // C++0x N2914 [namespace.udecl]p6:
7468 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007469 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007470 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7471 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007472 UD->setInvalidDecl();
7473 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007474 }
Mike Stump1eb44332009-09-09 15:08:12 +00007475
John McCall9f54ad42009-12-10 09:41:52 +00007476 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7477 if (!CheckUsingShadowDecl(UD, *I, Previous))
7478 BuildUsingShadowDecl(S, UD, *I);
7479 }
John McCall9488ea12009-11-17 05:59:44 +00007480
7481 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007482}
7483
Sebastian Redlf677ea32011-02-05 19:23:19 +00007484/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007485bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007486 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007487
Douglas Gregordc355712011-02-25 00:36:19 +00007488 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007489 assert(SourceType &&
7490 "Using decl naming constructor doesn't have type in scope spec.");
7491 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7492
7493 // Check whether the named type is a direct base class.
7494 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7495 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7496 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7497 BaseIt != BaseE; ++BaseIt) {
7498 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7499 if (CanonicalSourceType == BaseType)
7500 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007501 if (BaseIt->getType()->isDependentType())
7502 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007503 }
7504
7505 if (BaseIt == BaseE) {
7506 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007507 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007508 diag::err_using_decl_constructor_not_in_direct_base)
7509 << UD->getNameInfo().getSourceRange()
7510 << QualType(SourceType, 0) << TargetClass;
7511 return true;
7512 }
7513
Richard Smithc5a89a12012-04-02 01:30:27 +00007514 if (!CurContext->isDependentContext())
7515 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007516
7517 return false;
7518}
7519
John McCall9f54ad42009-12-10 09:41:52 +00007520/// Checks that the given using declaration is not an invalid
7521/// redeclaration. Note that this is checking only for the using decl
7522/// itself, not for any ill-formedness among the UsingShadowDecls.
7523bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007524 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007525 const CXXScopeSpec &SS,
7526 SourceLocation NameLoc,
7527 const LookupResult &Prev) {
7528 // C++03 [namespace.udecl]p8:
7529 // C++0x [namespace.udecl]p10:
7530 // A using-declaration is a declaration and can therefore be used
7531 // repeatedly where (and only where) multiple declarations are
7532 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007533 //
John McCall8a726212010-11-29 18:01:58 +00007534 // That's in non-member contexts.
7535 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007536 return false;
7537
7538 NestedNameSpecifier *Qual
7539 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7540
7541 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7542 NamedDecl *D = *I;
7543
7544 bool DTypename;
7545 NestedNameSpecifier *DQual;
7546 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007547 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007548 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007549 } else if (UnresolvedUsingValueDecl *UD
7550 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7551 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007552 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007553 } else if (UnresolvedUsingTypenameDecl *UD
7554 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7555 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007556 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007557 } else continue;
7558
7559 // using decls differ if one says 'typename' and the other doesn't.
7560 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007561 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007562
7563 // using decls differ if they name different scopes (but note that
7564 // template instantiation can cause this check to trigger when it
7565 // didn't before instantiation).
7566 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7567 Context.getCanonicalNestedNameSpecifier(DQual))
7568 continue;
7569
7570 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007571 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007572 return true;
7573 }
7574
7575 return false;
7576}
7577
John McCall604e7f12009-12-08 07:46:18 +00007578
John McCalled976492009-12-04 22:46:56 +00007579/// Checks that the given nested-name qualifier used in a using decl
7580/// in the current context is appropriately related to the current
7581/// scope. If an error is found, diagnoses it and returns true.
7582bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7583 const CXXScopeSpec &SS,
7584 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007585 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007586
John McCall604e7f12009-12-08 07:46:18 +00007587 if (!CurContext->isRecord()) {
7588 // C++03 [namespace.udecl]p3:
7589 // C++0x [namespace.udecl]p8:
7590 // A using-declaration for a class member shall be a member-declaration.
7591
7592 // If we weren't able to compute a valid scope, it must be a
7593 // dependent class scope.
7594 if (!NamedContext || NamedContext->isRecord()) {
7595 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7596 << SS.getRange();
7597 return true;
7598 }
7599
7600 // Otherwise, everything is known to be fine.
7601 return false;
7602 }
7603
7604 // The current scope is a record.
7605
7606 // If the named context is dependent, we can't decide much.
7607 if (!NamedContext) {
7608 // FIXME: in C++0x, we can diagnose if we can prove that the
7609 // nested-name-specifier does not refer to a base class, which is
7610 // still possible in some cases.
7611
7612 // Otherwise we have to conservatively report that things might be
7613 // okay.
7614 return false;
7615 }
7616
7617 if (!NamedContext->isRecord()) {
7618 // Ideally this would point at the last name in the specifier,
7619 // but we don't have that level of source info.
7620 Diag(SS.getRange().getBegin(),
7621 diag::err_using_decl_nested_name_specifier_is_not_class)
7622 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7623 return true;
7624 }
7625
Douglas Gregor6fb07292010-12-21 07:41:49 +00007626 if (!NamedContext->isDependentContext() &&
7627 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7628 return true;
7629
Richard Smith80ad52f2013-01-02 11:42:31 +00007630 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007631 // C++0x [namespace.udecl]p3:
7632 // In a using-declaration used as a member-declaration, the
7633 // nested-name-specifier shall name a base class of the class
7634 // being defined.
7635
7636 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7637 cast<CXXRecordDecl>(NamedContext))) {
7638 if (CurContext == NamedContext) {
7639 Diag(NameLoc,
7640 diag::err_using_decl_nested_name_specifier_is_current_class)
7641 << SS.getRange();
7642 return true;
7643 }
7644
7645 Diag(SS.getRange().getBegin(),
7646 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7647 << (NestedNameSpecifier*) SS.getScopeRep()
7648 << cast<CXXRecordDecl>(CurContext)
7649 << SS.getRange();
7650 return true;
7651 }
7652
7653 return false;
7654 }
7655
7656 // C++03 [namespace.udecl]p4:
7657 // A using-declaration used as a member-declaration shall refer
7658 // to a member of a base class of the class being defined [etc.].
7659
7660 // Salient point: SS doesn't have to name a base class as long as
7661 // lookup only finds members from base classes. Therefore we can
7662 // diagnose here only if we can prove that that can't happen,
7663 // i.e. if the class hierarchies provably don't intersect.
7664
7665 // TODO: it would be nice if "definitely valid" results were cached
7666 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7667 // need to be repeated.
7668
7669 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007670 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007671
7672 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7673 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7674 Data->Bases.insert(Base);
7675 return true;
7676 }
7677
7678 bool hasDependentBases(const CXXRecordDecl *Class) {
7679 return !Class->forallBases(collect, this);
7680 }
7681
7682 /// Returns true if the base is dependent or is one of the
7683 /// accumulated base classes.
7684 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7685 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7686 return !Data->Bases.count(Base);
7687 }
7688
7689 bool mightShareBases(const CXXRecordDecl *Class) {
7690 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7691 }
7692 };
7693
7694 UserData Data;
7695
7696 // Returns false if we find a dependent base.
7697 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7698 return false;
7699
7700 // Returns false if the class has a dependent base or if it or one
7701 // of its bases is present in the base set of the current context.
7702 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7703 return false;
7704
7705 Diag(SS.getRange().getBegin(),
7706 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7707 << (NestedNameSpecifier*) SS.getScopeRep()
7708 << cast<CXXRecordDecl>(CurContext)
7709 << SS.getRange();
7710
7711 return true;
John McCalled976492009-12-04 22:46:56 +00007712}
7713
Richard Smith162e1c12011-04-15 14:24:37 +00007714Decl *Sema::ActOnAliasDeclaration(Scope *S,
7715 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007716 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007717 SourceLocation UsingLoc,
7718 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007719 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007720 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007721 // Skip up to the relevant declaration scope.
7722 while (S->getFlags() & Scope::TemplateParamScope)
7723 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007724 assert((S->getFlags() & Scope::DeclScope) &&
7725 "got alias-declaration outside of declaration scope");
7726
7727 if (Type.isInvalid())
7728 return 0;
7729
7730 bool Invalid = false;
7731 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7732 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007733 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007734
7735 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7736 return 0;
7737
7738 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007739 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007740 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007741 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7742 TInfo->getTypeLoc().getBeginLoc());
7743 }
Richard Smith162e1c12011-04-15 14:24:37 +00007744
7745 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7746 LookupName(Previous, S);
7747
7748 // Warn about shadowing the name of a template parameter.
7749 if (Previous.isSingleResult() &&
7750 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007751 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007752 Previous.clear();
7753 }
7754
7755 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7756 "name in alias declaration must be an identifier");
7757 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7758 Name.StartLocation,
7759 Name.Identifier, TInfo);
7760
7761 NewTD->setAccess(AS);
7762
7763 if (Invalid)
7764 NewTD->setInvalidDecl();
7765
Richard Smith6b3d3e52013-02-20 19:22:51 +00007766 ProcessDeclAttributeList(S, NewTD, AttrList);
7767
Richard Smith3e4c6c42011-05-05 21:57:07 +00007768 CheckTypedefForVariablyModifiedType(S, NewTD);
7769 Invalid |= NewTD->isInvalidDecl();
7770
Richard Smith162e1c12011-04-15 14:24:37 +00007771 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007772
7773 NamedDecl *NewND;
7774 if (TemplateParamLists.size()) {
7775 TypeAliasTemplateDecl *OldDecl = 0;
7776 TemplateParameterList *OldTemplateParams = 0;
7777
7778 if (TemplateParamLists.size() != 1) {
7779 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007780 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7781 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007782 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007783 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007784
7785 // Only consider previous declarations in the same scope.
7786 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7787 /*ExplicitInstantiationOrSpecialization*/false);
7788 if (!Previous.empty()) {
7789 Redeclaration = true;
7790
7791 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7792 if (!OldDecl && !Invalid) {
7793 Diag(UsingLoc, diag::err_redefinition_different_kind)
7794 << Name.Identifier;
7795
7796 NamedDecl *OldD = Previous.getRepresentativeDecl();
7797 if (OldD->getLocation().isValid())
7798 Diag(OldD->getLocation(), diag::note_previous_definition);
7799
7800 Invalid = true;
7801 }
7802
7803 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7804 if (TemplateParameterListsAreEqual(TemplateParams,
7805 OldDecl->getTemplateParameters(),
7806 /*Complain=*/true,
7807 TPL_TemplateMatch))
7808 OldTemplateParams = OldDecl->getTemplateParameters();
7809 else
7810 Invalid = true;
7811
7812 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7813 if (!Invalid &&
7814 !Context.hasSameType(OldTD->getUnderlyingType(),
7815 NewTD->getUnderlyingType())) {
7816 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7817 // but we can't reasonably accept it.
7818 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7819 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7820 if (OldTD->getLocation().isValid())
7821 Diag(OldTD->getLocation(), diag::note_previous_definition);
7822 Invalid = true;
7823 }
7824 }
7825 }
7826
7827 // Merge any previous default template arguments into our parameters,
7828 // and check the parameter list.
7829 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7830 TPC_TypeAliasTemplate))
7831 return 0;
7832
7833 TypeAliasTemplateDecl *NewDecl =
7834 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7835 Name.Identifier, TemplateParams,
7836 NewTD);
7837
7838 NewDecl->setAccess(AS);
7839
7840 if (Invalid)
7841 NewDecl->setInvalidDecl();
7842 else if (OldDecl)
7843 NewDecl->setPreviousDeclaration(OldDecl);
7844
7845 NewND = NewDecl;
7846 } else {
7847 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7848 NewND = NewTD;
7849 }
Richard Smith162e1c12011-04-15 14:24:37 +00007850
7851 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007852 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007853
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007854 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007855 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007856}
7857
John McCalld226f652010-08-21 09:40:31 +00007858Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007859 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007860 SourceLocation AliasLoc,
7861 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007862 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007863 SourceLocation IdentLoc,
7864 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007865
Anders Carlsson81c85c42009-03-28 23:53:49 +00007866 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007867 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7868 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007869
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007870 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007871 NamedDecl *PrevDecl
7872 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7873 ForRedeclaration);
7874 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7875 PrevDecl = 0;
7876
7877 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007878 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007879 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007880 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007881 // FIXME: At some point, we'll want to create the (redundant)
7882 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007883 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007884 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007885 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007886 }
Mike Stump1eb44332009-09-09 15:08:12 +00007887
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007888 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7889 diag::err_redefinition_different_kind;
7890 Diag(AliasLoc, DiagID) << Alias;
7891 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007892 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007893 }
7894
John McCalla24dc2e2009-11-17 02:14:36 +00007895 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007896 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007897
John McCallf36e02d2009-10-09 21:13:30 +00007898 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007899 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007900 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007901 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007902 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007903 }
Mike Stump1eb44332009-09-09 15:08:12 +00007904
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007905 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007906 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007907 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007908 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007909
John McCall3dbd3d52010-02-16 06:53:13 +00007910 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007911 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007912}
7913
Sean Hunt001cad92011-05-10 00:49:42 +00007914Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007915Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7916 CXXMethodDecl *MD) {
7917 CXXRecordDecl *ClassDecl = MD->getParent();
7918
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007919 // C++ [except.spec]p14:
7920 // An implicitly declared special member function (Clause 12) shall have an
7921 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007922 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007923 if (ClassDecl->isInvalidDecl())
7924 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007925
Sebastian Redl60618fa2011-03-12 11:50:43 +00007926 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007927 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7928 BEnd = ClassDecl->bases_end();
7929 B != BEnd; ++B) {
7930 if (B->isVirtual()) // Handled below.
7931 continue;
7932
Douglas Gregor18274032010-07-03 00:47:00 +00007933 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7934 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007935 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7936 // If this is a deleted function, add it anyway. This might be conformant
7937 // with the standard. This might not. I'm not sure. It might not matter.
7938 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007939 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007940 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007941 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007942
7943 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007944 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7945 BEnd = ClassDecl->vbases_end();
7946 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007947 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7948 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007949 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7950 // If this is a deleted function, add it anyway. This might be conformant
7951 // with the standard. This might not. I'm not sure. It might not matter.
7952 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007953 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007954 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007955 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007956
7957 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007958 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7959 FEnd = ClassDecl->field_end();
7960 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007961 if (F->hasInClassInitializer()) {
7962 if (Expr *E = F->getInClassInitializer())
7963 ExceptSpec.CalledExpr(E);
7964 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007965 // DR1351:
7966 // If the brace-or-equal-initializer of a non-static data member
7967 // invokes a defaulted default constructor of its class or of an
7968 // enclosing class in a potentially evaluated subexpression, the
7969 // program is ill-formed.
7970 //
7971 // This resolution is unworkable: the exception specification of the
7972 // default constructor can be needed in an unevaluated context, in
7973 // particular, in the operand of a noexcept-expression, and we can be
7974 // unable to compute an exception specification for an enclosed class.
7975 //
7976 // We do not allow an in-class initializer to require the evaluation
7977 // of the exception specification for any in-class initializer whose
7978 // definition is not lexically complete.
7979 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007980 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007981 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007982 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7983 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7984 // If this is a deleted function, add it anyway. This might be conformant
7985 // with the standard. This might not. I'm not sure. It might not matter.
7986 // In particular, the problem is that this function never gets called. It
7987 // might just be ill-formed because this function attempts to refer to
7988 // a deleted function here.
7989 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007990 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007991 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007992 }
John McCalle23cf432010-12-14 08:05:40 +00007993
Sean Hunt001cad92011-05-10 00:49:42 +00007994 return ExceptSpec;
7995}
7996
Richard Smith07b0fdc2013-03-18 21:12:30 +00007997Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007998Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7999 CXXRecordDecl *ClassDecl = CD->getParent();
8000
8001 // C++ [except.spec]p14:
8002 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00008003 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00008004 if (ClassDecl->isInvalidDecl())
8005 return ExceptSpec;
8006
8007 // Inherited constructor.
8008 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
8009 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
8010 // FIXME: Copying or moving the parameters could add extra exceptions to the
8011 // set, as could the default arguments for the inherited constructor. This
8012 // will be addressed when we implement the resolution of core issue 1351.
8013 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
8014
8015 // Direct base-class constructors.
8016 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8017 BEnd = ClassDecl->bases_end();
8018 B != BEnd; ++B) {
8019 if (B->isVirtual()) // Handled below.
8020 continue;
8021
8022 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8023 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8024 if (BaseClassDecl == InheritedDecl)
8025 continue;
8026 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8027 if (Constructor)
8028 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8029 }
8030 }
8031
8032 // Virtual base-class constructors.
8033 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8034 BEnd = ClassDecl->vbases_end();
8035 B != BEnd; ++B) {
8036 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8037 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8038 if (BaseClassDecl == InheritedDecl)
8039 continue;
8040 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8041 if (Constructor)
8042 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8043 }
8044 }
8045
8046 // Field constructors.
8047 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8048 FEnd = ClassDecl->field_end();
8049 F != FEnd; ++F) {
8050 if (F->hasInClassInitializer()) {
8051 if (Expr *E = F->getInClassInitializer())
8052 ExceptSpec.CalledExpr(E);
8053 else if (!F->isInvalidDecl())
8054 Diag(CD->getLocation(),
8055 diag::err_in_class_initializer_references_def_ctor) << CD;
8056 } else if (const RecordType *RecordTy
8057 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8058 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8059 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8060 if (Constructor)
8061 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8062 }
8063 }
8064
Richard Smith07b0fdc2013-03-18 21:12:30 +00008065 return ExceptSpec;
8066}
8067
Richard Smithafb49182012-11-29 01:34:07 +00008068namespace {
8069/// RAII object to register a special member as being currently declared.
8070struct DeclaringSpecialMember {
8071 Sema &S;
8072 Sema::SpecialMemberDecl D;
8073 bool WasAlreadyBeingDeclared;
8074
8075 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8076 : S(S), D(RD, CSM) {
8077 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8078 if (WasAlreadyBeingDeclared)
8079 // This almost never happens, but if it does, ensure that our cache
8080 // doesn't contain a stale result.
8081 S.SpecialMemberCache.clear();
8082
8083 // FIXME: Register a note to be produced if we encounter an error while
8084 // declaring the special member.
8085 }
8086 ~DeclaringSpecialMember() {
8087 if (!WasAlreadyBeingDeclared)
8088 S.SpecialMembersBeingDeclared.erase(D);
8089 }
8090
8091 /// \brief Are we already trying to declare this special member?
8092 bool isAlreadyBeingDeclared() const {
8093 return WasAlreadyBeingDeclared;
8094 }
8095};
8096}
8097
Sean Hunt001cad92011-05-10 00:49:42 +00008098CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8099 CXXRecordDecl *ClassDecl) {
8100 // C++ [class.ctor]p5:
8101 // A default constructor for a class X is a constructor of class X
8102 // that can be called without an argument. If there is no
8103 // user-declared constructor for class X, a default constructor is
8104 // implicitly declared. An implicitly-declared default constructor
8105 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00008106 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00008107 "Should not build implicit default constructor!");
8108
Richard Smithafb49182012-11-29 01:34:07 +00008109 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8110 if (DSM.isAlreadyBeingDeclared())
8111 return 0;
8112
Richard Smith7756afa2012-06-10 05:43:50 +00008113 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8114 CXXDefaultConstructor,
8115 false);
8116
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008117 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00008118 CanQualType ClassType
8119 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008120 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008121 DeclarationName Name
8122 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008123 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00008124 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008125 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008126 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008127 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00008128 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00008129 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008130 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008131
8132 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008133 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008134 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008135
Richard Smithbc2a35d2012-12-08 08:32:28 +00008136 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8137 // constructors is easy to compute.
8138 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8139
8140 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008141 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008142
Douglas Gregor18274032010-07-03 00:47:00 +00008143 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00008144 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00008145
Douglas Gregor23c94db2010-07-02 17:43:08 +00008146 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00008147 PushOnScopeChains(DefaultCon, S, false);
8148 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00008149
Douglas Gregor32df23e2010-07-01 22:02:46 +00008150 return DefaultCon;
8151}
8152
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008153void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8154 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00008155 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008156 !Constructor->doesThisDeclarationHaveABody() &&
8157 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00008158 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008159
Anders Carlssonf6513ed2010-04-23 16:04:08 +00008160 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00008161 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00008162
Eli Friedman9a14db32012-10-18 20:14:08 +00008163 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008164 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00008165 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008166 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008167 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00008168 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00008169 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008170 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00008171 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008172
8173 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008174 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008175
Eli Friedman86164e82013-09-05 00:02:25 +00008176 Constructor->markUsed(Context);
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008177 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008178
8179 if (ASTMutationListener *L = getASTMutationListener()) {
8180 L->CompletedImplicitDefinition(Constructor);
8181 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008182}
8183
Richard Smith7a614d82011-06-11 17:19:42 +00008184void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00008185 // Check that any explicitly-defaulted methods have exception specifications
8186 // compatible with their implicit exception specifications.
8187 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Trieuef8f90c2013-09-20 03:03:06 +00008188
8189 // Once all the member initializers are processed, perform checks to see if
8190 // any unintialized use is happeneing.
8191 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
8192 D->getLocation())
8193 == DiagnosticsEngine::Ignored)
8194 return;
8195
8196 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D);
8197 if (!RD) return;
8198
8199 // Holds fields that are uninitialized.
8200 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
8201
8202 // In the beginning, every field is uninitialized.
8203 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
8204 I != E; ++I) {
8205 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
8206 UninitializedFields.insert(FD);
8207 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
8208 UninitializedFields.insert(IFD->getAnonField());
8209 }
8210 }
8211
8212 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
8213 I != E; ++I) {
8214 FieldDecl *FD = dyn_cast<FieldDecl>(*I);
8215 if (!FD)
8216 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I))
8217 FD = IFD->getAnonField();
8218
8219 if (!FD)
8220 continue;
8221
8222 Expr *InitExpr = FD->getInClassInitializer();
8223 if (!InitExpr) {
8224 // Uninitialized reference types will give an error.
8225 // Record types with an initializer are default initialized.
8226 QualType FieldType = FD->getType();
8227 if (FieldType->isReferenceType() || FieldType->isRecordType())
8228 UninitializedFields.erase(FD);
8229 continue;
8230 }
8231
8232 CheckInitExprContainsUninitializedFields(
8233 *this, InitExpr, FD, UninitializedFields,
8234 UninitializedFields.count(FD)/*WarnOnSelfReference*/);
8235
8236 UninitializedFields.erase(FD);
8237 }
Richard Smith7a614d82011-06-11 17:19:42 +00008238}
8239
Richard Smith4841ca52013-04-10 05:48:59 +00008240namespace {
8241/// Information on inheriting constructors to declare.
8242class InheritingConstructorInfo {
8243public:
8244 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8245 : SemaRef(SemaRef), Derived(Derived) {
8246 // Mark the constructors that we already have in the derived class.
8247 //
8248 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8249 // unless there is a user-declared constructor with the same signature in
8250 // the class where the using-declaration appears.
8251 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8252 }
8253
8254 void inheritAll(CXXRecordDecl *RD) {
8255 visitAll(RD, &InheritingConstructorInfo::inherit);
8256 }
8257
8258private:
8259 /// Information about an inheriting constructor.
8260 struct InheritingConstructor {
8261 InheritingConstructor()
8262 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8263
8264 /// If \c true, a constructor with this signature is already declared
8265 /// in the derived class.
8266 bool DeclaredInDerived;
8267
8268 /// The constructor which is inherited.
8269 const CXXConstructorDecl *BaseCtor;
8270
8271 /// The derived constructor we declared.
8272 CXXConstructorDecl *DerivedCtor;
8273 };
8274
8275 /// Inheriting constructors with a given canonical type. There can be at
8276 /// most one such non-template constructor, and any number of templated
8277 /// constructors.
8278 struct InheritingConstructorsForType {
8279 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008280 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8281 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008282
8283 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8284 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8285 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8286 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8287 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8288 false, S.TPL_TemplateMatch))
8289 return Templates[I].second;
8290 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8291 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008292 }
Richard Smith4841ca52013-04-10 05:48:59 +00008293
8294 return NonTemplate;
8295 }
8296 };
8297
8298 /// Get or create the inheriting constructor record for a constructor.
8299 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8300 QualType CtorType) {
8301 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8302 .getEntry(SemaRef, Ctor);
8303 }
8304
8305 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8306
8307 /// Process all constructors for a class.
8308 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8309 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8310 CtorE = RD->ctor_end();
8311 CtorIt != CtorE; ++CtorIt)
8312 (this->*Callback)(*CtorIt);
8313 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8314 I(RD->decls_begin()), E(RD->decls_end());
8315 I != E; ++I) {
8316 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8317 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8318 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008319 }
8320 }
Richard Smith4841ca52013-04-10 05:48:59 +00008321
8322 /// Note that a constructor (or constructor template) was declared in Derived.
8323 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8324 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8325 }
8326
8327 /// Inherit a single constructor.
8328 void inherit(const CXXConstructorDecl *Ctor) {
8329 const FunctionProtoType *CtorType =
8330 Ctor->getType()->castAs<FunctionProtoType>();
8331 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8332 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8333
8334 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8335
8336 // Core issue (no number yet): the ellipsis is always discarded.
8337 if (EPI.Variadic) {
8338 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8339 SemaRef.Diag(Ctor->getLocation(),
8340 diag::note_using_decl_constructor_ellipsis);
8341 EPI.Variadic = false;
8342 }
8343
8344 // Declare a constructor for each number of parameters.
8345 //
8346 // C++11 [class.inhctor]p1:
8347 // The candidate set of inherited constructors from the class X named in
8348 // the using-declaration consists of [... modulo defects ...] for each
8349 // constructor or constructor template of X, the set of constructors or
8350 // constructor templates that results from omitting any ellipsis parameter
8351 // specification and successively omitting parameters with a default
8352 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008353 unsigned MinParams = minParamsToInherit(Ctor);
8354 unsigned Params = Ctor->getNumParams();
8355 if (Params >= MinParams) {
8356 do
8357 declareCtor(UsingLoc, Ctor,
8358 SemaRef.Context.getFunctionType(
8359 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8360 while (Params > MinParams &&
8361 Ctor->getParamDecl(--Params)->hasDefaultArg());
8362 }
Richard Smith4841ca52013-04-10 05:48:59 +00008363 }
8364
8365 /// Find the using-declaration which specified that we should inherit the
8366 /// constructors of \p Base.
8367 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8368 // No fancy lookup required; just look for the base constructor name
8369 // directly within the derived class.
8370 ASTContext &Context = SemaRef.Context;
8371 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8372 Context.getCanonicalType(Context.getRecordType(Base)));
8373 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8374 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8375 }
8376
8377 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8378 // C++11 [class.inhctor]p3:
8379 // [F]or each constructor template in the candidate set of inherited
8380 // constructors, a constructor template is implicitly declared
8381 if (Ctor->getDescribedFunctionTemplate())
8382 return 0;
8383
8384 // For each non-template constructor in the candidate set of inherited
8385 // constructors other than a constructor having no parameters or a
8386 // copy/move constructor having a single parameter, a constructor is
8387 // implicitly declared [...]
8388 if (Ctor->getNumParams() == 0)
8389 return 1;
8390 if (Ctor->isCopyOrMoveConstructor())
8391 return 2;
8392
8393 // Per discussion on core reflector, never inherit a constructor which
8394 // would become a default, copy, or move constructor of Derived either.
8395 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8396 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8397 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8398 }
8399
8400 /// Declare a single inheriting constructor, inheriting the specified
8401 /// constructor, with the given type.
8402 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8403 QualType DerivedType) {
8404 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8405
8406 // C++11 [class.inhctor]p3:
8407 // ... a constructor is implicitly declared with the same constructor
8408 // characteristics unless there is a user-declared constructor with
8409 // the same signature in the class where the using-declaration appears
8410 if (Entry.DeclaredInDerived)
8411 return;
8412
8413 // C++11 [class.inhctor]p7:
8414 // If two using-declarations declare inheriting constructors with the
8415 // same signature, the program is ill-formed
8416 if (Entry.DerivedCtor) {
8417 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8418 // Only diagnose this once per constructor.
8419 if (Entry.DerivedCtor->isInvalidDecl())
8420 return;
8421 Entry.DerivedCtor->setInvalidDecl();
8422
8423 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8424 SemaRef.Diag(BaseCtor->getLocation(),
8425 diag::note_using_decl_constructor_conflict_current_ctor);
8426 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8427 diag::note_using_decl_constructor_conflict_previous_ctor);
8428 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8429 diag::note_using_decl_constructor_conflict_previous_using);
8430 } else {
8431 // Core issue (no number): if the same inheriting constructor is
8432 // produced by multiple base class constructors from the same base
8433 // class, the inheriting constructor is defined as deleted.
8434 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8435 }
8436
8437 return;
8438 }
8439
8440 ASTContext &Context = SemaRef.Context;
8441 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8442 Context.getCanonicalType(Context.getRecordType(Derived)));
8443 DeclarationNameInfo NameInfo(Name, UsingLoc);
8444
8445 TemplateParameterList *TemplateParams = 0;
8446 if (const FunctionTemplateDecl *FTD =
8447 BaseCtor->getDescribedFunctionTemplate()) {
8448 TemplateParams = FTD->getTemplateParameters();
8449 // We're reusing template parameters from a different DeclContext. This
8450 // is questionable at best, but works out because the template depth in
8451 // both places is guaranteed to be 0.
8452 // FIXME: Rebuild the template parameters in the new context, and
8453 // transform the function type to refer to them.
8454 }
8455
8456 // Build type source info pointing at the using-declaration. This is
8457 // required by template instantiation.
8458 TypeSourceInfo *TInfo =
8459 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8460 FunctionProtoTypeLoc ProtoLoc =
8461 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8462
8463 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8464 Context, Derived, UsingLoc, NameInfo, DerivedType,
8465 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8466 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8467
8468 // Build an unevaluated exception specification for this constructor.
8469 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8470 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8471 EPI.ExceptionSpecType = EST_Unevaluated;
8472 EPI.ExceptionSpecDecl = DerivedCtor;
8473 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8474 FPT->getArgTypes(), EPI));
8475
8476 // Build the parameter declarations.
8477 SmallVector<ParmVarDecl *, 16> ParamDecls;
8478 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8479 TypeSourceInfo *TInfo =
8480 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8481 ParmVarDecl *PD = ParmVarDecl::Create(
8482 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8483 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8484 PD->setScopeInfo(0, I);
8485 PD->setImplicit();
8486 ParamDecls.push_back(PD);
8487 ProtoLoc.setArg(I, PD);
8488 }
8489
8490 // Set up the new constructor.
8491 DerivedCtor->setAccess(BaseCtor->getAccess());
8492 DerivedCtor->setParams(ParamDecls);
8493 DerivedCtor->setInheritedConstructor(BaseCtor);
8494 if (BaseCtor->isDeleted())
8495 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8496
8497 // If this is a constructor template, build the template declaration.
8498 if (TemplateParams) {
8499 FunctionTemplateDecl *DerivedTemplate =
8500 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8501 TemplateParams, DerivedCtor);
8502 DerivedTemplate->setAccess(BaseCtor->getAccess());
8503 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8504 Derived->addDecl(DerivedTemplate);
8505 } else {
8506 Derived->addDecl(DerivedCtor);
8507 }
8508
8509 Entry.BaseCtor = BaseCtor;
8510 Entry.DerivedCtor = DerivedCtor;
8511 }
8512
8513 Sema &SemaRef;
8514 CXXRecordDecl *Derived;
8515 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8516 MapType Map;
8517};
8518}
8519
8520void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8521 // Defer declaring the inheriting constructors until the class is
8522 // instantiated.
8523 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008524 return;
8525
Richard Smith4841ca52013-04-10 05:48:59 +00008526 // Find base classes from which we might inherit constructors.
8527 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8528 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8529 BaseE = ClassDecl->bases_end();
8530 BaseIt != BaseE; ++BaseIt)
8531 if (BaseIt->getInheritConstructors())
8532 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008533
Richard Smith4841ca52013-04-10 05:48:59 +00008534 // Go no further if we're not inheriting any constructors.
8535 if (InheritedBases.empty())
8536 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008537
Richard Smith4841ca52013-04-10 05:48:59 +00008538 // Declare the inherited constructors.
8539 InheritingConstructorInfo ICI(*this, ClassDecl);
8540 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8541 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008542}
8543
Richard Smith07b0fdc2013-03-18 21:12:30 +00008544void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8545 CXXConstructorDecl *Constructor) {
8546 CXXRecordDecl *ClassDecl = Constructor->getParent();
8547 assert(Constructor->getInheritedConstructor() &&
8548 !Constructor->doesThisDeclarationHaveABody() &&
8549 !Constructor->isDeleted());
8550
8551 SynthesizedFunctionScope Scope(*this, Constructor);
8552 DiagnosticErrorTrap Trap(Diags);
8553 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8554 Trap.hasErrorOccurred()) {
8555 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8556 << Context.getTagDeclType(ClassDecl);
8557 Constructor->setInvalidDecl();
8558 return;
8559 }
8560
8561 SourceLocation Loc = Constructor->getLocation();
8562 Constructor->setBody(new (Context) CompoundStmt(Loc));
8563
Eli Friedman86164e82013-09-05 00:02:25 +00008564 Constructor->markUsed(Context);
Richard Smith07b0fdc2013-03-18 21:12:30 +00008565 MarkVTableUsed(CurrentLocation, ClassDecl);
8566
8567 if (ASTMutationListener *L = getASTMutationListener()) {
8568 L->CompletedImplicitDefinition(Constructor);
8569 }
8570}
8571
8572
Sean Huntcb45a0f2011-05-12 22:46:25 +00008573Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008574Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8575 CXXRecordDecl *ClassDecl = MD->getParent();
8576
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008577 // C++ [except.spec]p14:
8578 // An implicitly declared special member function (Clause 12) shall have
8579 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008580 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008581 if (ClassDecl->isInvalidDecl())
8582 return ExceptSpec;
8583
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008584 // Direct base-class destructors.
8585 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8586 BEnd = ClassDecl->bases_end();
8587 B != BEnd; ++B) {
8588 if (B->isVirtual()) // Handled below.
8589 continue;
8590
8591 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008592 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008593 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008594 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008595
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008596 // Virtual base-class destructors.
8597 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8598 BEnd = ClassDecl->vbases_end();
8599 B != BEnd; ++B) {
8600 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008601 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008602 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008603 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008604
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008605 // Field destructors.
8606 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8607 FEnd = ClassDecl->field_end();
8608 F != FEnd; ++F) {
8609 if (const RecordType *RecordTy
8610 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008611 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008612 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008613 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008614
Sean Huntcb45a0f2011-05-12 22:46:25 +00008615 return ExceptSpec;
8616}
8617
8618CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8619 // C++ [class.dtor]p2:
8620 // If a class has no user-declared destructor, a destructor is
8621 // declared implicitly. An implicitly-declared destructor is an
8622 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008623 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008624
Richard Smithafb49182012-11-29 01:34:07 +00008625 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8626 if (DSM.isAlreadyBeingDeclared())
8627 return 0;
8628
Douglas Gregor4923aa22010-07-02 20:37:36 +00008629 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008630 CanQualType ClassType
8631 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008632 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008633 DeclarationName Name
8634 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008635 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008636 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008637 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8638 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008639 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008640 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008641 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008642 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008643
8644 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008645 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008646 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008647
Richard Smithbc2a35d2012-12-08 08:32:28 +00008648 AddOverriddenMethods(ClassDecl, Destructor);
8649
8650 // We don't need to use SpecialMemberIsTrivial here; triviality for
8651 // destructors is easy to compute.
8652 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8653
8654 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008655 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008656
Douglas Gregor4923aa22010-07-02 20:37:36 +00008657 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008658 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008659
Douglas Gregor4923aa22010-07-02 20:37:36 +00008660 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008661 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008662 PushOnScopeChains(Destructor, S, false);
8663 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008664
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008665 return Destructor;
8666}
8667
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008668void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008669 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008670 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008671 !Destructor->doesThisDeclarationHaveABody() &&
8672 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008673 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008674 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008675 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008676
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008677 if (Destructor->isInvalidDecl())
8678 return;
8679
Eli Friedman9a14db32012-10-18 20:14:08 +00008680 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008681
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008682 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008683 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8684 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008685
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008686 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008687 Diag(CurrentLocation, diag::note_member_synthesized_at)
8688 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8689
8690 Destructor->setInvalidDecl();
8691 return;
8692 }
8693
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008694 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008695 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman86164e82013-09-05 00:02:25 +00008696 Destructor->markUsed(Context);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008697 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008698
8699 if (ASTMutationListener *L = getASTMutationListener()) {
8700 L->CompletedImplicitDefinition(Destructor);
8701 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008702}
8703
Richard Smitha4156b82012-04-21 18:42:51 +00008704/// \brief Perform any semantic analysis which needs to be delayed until all
8705/// pending class member declarations have been parsed.
8706void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008707 // If the context is an invalid C++ class, just suppress these checks.
8708 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8709 if (Record->isInvalidDecl()) {
8710 DelayedDestructorExceptionSpecChecks.clear();
8711 return;
8712 }
8713 }
8714
Richard Smitha4156b82012-04-21 18:42:51 +00008715 // Perform any deferred checking of exception specifications for virtual
8716 // destructors.
8717 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8718 i != e; ++i) {
8719 const CXXDestructorDecl *Dtor =
8720 DelayedDestructorExceptionSpecChecks[i].first;
8721 assert(!Dtor->getParent()->isDependentType() &&
8722 "Should not ever add destructors of templates into the list.");
8723 CheckOverridingFunctionExceptionSpec(Dtor,
8724 DelayedDestructorExceptionSpecChecks[i].second);
8725 }
8726 DelayedDestructorExceptionSpecChecks.clear();
8727}
8728
Richard Smithb9d0b762012-07-27 04:22:15 +00008729void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8730 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008731 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008732 "adjusting dtor exception specs was introduced in c++11");
8733
Sebastian Redl0ee33912011-05-19 05:13:44 +00008734 // C++11 [class.dtor]p3:
8735 // A declaration of a destructor that does not have an exception-
8736 // specification is implicitly considered to have the same exception-
8737 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008738 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008739 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008740 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008741 return;
8742
Chandler Carruth3f224b22011-09-20 04:55:26 +00008743 // Replace the destructor's type, building off the existing one. Fortunately,
8744 // the only thing of interest in the destructor type is its extended info.
8745 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008746 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8747 EPI.ExceptionSpecType = EST_Unevaluated;
8748 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008749 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008750
Sebastian Redl0ee33912011-05-19 05:13:44 +00008751 // FIXME: If the destructor has a body that could throw, and the newly created
8752 // spec doesn't allow exceptions, we should emit a warning, because this
8753 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008754 // However, we don't have a body or an exception specification yet, so it
8755 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008756}
8757
Pavel Labath66ea35d2013-08-30 08:52:28 +00008758namespace {
8759/// \brief An abstract base class for all helper classes used in building the
8760// copy/move operators. These classes serve as factory functions and help us
8761// avoid using the same Expr* in the AST twice.
8762class ExprBuilder {
8763 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8764 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8765
8766protected:
8767 static Expr *assertNotNull(Expr *E) {
8768 assert(E && "Expression construction must not fail.");
8769 return E;
8770 }
8771
8772public:
8773 ExprBuilder() {}
8774 virtual ~ExprBuilder() {}
8775
8776 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8777};
8778
8779class RefBuilder: public ExprBuilder {
8780 VarDecl *Var;
8781 QualType VarType;
8782
8783public:
8784 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8785 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8786 }
8787
8788 RefBuilder(VarDecl *Var, QualType VarType)
8789 : Var(Var), VarType(VarType) {}
8790};
8791
8792class ThisBuilder: public ExprBuilder {
8793public:
8794 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8795 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8796 }
8797};
8798
8799class CastBuilder: public ExprBuilder {
8800 const ExprBuilder &Builder;
8801 QualType Type;
8802 ExprValueKind Kind;
8803 const CXXCastPath &Path;
8804
8805public:
8806 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8807 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8808 CK_UncheckedDerivedToBase, Kind,
8809 &Path).take());
8810 }
8811
8812 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8813 const CXXCastPath &Path)
8814 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8815};
8816
8817class DerefBuilder: public ExprBuilder {
8818 const ExprBuilder &Builder;
8819
8820public:
8821 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8822 return assertNotNull(
8823 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8824 }
8825
8826 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8827};
8828
8829class MemberBuilder: public ExprBuilder {
8830 const ExprBuilder &Builder;
8831 QualType Type;
8832 CXXScopeSpec SS;
8833 bool IsArrow;
8834 LookupResult &MemberLookup;
8835
8836public:
8837 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8838 return assertNotNull(S.BuildMemberReferenceExpr(
8839 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8840 MemberLookup, 0).take());
8841 }
8842
8843 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8844 LookupResult &MemberLookup)
8845 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8846 MemberLookup(MemberLookup) {}
8847};
8848
8849class MoveCastBuilder: public ExprBuilder {
8850 const ExprBuilder &Builder;
8851
8852public:
8853 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8854 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8855 }
8856
8857 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8858};
8859
8860class LvalueConvBuilder: public ExprBuilder {
8861 const ExprBuilder &Builder;
8862
8863public:
8864 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8865 return assertNotNull(
8866 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8867 }
8868
8869 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8870};
8871
8872class SubscriptBuilder: public ExprBuilder {
8873 const ExprBuilder &Base;
8874 const ExprBuilder &Index;
8875
8876public:
8877 virtual Expr *build(Sema &S, SourceLocation Loc) const
8878 LLVM_OVERRIDE {
8879 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8880 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8881 }
8882
8883 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8884 : Base(Base), Index(Index) {}
8885};
8886
8887} // end anonymous namespace
8888
Richard Smith8c889532012-11-14 00:50:40 +00008889/// When generating a defaulted copy or move assignment operator, if a field
8890/// should be copied with __builtin_memcpy rather than via explicit assignments,
8891/// do so. This optimization only applies for arrays of scalars, and for arrays
8892/// of class type where the selected copy/move-assignment operator is trivial.
8893static StmtResult
8894buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008895 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00008896 // Compute the size of the memory buffer to be copied.
8897 QualType SizeType = S.Context.getSizeType();
8898 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8899 S.Context.getTypeSizeInChars(T).getQuantity());
8900
8901 // Take the address of the field references for "from" and "to". We
8902 // directly construct UnaryOperators here because semantic analysis
8903 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008904 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008905 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8906 S.Context.getPointerType(From->getType()),
8907 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00008908 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008909 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8910 S.Context.getPointerType(To->getType()),
8911 VK_RValue, OK_Ordinary, Loc);
8912
8913 const Type *E = T->getBaseElementTypeUnsafe();
8914 bool NeedsCollectableMemCpy =
8915 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8916
8917 // Create a reference to the __builtin_objc_memmove_collectable function
8918 StringRef MemCpyName = NeedsCollectableMemCpy ?
8919 "__builtin_objc_memmove_collectable" :
8920 "__builtin_memcpy";
8921 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8922 Sema::LookupOrdinaryName);
8923 S.LookupName(R, S.TUScope, true);
8924
8925 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8926 if (!MemCpy)
8927 // Something went horribly wrong earlier, and we will have complained
8928 // about it.
8929 return StmtError();
8930
8931 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8932 VK_RValue, Loc, 0);
8933 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8934
8935 Expr *CallArgs[] = {
8936 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8937 };
8938 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8939 Loc, CallArgs, Loc);
8940
8941 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8942 return S.Owned(Call.takeAs<Stmt>());
8943}
8944
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008945/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008946/// \c To.
8947///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008948/// This routine is used to copy/move the members of a class with an
8949/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008950/// copied are arrays, this routine builds for loops to copy them.
8951///
8952/// \param S The Sema object used for type-checking.
8953///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008954/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008955///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008956/// \param T The type of the expressions being copied/moved. Both expressions
8957/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008958///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008959/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008960///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008961/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008962///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008963/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008964/// Otherwise, it's a non-static member subobject.
8965///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008966/// \param Copying Whether we're copying or moving.
8967///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008968/// \param Depth Internal parameter recording the depth of the recursion.
8969///
Richard Smith8c889532012-11-14 00:50:40 +00008970/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8971/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008972static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008973buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008974 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008975 bool CopyingBaseSubobject, bool Copying,
8976 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008977 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008978 // Each subobject is assigned in the manner appropriate to its type:
8979 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008980 // - if the subobject is of class type, as if by a call to operator= with
8981 // the subobject as the object expression and the corresponding
8982 // subobject of x as a single function argument (as if by explicit
8983 // qualification; that is, ignoring any possible virtual overriding
8984 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008985 //
8986 // C++03 [class.copy]p13:
8987 // - if the subobject is of class type, the copy assignment operator for
8988 // the class is used (as if by explicit qualification; that is,
8989 // ignoring any possible virtual overriding functions in more derived
8990 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008991 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8992 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008993
Douglas Gregor06a9f362010-05-01 20:49:11 +00008994 // Look for operator=.
8995 DeclarationName Name
8996 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8997 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8998 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008999
Richard Smith044c8aa2012-11-13 00:54:12 +00009000 // Prior to C++11, filter out any result that isn't a copy/move-assignment
9001 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00009002 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00009003 LookupResult::Filter F = OpLookup.makeFilter();
9004 while (F.hasNext()) {
9005 NamedDecl *D = F.next();
9006 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
9007 if (Method->isCopyAssignmentOperator() ||
9008 (!Copying && Method->isMoveAssignmentOperator()))
9009 continue;
9010
9011 F.erase();
9012 }
9013 F.done();
John McCallb0207482010-03-16 06:11:48 +00009014 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009015
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009016 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00009017 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009018 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00009019 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00009020 // ambiguities), we need to cast "this" to that subobject type; to
9021 // ensure that we don't go through the virtual call mechanism, we need
9022 // to qualify the operator= name with the base class (see below). However,
9023 // this means that if the base class has a protected copy assignment
9024 // operator, the protected member access check will fail. So, we
9025 // rewrite "protected" access to "public" access in this case, since we
9026 // know by construction that we're calling from a derived class.
9027 if (CopyingBaseSubobject) {
9028 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
9029 L != LEnd; ++L) {
9030 if (L.getAccess() == AS_protected)
9031 L.setAccess(AS_public);
9032 }
9033 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009034
Douglas Gregor06a9f362010-05-01 20:49:11 +00009035 // Create the nested-name-specifier that will be used to qualify the
9036 // reference to operator=; this is required to suppress the virtual
9037 // call mechanism.
9038 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009039 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00009040 SS.MakeTrivial(S.Context,
9041 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009042 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00009043 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00009044
Douglas Gregor06a9f362010-05-01 20:49:11 +00009045 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00009046 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00009047 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9048 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009049 /*FirstQualifierInScope=*/0,
9050 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009051 /*TemplateArgs=*/0,
9052 /*SuppressQualifierCheck=*/true);
9053 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009054 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009055
Douglas Gregor06a9f362010-05-01 20:49:11 +00009056 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00009057
Pavel Labath66ea35d2013-08-30 08:52:28 +00009058 Expr *FromInst = From.build(S, Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00009059 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00009060 OpEqualRef.takeAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009061 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009062 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009063 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009064
Richard Smith8c889532012-11-14 00:50:40 +00009065 // If we built a call to a trivial 'operator=' while copying an array,
9066 // bail out. We'll replace the whole shebang with a memcpy.
9067 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9068 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9069 return StmtResult((Stmt*)0);
9070
Richard Smith044c8aa2012-11-13 00:54:12 +00009071 // Convert to an expression-statement, and clean up any produced
9072 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00009073 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009074 }
John McCallb0207482010-03-16 06:11:48 +00009075
Richard Smith044c8aa2012-11-13 00:54:12 +00009076 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00009077 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00009078 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009079 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009080 ExprResult Assignment = S.CreateBuiltinBinOp(
9081 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009082 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009083 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00009084 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009085 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009086
9087 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00009088 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00009089
Douglas Gregor06a9f362010-05-01 20:49:11 +00009090 // Construct a loop over the array bounds, e.g.,
9091 //
9092 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9093 //
9094 // that will copy each of the array elements.
9095 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00009096
Douglas Gregor06a9f362010-05-01 20:49:11 +00009097 // Create the iteration variable.
9098 IdentifierInfo *IterationVarName = 0;
9099 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009100 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009101 llvm::raw_svector_ostream OS(Str);
9102 OS << "__i" << Depth;
9103 IterationVarName = &S.Context.Idents.get(OS.str());
9104 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009105 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009106 IterationVarName, SizeType,
9107 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009108 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00009109
Douglas Gregor06a9f362010-05-01 20:49:11 +00009110 // Initialize the iteration variable to zero.
9111 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009112 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009113
Pavel Labath66ea35d2013-08-30 08:52:28 +00009114 // Creates a reference to the iteration variable.
9115 RefBuilder IterationVarRef(IterationVar, SizeType);
9116 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00009117
Douglas Gregor06a9f362010-05-01 20:49:11 +00009118 // Create the DeclStmt that holds the iteration variable.
9119 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009120
Douglas Gregor06a9f362010-05-01 20:49:11 +00009121 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009122 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9123 MoveCastBuilder FromIndexMove(FromIndexCopy);
9124 const ExprBuilder *FromIndex;
9125 if (Copying)
9126 FromIndex = &FromIndexCopy;
9127 else
9128 FromIndex = &FromIndexMove;
9129
9130 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009131
9132 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00009133 StmtResult Copy =
9134 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009135 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00009136 Copying, Depth + 1);
9137 // Bail out if copying fails or if we determined that we should use memcpy.
9138 if (Copy.isInvalid() || !Copy.get())
9139 return Copy;
9140
9141 // Create the comparison against the array bound.
9142 llvm::APInt Upper
9143 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9144 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00009145 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00009146 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9147 BO_NE, S.Context.BoolTy,
9148 VK_RValue, OK_Ordinary, Loc, false);
9149
9150 // Create the pre-increment of the iteration variable.
9151 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00009152 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9153 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009154
Douglas Gregor06a9f362010-05-01 20:49:11 +00009155 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00009156 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009157 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00009158 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00009159 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009160}
9161
Richard Smith8c889532012-11-14 00:50:40 +00009162static StmtResult
9163buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009164 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00009165 bool CopyingBaseSubobject, bool Copying) {
9166 // Maybe we should use a memcpy?
9167 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9168 T.isTriviallyCopyableType(S.Context))
9169 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9170
9171 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9172 CopyingBaseSubobject,
9173 Copying, 0));
9174
9175 // If we ended up picking a trivial assignment operator for an array of a
9176 // non-trivially-copyable class type, just emit a memcpy.
9177 if (!Result.isInvalid() && !Result.get())
9178 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9179
9180 return Result;
9181}
9182
Richard Smithb9d0b762012-07-27 04:22:15 +00009183Sema::ImplicitExceptionSpecification
9184Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9185 CXXRecordDecl *ClassDecl = MD->getParent();
9186
9187 ImplicitExceptionSpecification ExceptSpec(*this);
9188 if (ClassDecl->isInvalidDecl())
9189 return ExceptSpec;
9190
9191 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9192 assert(T->getNumArgs() == 1 && "not a copy assignment op");
9193 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9194
Douglas Gregorb87786f2010-07-01 17:48:08 +00009195 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00009196 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00009197 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00009198
9199 // It is unspecified whether or not an implicit copy assignment operator
9200 // attempts to deduplicate calls to assignment operators of virtual bases are
9201 // made. As such, this exception specification is effectively unspecified.
9202 // Based on a similar decision made for constness in C++0x, we're erring on
9203 // the side of assuming such calls to be made regardless of whether they
9204 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00009205 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9206 BaseEnd = ClassDecl->bases_end();
9207 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00009208 if (Base->isVirtual())
9209 continue;
9210
Douglas Gregora376d102010-07-02 21:50:04 +00009211 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00009212 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009213 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9214 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009215 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00009216 }
Sean Hunt661c67a2011-06-21 23:42:56 +00009217
9218 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9219 BaseEnd = ClassDecl->vbases_end();
9220 Base != BaseEnd; ++Base) {
9221 CXXRecordDecl *BaseClassDecl
9222 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9223 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9224 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009225 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00009226 }
9227
Douglas Gregorb87786f2010-07-01 17:48:08 +00009228 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9229 FieldEnd = ClassDecl->field_end();
9230 Field != FieldEnd;
9231 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009232 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00009233 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9234 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009235 LookupCopyingAssignment(FieldClassDecl,
9236 ArgQuals | FieldType.getCVRQualifiers(),
9237 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009238 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009239 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00009240 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009241
Richard Smithb9d0b762012-07-27 04:22:15 +00009242 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00009243}
9244
9245CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9246 // Note: The following rules are largely analoguous to the copy
9247 // constructor rules. Note that virtual bases are not taken into account
9248 // for determining the argument type of the operator. Note also that
9249 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00009250 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00009251
Richard Smithafb49182012-11-29 01:34:07 +00009252 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9253 if (DSM.isAlreadyBeingDeclared())
9254 return 0;
9255
Sean Hunt30de05c2011-05-14 05:23:20 +00009256 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9257 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00009258 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9259 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00009260 ArgType = ArgType.withConst();
9261 ArgType = Context.getLValueReferenceType(ArgType);
9262
Richard Smitha8942d72013-05-07 03:19:20 +00009263 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9264 CXXCopyAssignment,
9265 Const);
9266
Douglas Gregord3c35902010-07-01 16:36:15 +00009267 // An implicitly-declared copy assignment operator is an inline public
9268 // member of its class.
9269 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009270 SourceLocation ClassLoc = ClassDecl->getLocation();
9271 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009272 CXXMethodDecl *CopyAssignment =
9273 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9274 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9275 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00009276 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00009277 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00009278 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00009279
9280 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009281 FunctionProtoType::ExtProtoInfo EPI =
9282 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009283 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009284
Douglas Gregord3c35902010-07-01 16:36:15 +00009285 // Add the parameter to the operator.
9286 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009287 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00009288 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009289 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009290 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00009291
Richard Smithbc2a35d2012-12-08 08:32:28 +00009292 AddOverriddenMethods(ClassDecl, CopyAssignment);
9293
9294 CopyAssignment->setTrivial(
9295 ClassDecl->needsOverloadResolutionForCopyAssignment()
9296 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9297 : ClassDecl->hasTrivialCopyAssignment());
9298
Richard Smitha8942d72013-05-07 03:19:20 +00009299 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00009300 // .... If the class definition does not explicitly declare a copy
9301 // assignment operator, there is no user-declared move constructor, and
9302 // there is no user-declared move assignment operator, a copy assignment
9303 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009304 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009305 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009306
Richard Smithbc2a35d2012-12-08 08:32:28 +00009307 // Note that we have added this copy-assignment operator.
9308 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9309
9310 if (Scope *S = getScopeForContext(ClassDecl))
9311 PushOnScopeChains(CopyAssignment, S, false);
9312 ClassDecl->addDecl(CopyAssignment);
9313
Douglas Gregord3c35902010-07-01 16:36:15 +00009314 return CopyAssignment;
9315}
9316
Richard Smith36155c12013-06-13 03:23:42 +00009317/// Diagnose an implicit copy operation for a class which is odr-used, but
9318/// which is deprecated because the class has a user-declared copy constructor,
9319/// copy assignment operator, or destructor.
9320static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9321 SourceLocation UseLoc) {
9322 assert(CopyOp->isImplicit());
9323
9324 CXXRecordDecl *RD = CopyOp->getParent();
9325 CXXMethodDecl *UserDeclaredOperation = 0;
9326
9327 // In Microsoft mode, assignment operations don't affect constructors and
9328 // vice versa.
9329 if (RD->hasUserDeclaredDestructor()) {
9330 UserDeclaredOperation = RD->getDestructor();
9331 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9332 RD->hasUserDeclaredCopyConstructor() &&
9333 !S.getLangOpts().MicrosoftMode) {
9334 // Find any user-declared copy constructor.
9335 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9336 E = RD->ctor_end(); I != E; ++I) {
9337 if (I->isCopyConstructor()) {
9338 UserDeclaredOperation = *I;
9339 break;
9340 }
9341 }
9342 assert(UserDeclaredOperation);
9343 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9344 RD->hasUserDeclaredCopyAssignment() &&
9345 !S.getLangOpts().MicrosoftMode) {
9346 // Find any user-declared move assignment operator.
9347 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9348 E = RD->method_end(); I != E; ++I) {
9349 if (I->isCopyAssignmentOperator()) {
9350 UserDeclaredOperation = *I;
9351 break;
9352 }
9353 }
9354 assert(UserDeclaredOperation);
9355 }
9356
9357 if (UserDeclaredOperation) {
9358 S.Diag(UserDeclaredOperation->getLocation(),
9359 diag::warn_deprecated_copy_operation)
9360 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9361 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9362 S.Diag(UseLoc, diag::note_member_synthesized_at)
9363 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9364 : Sema::CXXCopyAssignment)
9365 << RD;
9366 }
9367}
9368
Douglas Gregor06a9f362010-05-01 20:49:11 +00009369void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9370 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00009371 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009372 CopyAssignOperator->isOverloadedOperator() &&
9373 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009374 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9375 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009376 "DefineImplicitCopyAssignment called for wrong function");
9377
9378 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9379
9380 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9381 CopyAssignOperator->setInvalidDecl();
9382 return;
9383 }
Richard Smith36155c12013-06-13 03:23:42 +00009384
9385 // C++11 [class.copy]p18:
9386 // The [definition of an implicitly declared copy assignment operator] is
9387 // deprecated if the class has a user-declared copy constructor or a
9388 // user-declared destructor.
9389 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9390 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9391
Eli Friedman86164e82013-09-05 00:02:25 +00009392 CopyAssignOperator->markUsed(Context);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009393
Eli Friedman9a14db32012-10-18 20:14:08 +00009394 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009395 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009396
9397 // C++0x [class.copy]p30:
9398 // The implicitly-defined or explicitly-defaulted copy assignment operator
9399 // for a non-union class X performs memberwise copy assignment of its
9400 // subobjects. The direct base classes of X are assigned first, in the
9401 // order of their declaration in the base-specifier-list, and then the
9402 // immediate non-static data members of X are assigned, in the order in
9403 // which they were declared in the class definition.
9404
9405 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009406 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009407
9408 // The parameter for the "other" object, which we are copying from.
9409 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9410 Qualifiers OtherQuals = Other->getType().getQualifiers();
9411 QualType OtherRefType = Other->getType();
9412 if (const LValueReferenceType *OtherRef
9413 = OtherRefType->getAs<LValueReferenceType>()) {
9414 OtherRefType = OtherRef->getPointeeType();
9415 OtherQuals = OtherRefType.getQualifiers();
9416 }
9417
9418 // Our location for everything implicitly-generated.
9419 SourceLocation Loc = CopyAssignOperator->getLocation();
9420
Pavel Labath66ea35d2013-08-30 08:52:28 +00009421 // Builds a DeclRefExpr for the "other" object.
9422 RefBuilder OtherRef(Other, OtherRefType);
9423
9424 // Builds the "this" pointer.
9425 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009426
9427 // Assign base classes.
9428 bool Invalid = false;
9429 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9430 E = ClassDecl->bases_end(); Base != E; ++Base) {
9431 // Form the assignment:
9432 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9433 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009434 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009435 Invalid = true;
9436 continue;
9437 }
9438
John McCallf871d0c2010-08-07 06:22:56 +00009439 CXXCastPath BasePath;
9440 BasePath.push_back(Base);
9441
Douglas Gregor06a9f362010-05-01 20:49:11 +00009442 // Construct the "from" expression, which is an implicit cast to the
9443 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009444 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9445 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009446
9447 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009448 DerefBuilder DerefThis(This);
9449 CastBuilder To(DerefThis,
9450 Context.getCVRQualifiedType(
9451 BaseType, CopyAssignOperator->getTypeQualifiers()),
9452 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009453
9454 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009455 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009456 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009457 /*CopyingBaseSubobject=*/true,
9458 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009459 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009460 Diag(CurrentLocation, diag::note_member_synthesized_at)
9461 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9462 CopyAssignOperator->setInvalidDecl();
9463 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009464 }
9465
9466 // Success! Record the copy.
9467 Statements.push_back(Copy.takeAs<Expr>());
9468 }
9469
Douglas Gregor06a9f362010-05-01 20:49:11 +00009470 // Assign non-static members.
9471 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9472 FieldEnd = ClassDecl->field_end();
9473 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009474 if (Field->isUnnamedBitfield())
9475 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009476
9477 if (Field->isInvalidDecl()) {
9478 Invalid = true;
9479 continue;
9480 }
9481
Douglas Gregor06a9f362010-05-01 20:49:11 +00009482 // Check for members of reference type; we can't copy those.
9483 if (Field->getType()->isReferenceType()) {
9484 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9485 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9486 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009487 Diag(CurrentLocation, diag::note_member_synthesized_at)
9488 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009489 Invalid = true;
9490 continue;
9491 }
9492
9493 // Check for members of const-qualified, non-class type.
9494 QualType BaseType = Context.getBaseElementType(Field->getType());
9495 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9496 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9497 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9498 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009499 Diag(CurrentLocation, diag::note_member_synthesized_at)
9500 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009501 Invalid = true;
9502 continue;
9503 }
John McCallb77115d2011-06-17 00:18:42 +00009504
9505 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009506 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9507 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009508
9509 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009510 if (FieldType->isIncompleteArrayType()) {
9511 assert(ClassDecl->hasFlexibleArrayMember() &&
9512 "Incomplete array type is not valid");
9513 continue;
9514 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009515
9516 // Build references to the field in the object we're copying from and to.
9517 CXXScopeSpec SS; // Intentionally empty
9518 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9519 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009520 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009521 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009522
9523 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9524
9525 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009526
Douglas Gregor06a9f362010-05-01 20:49:11 +00009527 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009528 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009529 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009530 /*CopyingBaseSubobject=*/false,
9531 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009532 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009533 Diag(CurrentLocation, diag::note_member_synthesized_at)
9534 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9535 CopyAssignOperator->setInvalidDecl();
9536 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009537 }
9538
9539 // Success! Record the copy.
9540 Statements.push_back(Copy.takeAs<Stmt>());
9541 }
9542
9543 if (!Invalid) {
9544 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009545 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009546
John McCall60d7b3a2010-08-24 06:29:42 +00009547 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009548 if (Return.isInvalid())
9549 Invalid = true;
9550 else {
9551 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009552
9553 if (Trap.hasErrorOccurred()) {
9554 Diag(CurrentLocation, diag::note_member_synthesized_at)
9555 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9556 Invalid = true;
9557 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009558 }
9559 }
9560
9561 if (Invalid) {
9562 CopyAssignOperator->setInvalidDecl();
9563 return;
9564 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009565
9566 StmtResult Body;
9567 {
9568 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009569 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009570 /*isStmtExpr=*/false);
9571 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9572 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009573 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009574
9575 if (ASTMutationListener *L = getASTMutationListener()) {
9576 L->CompletedImplicitDefinition(CopyAssignOperator);
9577 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009578}
9579
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009580Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009581Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9582 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009583
Richard Smithb9d0b762012-07-27 04:22:15 +00009584 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009585 if (ClassDecl->isInvalidDecl())
9586 return ExceptSpec;
9587
9588 // C++0x [except.spec]p14:
9589 // An implicitly declared special member function (Clause 12) shall have an
9590 // exception-specification. [...]
9591
9592 // It is unspecified whether or not an implicit move assignment operator
9593 // attempts to deduplicate calls to assignment operators of virtual bases are
9594 // made. As such, this exception specification is effectively unspecified.
9595 // Based on a similar decision made for constness in C++0x, we're erring on
9596 // the side of assuming such calls to be made regardless of whether they
9597 // actually happen.
9598 // Note that a move constructor is not implicitly declared when there are
9599 // virtual bases, but it can still be user-declared and explicitly defaulted.
9600 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9601 BaseEnd = ClassDecl->bases_end();
9602 Base != BaseEnd; ++Base) {
9603 if (Base->isVirtual())
9604 continue;
9605
9606 CXXRecordDecl *BaseClassDecl
9607 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9608 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009609 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009610 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009611 }
9612
9613 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9614 BaseEnd = ClassDecl->vbases_end();
9615 Base != BaseEnd; ++Base) {
9616 CXXRecordDecl *BaseClassDecl
9617 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9618 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009619 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009620 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009621 }
9622
9623 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9624 FieldEnd = ClassDecl->field_end();
9625 Field != FieldEnd;
9626 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009627 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009628 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009629 if (CXXMethodDecl *MoveAssign =
9630 LookupMovingAssignment(FieldClassDecl,
9631 FieldType.getCVRQualifiers(),
9632 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009633 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009634 }
9635 }
9636
9637 return ExceptSpec;
9638}
9639
Richard Smith1c931be2012-04-02 18:40:40 +00009640/// Determine whether the class type has any direct or indirect virtual base
9641/// classes which have a non-trivial move assignment operator.
9642static bool
9643hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9644 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9645 BaseEnd = ClassDecl->vbases_end();
9646 Base != BaseEnd; ++Base) {
9647 CXXRecordDecl *BaseClass =
9648 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9649
9650 // Try to declare the move assignment. If it would be deleted, then the
9651 // class does not have a non-trivial move assignment.
9652 if (BaseClass->needsImplicitMoveAssignment())
9653 S.DeclareImplicitMoveAssignment(BaseClass);
9654
Richard Smith426391c2012-11-16 00:53:38 +00009655 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009656 return true;
9657 }
9658
9659 return false;
9660}
9661
9662/// Determine whether the given type either has a move constructor or is
9663/// trivially copyable.
9664static bool
9665hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9666 Type = S.Context.getBaseElementType(Type);
9667
9668 // FIXME: Technically, non-trivially-copyable non-class types, such as
9669 // reference types, are supposed to return false here, but that appears
9670 // to be a standard defect.
9671 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009672 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009673 return true;
9674
9675 if (Type.isTriviallyCopyableType(S.Context))
9676 return true;
9677
9678 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009679 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9680 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009681 if (ClassDecl->needsImplicitMoveConstructor())
9682 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009683 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009684 }
9685
Richard Smithe5411b72012-12-01 02:35:44 +00009686 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9687 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009688 if (ClassDecl->needsImplicitMoveAssignment())
9689 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009690 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009691}
9692
9693/// Determine whether all non-static data members and direct or virtual bases
9694/// of class \p ClassDecl have either a move operation, or are trivially
9695/// copyable.
9696static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9697 bool IsConstructor) {
9698 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9699 BaseEnd = ClassDecl->bases_end();
9700 Base != BaseEnd; ++Base) {
9701 if (Base->isVirtual())
9702 continue;
9703
9704 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9705 return false;
9706 }
9707
9708 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9709 BaseEnd = ClassDecl->vbases_end();
9710 Base != BaseEnd; ++Base) {
9711 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9712 return false;
9713 }
9714
9715 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9716 FieldEnd = ClassDecl->field_end();
9717 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009718 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009719 return false;
9720 }
9721
9722 return true;
9723}
9724
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009725CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009726 // C++11 [class.copy]p20:
9727 // If the definition of a class X does not explicitly declare a move
9728 // assignment operator, one will be implicitly declared as defaulted
9729 // if and only if:
9730 //
9731 // - [first 4 bullets]
9732 assert(ClassDecl->needsImplicitMoveAssignment());
9733
Richard Smithafb49182012-11-29 01:34:07 +00009734 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9735 if (DSM.isAlreadyBeingDeclared())
9736 return 0;
9737
Richard Smith1c931be2012-04-02 18:40:40 +00009738 // [Checked after we build the declaration]
9739 // - the move assignment operator would not be implicitly defined as
9740 // deleted,
9741
9742 // [DR1402]:
9743 // - X has no direct or indirect virtual base class with a non-trivial
9744 // move assignment operator, and
9745 // - each of X's non-static data members and direct or virtual base classes
9746 // has a type that either has a move assignment operator or is trivially
9747 // copyable.
9748 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9749 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9750 ClassDecl->setFailedImplicitMoveAssignment();
9751 return 0;
9752 }
9753
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009754 // Note: The following rules are largely analoguous to the move
9755 // constructor rules.
9756
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009757 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9758 QualType RetType = Context.getLValueReferenceType(ArgType);
9759 ArgType = Context.getRValueReferenceType(ArgType);
9760
Richard Smitha8942d72013-05-07 03:19:20 +00009761 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9762 CXXMoveAssignment,
9763 false);
9764
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009765 // An implicitly-declared move assignment operator is an inline public
9766 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009767 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9768 SourceLocation ClassLoc = ClassDecl->getLocation();
9769 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009770 CXXMethodDecl *MoveAssignment =
9771 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9772 /*TInfo=*/0, /*StorageClass=*/SC_None,
9773 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009774 MoveAssignment->setAccess(AS_public);
9775 MoveAssignment->setDefaulted();
9776 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009777
Richard Smithb9d0b762012-07-27 04:22:15 +00009778 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009779 FunctionProtoType::ExtProtoInfo EPI =
9780 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009781 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009782
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009783 // Add the parameter to the operator.
9784 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9785 ClassLoc, ClassLoc, /*Id=*/0,
9786 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009787 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009788 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009789
Richard Smithbc2a35d2012-12-08 08:32:28 +00009790 AddOverriddenMethods(ClassDecl, MoveAssignment);
9791
9792 MoveAssignment->setTrivial(
9793 ClassDecl->needsOverloadResolutionForMoveAssignment()
9794 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9795 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009796
9797 // C++0x [class.copy]p9:
9798 // If the definition of a class X does not explicitly declare a move
9799 // assignment operator, one will be implicitly declared as defaulted if and
9800 // only if:
9801 // [...]
9802 // - the move assignment operator would not be implicitly defined as
9803 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009804 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009805 // Cache this result so that we don't try to generate this over and over
9806 // on every lookup, leaking memory and wasting time.
9807 ClassDecl->setFailedImplicitMoveAssignment();
9808 return 0;
9809 }
9810
Richard Smithbc2a35d2012-12-08 08:32:28 +00009811 // Note that we have added this copy-assignment operator.
9812 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9813
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009814 if (Scope *S = getScopeForContext(ClassDecl))
9815 PushOnScopeChains(MoveAssignment, S, false);
9816 ClassDecl->addDecl(MoveAssignment);
9817
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009818 return MoveAssignment;
9819}
9820
9821void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9822 CXXMethodDecl *MoveAssignOperator) {
9823 assert((MoveAssignOperator->isDefaulted() &&
9824 MoveAssignOperator->isOverloadedOperator() &&
9825 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009826 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9827 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009828 "DefineImplicitMoveAssignment called for wrong function");
9829
9830 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9831
9832 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9833 MoveAssignOperator->setInvalidDecl();
9834 return;
9835 }
9836
Eli Friedman86164e82013-09-05 00:02:25 +00009837 MoveAssignOperator->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009838
Eli Friedman9a14db32012-10-18 20:14:08 +00009839 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009840 DiagnosticErrorTrap Trap(Diags);
9841
9842 // C++0x [class.copy]p28:
9843 // The implicitly-defined or move assignment operator for a non-union class
9844 // X performs memberwise move assignment of its subobjects. The direct base
9845 // classes of X are assigned first, in the order of their declaration in the
9846 // base-specifier-list, and then the immediate non-static data members of X
9847 // are assigned, in the order in which they were declared in the class
9848 // definition.
9849
9850 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009851 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009852
9853 // The parameter for the "other" object, which we are move from.
9854 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9855 QualType OtherRefType = Other->getType()->
9856 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009857 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009858 "Bad argument type of defaulted move assignment");
9859
9860 // Our location for everything implicitly-generated.
9861 SourceLocation Loc = MoveAssignOperator->getLocation();
9862
Pavel Labath66ea35d2013-08-30 08:52:28 +00009863 // Builds a reference to the "other" object.
9864 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009865 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009866 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009867
Pavel Labath66ea35d2013-08-30 08:52:28 +00009868 // Builds the "this" pointer.
9869 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +00009870
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009871 // Assign base classes.
9872 bool Invalid = false;
9873 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9874 E = ClassDecl->bases_end(); Base != E; ++Base) {
9875 // Form the assignment:
9876 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9877 QualType BaseType = Base->getType().getUnqualifiedType();
9878 if (!BaseType->isRecordType()) {
9879 Invalid = true;
9880 continue;
9881 }
9882
9883 CXXCastPath BasePath;
9884 BasePath.push_back(Base);
9885
9886 // Construct the "from" expression, which is an implicit cast to the
9887 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009888 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009889
9890 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009891 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009892
9893 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009894 CastBuilder To(DerefThis,
9895 Context.getCVRQualifiedType(
9896 BaseType, MoveAssignOperator->getTypeQualifiers()),
9897 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009898
9899 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009900 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009901 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009902 /*CopyingBaseSubobject=*/true,
9903 /*Copying=*/false);
9904 if (Move.isInvalid()) {
9905 Diag(CurrentLocation, diag::note_member_synthesized_at)
9906 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9907 MoveAssignOperator->setInvalidDecl();
9908 return;
9909 }
9910
9911 // Success! Record the move.
9912 Statements.push_back(Move.takeAs<Expr>());
9913 }
9914
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009915 // Assign non-static members.
9916 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9917 FieldEnd = ClassDecl->field_end();
9918 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009919 if (Field->isUnnamedBitfield())
9920 continue;
9921
Eli Friedman8150da32013-06-07 01:48:56 +00009922 if (Field->isInvalidDecl()) {
9923 Invalid = true;
9924 continue;
9925 }
9926
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009927 // Check for members of reference type; we can't move those.
9928 if (Field->getType()->isReferenceType()) {
9929 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9930 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9931 Diag(Field->getLocation(), diag::note_declared_at);
9932 Diag(CurrentLocation, diag::note_member_synthesized_at)
9933 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9934 Invalid = true;
9935 continue;
9936 }
9937
9938 // Check for members of const-qualified, non-class type.
9939 QualType BaseType = Context.getBaseElementType(Field->getType());
9940 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9941 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9942 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9943 Diag(Field->getLocation(), diag::note_declared_at);
9944 Diag(CurrentLocation, diag::note_member_synthesized_at)
9945 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9946 Invalid = true;
9947 continue;
9948 }
9949
9950 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009951 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9952 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009953
9954 QualType FieldType = Field->getType().getNonReferenceType();
9955 if (FieldType->isIncompleteArrayType()) {
9956 assert(ClassDecl->hasFlexibleArrayMember() &&
9957 "Incomplete array type is not valid");
9958 continue;
9959 }
9960
9961 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009962 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9963 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009964 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009965 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009966 MemberBuilder From(MoveOther, OtherRefType,
9967 /*IsArrow=*/false, MemberLookup);
9968 MemberBuilder To(This, getCurrentThisType(),
9969 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009970
Pavel Labath66ea35d2013-08-30 08:52:28 +00009971 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009972 "Member reference with rvalue base must be rvalue except for reference "
9973 "members, which aren't allowed for move assignment.");
9974
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009975 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009976 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009977 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009978 /*CopyingBaseSubobject=*/false,
9979 /*Copying=*/false);
9980 if (Move.isInvalid()) {
9981 Diag(CurrentLocation, diag::note_member_synthesized_at)
9982 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9983 MoveAssignOperator->setInvalidDecl();
9984 return;
9985 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009986
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009987 // Success! Record the copy.
9988 Statements.push_back(Move.takeAs<Stmt>());
9989 }
9990
9991 if (!Invalid) {
9992 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009993 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009994
9995 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9996 if (Return.isInvalid())
9997 Invalid = true;
9998 else {
9999 Statements.push_back(Return.takeAs<Stmt>());
10000
10001 if (Trap.hasErrorOccurred()) {
10002 Diag(CurrentLocation, diag::note_member_synthesized_at)
10003 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
10004 Invalid = true;
10005 }
10006 }
10007 }
10008
10009 if (Invalid) {
10010 MoveAssignOperator->setInvalidDecl();
10011 return;
10012 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010013
10014 StmtResult Body;
10015 {
10016 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010017 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010018 /*isStmtExpr=*/false);
10019 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
10020 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010021 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
10022
10023 if (ASTMutationListener *L = getASTMutationListener()) {
10024 L->CompletedImplicitDefinition(MoveAssignOperator);
10025 }
10026}
10027
Richard Smithb9d0b762012-07-27 04:22:15 +000010028Sema::ImplicitExceptionSpecification
10029Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10030 CXXRecordDecl *ClassDecl = MD->getParent();
10031
10032 ImplicitExceptionSpecification ExceptSpec(*this);
10033 if (ClassDecl->isInvalidDecl())
10034 return ExceptSpec;
10035
10036 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10037 assert(T->getNumArgs() >= 1 && "not a copy ctor");
10038 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
10039
Douglas Gregor0d405db2010-07-01 20:59:04 +000010040 // C++ [except.spec]p14:
10041 // An implicitly declared special member function (Clause 12) shall have an
10042 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +000010043 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
10044 BaseEnd = ClassDecl->bases_end();
10045 Base != BaseEnd;
10046 ++Base) {
10047 // Virtual bases are handled below.
10048 if (Base->isVirtual())
10049 continue;
10050
Douglas Gregor22584312010-07-02 23:41:54 +000010051 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +000010052 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010053 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010054 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +000010055 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010056 }
10057 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
10058 BaseEnd = ClassDecl->vbases_end();
10059 Base != BaseEnd;
10060 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +000010061 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +000010062 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010063 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010064 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +000010065 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010066 }
10067 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
10068 FieldEnd = ClassDecl->field_end();
10069 Field != FieldEnd;
10070 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +000010071 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +000010072 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10073 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +000010074 LookupCopyingConstructor(FieldClassDecl,
10075 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +000010076 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010077 }
10078 }
Sebastian Redl60618fa2011-03-12 11:50:43 +000010079
Richard Smithb9d0b762012-07-27 04:22:15 +000010080 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +000010081}
10082
10083CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10084 CXXRecordDecl *ClassDecl) {
10085 // C++ [class.copy]p4:
10086 // If the class definition does not explicitly declare a copy
10087 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +000010088 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +000010089
Richard Smithafb49182012-11-29 01:34:07 +000010090 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10091 if (DSM.isAlreadyBeingDeclared())
10092 return 0;
10093
Sean Hunt49634cf2011-05-13 06:10:58 +000010094 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10095 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +000010096 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +000010097 if (Const)
10098 ArgType = ArgType.withConst();
10099 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +000010100
Richard Smith7756afa2012-06-10 05:43:50 +000010101 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10102 CXXCopyConstructor,
10103 Const);
10104
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010105 DeclarationName Name
10106 = Context.DeclarationNames.getCXXConstructorName(
10107 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010108 SourceLocation ClassLoc = ClassDecl->getLocation();
10109 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +000010110
10111 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010112 // member of its class.
10113 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010114 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010115 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010116 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010117 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +000010118 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010119
Richard Smithb9d0b762012-07-27 04:22:15 +000010120 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010121 FunctionProtoType::ExtProtoInfo EPI =
10122 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010123 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010124 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010125
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010126 // Add the parameter to the constructor.
10127 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010128 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010129 /*IdentifierInfo=*/0,
10130 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +000010131 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010132 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +000010133
Richard Smithbc2a35d2012-12-08 08:32:28 +000010134 CopyConstructor->setTrivial(
10135 ClassDecl->needsOverloadResolutionForCopyConstructor()
10136 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10137 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +000010138
Nico Weberafcc96a2012-01-23 03:19:29 +000010139 // C++11 [class.copy]p8:
10140 // ... If the class definition does not explicitly declare a copy
10141 // constructor, there is no user-declared move constructor, and there is no
10142 // user-declared move assignment operator, a copy constructor is implicitly
10143 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +000010144 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +000010145 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +000010146
Richard Smithbc2a35d2012-12-08 08:32:28 +000010147 // Note that we have declared this constructor.
10148 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10149
10150 if (Scope *S = getScopeForContext(ClassDecl))
10151 PushOnScopeChains(CopyConstructor, S, false);
10152 ClassDecl->addDecl(CopyConstructor);
10153
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010154 return CopyConstructor;
10155}
10156
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010157void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +000010158 CXXConstructorDecl *CopyConstructor) {
10159 assert((CopyConstructor->isDefaulted() &&
10160 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010161 !CopyConstructor->doesThisDeclarationHaveABody() &&
10162 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010163 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +000010164
Anders Carlsson63010a72010-04-23 16:24:12 +000010165 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010166 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010167
Richard Smith36155c12013-06-13 03:23:42 +000010168 // C++11 [class.copy]p7:
Benjamin Kramere5753592013-09-09 14:48:42 +000010169 // The [definition of an implicitly declared copy constructor] is
Richard Smith36155c12013-06-13 03:23:42 +000010170 // deprecated if the class has a user-declared copy assignment operator
10171 // or a user-declared destructor.
10172 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10173 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10174
Eli Friedman9a14db32012-10-18 20:14:08 +000010175 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +000010176 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010177
David Blaikie93c86172013-01-17 05:26:25 +000010178 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +000010179 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +000010180 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010181 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +000010182 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010183 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010184 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010185 CopyConstructor->setBody(ActOnCompoundStmt(
10186 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10187 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +000010188 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010189
Eli Friedman86164e82013-09-05 00:02:25 +000010190 CopyConstructor->markUsed(Context);
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010191 if (ASTMutationListener *L = getASTMutationListener()) {
10192 L->CompletedImplicitDefinition(CopyConstructor);
10193 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010194}
10195
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010196Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010197Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10198 CXXRecordDecl *ClassDecl = MD->getParent();
10199
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010200 // C++ [except.spec]p14:
10201 // An implicitly declared special member function (Clause 12) shall have an
10202 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +000010203 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010204 if (ClassDecl->isInvalidDecl())
10205 return ExceptSpec;
10206
10207 // Direct base-class constructors.
10208 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10209 BEnd = ClassDecl->bases_end();
10210 B != BEnd; ++B) {
10211 if (B->isVirtual()) // Handled below.
10212 continue;
10213
10214 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10215 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010216 CXXConstructorDecl *Constructor =
10217 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010218 // If this is a deleted function, add it anyway. This might be conformant
10219 // with the standard. This might not. I'm not sure. It might not matter.
10220 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010221 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010222 }
10223 }
10224
10225 // Virtual base-class constructors.
10226 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10227 BEnd = ClassDecl->vbases_end();
10228 B != BEnd; ++B) {
10229 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10230 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010231 CXXConstructorDecl *Constructor =
10232 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010233 // If this is a deleted function, add it anyway. This might be conformant
10234 // with the standard. This might not. I'm not sure. It might not matter.
10235 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010236 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010237 }
10238 }
10239
10240 // Field constructors.
10241 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10242 FEnd = ClassDecl->field_end();
10243 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010244 QualType FieldType = Context.getBaseElementType(F->getType());
10245 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10246 CXXConstructorDecl *Constructor =
10247 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010248 // If this is a deleted function, add it anyway. This might be conformant
10249 // with the standard. This might not. I'm not sure. It might not matter.
10250 // In particular, the problem is that this function never gets called. It
10251 // might just be ill-formed because this function attempts to refer to
10252 // a deleted function here.
10253 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010254 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010255 }
10256 }
10257
10258 return ExceptSpec;
10259}
10260
10261CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10262 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010263 // C++11 [class.copy]p9:
10264 // If the definition of a class X does not explicitly declare a move
10265 // constructor, one will be implicitly declared as defaulted if and only if:
10266 //
10267 // - [first 4 bullets]
10268 assert(ClassDecl->needsImplicitMoveConstructor());
10269
Richard Smithafb49182012-11-29 01:34:07 +000010270 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10271 if (DSM.isAlreadyBeingDeclared())
10272 return 0;
10273
Richard Smith1c931be2012-04-02 18:40:40 +000010274 // [Checked after we build the declaration]
10275 // - the move assignment operator would not be implicitly defined as
10276 // deleted,
10277
10278 // [DR1402]:
10279 // - each of X's non-static data members and direct or virtual base classes
10280 // has a type that either has a move constructor or is trivially copyable.
10281 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
10282 ClassDecl->setFailedImplicitMoveConstructor();
10283 return 0;
10284 }
10285
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010286 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10287 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010288
Richard Smith7756afa2012-06-10 05:43:50 +000010289 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10290 CXXMoveConstructor,
10291 false);
10292
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010293 DeclarationName Name
10294 = Context.DeclarationNames.getCXXConstructorName(
10295 Context.getCanonicalType(ClassType));
10296 SourceLocation ClassLoc = ClassDecl->getLocation();
10297 DeclarationNameInfo NameInfo(Name, ClassLoc);
10298
Richard Smitha8942d72013-05-07 03:19:20 +000010299 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010300 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010301 // member of its class.
10302 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010303 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010304 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010305 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010306 MoveConstructor->setAccess(AS_public);
10307 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010308
Richard Smithb9d0b762012-07-27 04:22:15 +000010309 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010310 FunctionProtoType::ExtProtoInfo EPI =
10311 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010312 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010313 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010314
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010315 // Add the parameter to the constructor.
10316 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10317 ClassLoc, ClassLoc,
10318 /*IdentifierInfo=*/0,
10319 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010320 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010321 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010322
Richard Smithbc2a35d2012-12-08 08:32:28 +000010323 MoveConstructor->setTrivial(
10324 ClassDecl->needsOverloadResolutionForMoveConstructor()
10325 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10326 : ClassDecl->hasTrivialMoveConstructor());
10327
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010328 // C++0x [class.copy]p9:
10329 // If the definition of a class X does not explicitly declare a move
10330 // constructor, one will be implicitly declared as defaulted if and only if:
10331 // [...]
10332 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +000010333 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010334 // Cache this result so that we don't try to generate this over and over
10335 // on every lookup, leaking memory and wasting time.
10336 ClassDecl->setFailedImplicitMoveConstructor();
10337 return 0;
10338 }
10339
10340 // Note that we have declared this constructor.
10341 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10342
10343 if (Scope *S = getScopeForContext(ClassDecl))
10344 PushOnScopeChains(MoveConstructor, S, false);
10345 ClassDecl->addDecl(MoveConstructor);
10346
10347 return MoveConstructor;
10348}
10349
10350void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10351 CXXConstructorDecl *MoveConstructor) {
10352 assert((MoveConstructor->isDefaulted() &&
10353 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010354 !MoveConstructor->doesThisDeclarationHaveABody() &&
10355 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010356 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10357
10358 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10359 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10360
Eli Friedman9a14db32012-10-18 20:14:08 +000010361 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010362 DiagnosticErrorTrap Trap(Diags);
10363
David Blaikie93c86172013-01-17 05:26:25 +000010364 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010365 Trap.hasErrorOccurred()) {
10366 Diag(CurrentLocation, diag::note_member_synthesized_at)
10367 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10368 MoveConstructor->setInvalidDecl();
10369 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010370 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010371 MoveConstructor->setBody(ActOnCompoundStmt(
10372 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10373 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010374 }
10375
Eli Friedman86164e82013-09-05 00:02:25 +000010376 MoveConstructor->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010377
10378 if (ASTMutationListener *L = getASTMutationListener()) {
10379 L->CompletedImplicitDefinition(MoveConstructor);
10380 }
10381}
10382
Douglas Gregore4e68d42012-02-15 19:33:52 +000010383bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010384 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010385}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010386
10387void Sema::DefineImplicitLambdaToFunctionPointerConversion(
Faisal Valid6992ab2013-09-29 08:45:24 +000010388 SourceLocation CurrentLocation,
10389 CXXConversionDecl *Conv) {
10390 CXXRecordDecl *Lambda = Conv->getParent();
10391 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10392 // If we are defining a specialization of a conversion to function-ptr
10393 // cache the deduced template arguments for this specialization
10394 // so that we can use them to retrieve the corresponding call-operator
10395 // and static-invoker.
10396 const TemplateArgumentList *DeducedTemplateArgs = 0;
10397
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010398
Faisal Valid6992ab2013-09-29 08:45:24 +000010399 // Retrieve the corresponding call-operator specialization.
10400 if (Lambda->isGenericLambda()) {
10401 assert(Conv->isFunctionTemplateSpecialization());
10402 FunctionTemplateDecl *CallOpTemplate =
10403 CallOp->getDescribedFunctionTemplate();
10404 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10405 void *InsertPos = 0;
10406 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10407 DeducedTemplateArgs->data(),
10408 DeducedTemplateArgs->size(),
10409 InsertPos);
10410 assert(CallOpSpec &&
10411 "Conversion operator must have a corresponding call operator");
10412 CallOp = cast<CXXMethodDecl>(CallOpSpec);
10413 }
10414 // Mark the call operator referenced (and add to pending instantiations
10415 // if necessary).
10416 // For both the conversion and static-invoker template specializations
10417 // we construct their body's in this function, so no need to add them
10418 // to the PendingInstantiations.
10419 MarkFunctionReferenced(CurrentLocation, CallOp);
10420
Eli Friedman9a14db32012-10-18 20:14:08 +000010421 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010422 DiagnosticErrorTrap Trap(Diags);
Faisal Valid6992ab2013-09-29 08:45:24 +000010423
10424 // Retreive the static invoker...
10425 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10426 // ... and get the corresponding specialization for a generic lambda.
10427 if (Lambda->isGenericLambda()) {
10428 assert(DeducedTemplateArgs &&
10429 "Must have deduced template arguments from Conversion Operator");
10430 FunctionTemplateDecl *InvokeTemplate =
10431 Invoker->getDescribedFunctionTemplate();
10432 void *InsertPos = 0;
10433 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10434 DeducedTemplateArgs->data(),
10435 DeducedTemplateArgs->size(),
10436 InsertPos);
10437 assert(InvokeSpec &&
10438 "Must have a corresponding static invoker specialization");
10439 Invoker = cast<CXXMethodDecl>(InvokeSpec);
10440 }
10441 // Construct the body of the conversion function { return __invoke; }.
10442 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10443 VK_LValue, Conv->getLocation()).take();
10444 assert(FunctionRef && "Can't refer to __invoke function?");
10445 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10446 Conv->setBody(new (Context) CompoundStmt(Context, Return,
10447 Conv->getLocation(),
10448 Conv->getLocation()));
10449
10450 Conv->markUsed(Context);
10451 Conv->setReferenced();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010452
Faisal Valid6992ab2013-09-29 08:45:24 +000010453 // Fill in the __invoke function with a dummy implementation. IR generation
10454 // will fill in the actual details.
10455 Invoker->markUsed(Context);
10456 Invoker->setReferenced();
10457 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10458
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010459 if (ASTMutationListener *L = getASTMutationListener()) {
10460 L->CompletedImplicitDefinition(Conv);
Faisal Valid6992ab2013-09-29 08:45:24 +000010461 L->CompletedImplicitDefinition(Invoker);
10462 }
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010463}
10464
Faisal Valid6992ab2013-09-29 08:45:24 +000010465
10466
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010467void Sema::DefineImplicitLambdaToBlockPointerConversion(
10468 SourceLocation CurrentLocation,
10469 CXXConversionDecl *Conv)
10470{
Faisal Vali56fe35b2013-09-29 17:08:32 +000010471 assert(!Conv->getParent()->isGenericLambda());
Faisal Valid6992ab2013-09-29 08:45:24 +000010472
Eli Friedman86164e82013-09-05 00:02:25 +000010473 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010474
Eli Friedman9a14db32012-10-18 20:14:08 +000010475 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010476 DiagnosticErrorTrap Trap(Diags);
10477
Douglas Gregorac1303e2012-02-22 05:02:47 +000010478 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010479 Expr *This = ActOnCXXThis(CurrentLocation).take();
10480 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010481
Eli Friedman23f02672012-03-01 04:01:32 +000010482 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10483 Conv->getLocation(),
10484 Conv, DerefThis);
10485
10486 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10487 // behavior. Note that only the general conversion function does this
10488 // (since it's unusable otherwise); in the case where we inline the
10489 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010490 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010491 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10492 CK_CopyAndAutoreleaseBlockObject,
10493 BuildBlock.get(), 0, VK_RValue);
10494
10495 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010496 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010497 Conv->setInvalidDecl();
10498 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010499 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010500
Douglas Gregorac1303e2012-02-22 05:02:47 +000010501 // Create the return statement that returns the block from the conversion
10502 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010503 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010504 if (Return.isInvalid()) {
10505 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10506 Conv->setInvalidDecl();
10507 return;
10508 }
10509
10510 // Set the body of the conversion function.
10511 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010512 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010513 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010514 Conv->getLocation()));
10515
Douglas Gregorac1303e2012-02-22 05:02:47 +000010516 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010517 if (ASTMutationListener *L = getASTMutationListener()) {
10518 L->CompletedImplicitDefinition(Conv);
10519 }
10520}
10521
Douglas Gregorf52757d2012-03-10 06:53:13 +000010522/// \brief Determine whether the given list arguments contains exactly one
10523/// "real" (non-default) argument.
10524static bool hasOneRealArgument(MultiExprArg Args) {
10525 switch (Args.size()) {
10526 case 0:
10527 return false;
10528
10529 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010530 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010531 return false;
10532
10533 // fall through
10534 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010535 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010536 }
10537
10538 return false;
10539}
10540
John McCall60d7b3a2010-08-24 06:29:42 +000010541ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010542Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010543 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010544 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010545 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010546 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010547 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010548 unsigned ConstructKind,
10549 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010550 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010551
Douglas Gregor2f599792010-04-02 18:24:57 +000010552 // C++0x [class.copy]p34:
10553 // When certain criteria are met, an implementation is allowed to
10554 // omit the copy/move construction of a class object, even if the
10555 // copy/move constructor and/or destructor for the object have
10556 // side effects. [...]
10557 // - when a temporary class object that has not been bound to a
10558 // reference (12.2) would be copied/moved to a class object
10559 // with the same cv-unqualified type, the copy/move operation
10560 // can be omitted by constructing the temporary object
10561 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010562 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010563 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010564 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010565 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010566 }
Mike Stump1eb44332009-09-09 15:08:12 +000010567
10568 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010569 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010570 IsListInitialization, RequiresZeroInit,
10571 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010572}
10573
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010574/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10575/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010576ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010577Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10578 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010579 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010580 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010581 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010582 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010583 unsigned ConstructKind,
10584 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010585 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010586 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010587 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010588 HadMultipleCandidates,
10589 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010590 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10591 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010592}
10593
John McCall68c6c9a2010-02-02 09:10:11 +000010594void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010595 if (VD->isInvalidDecl()) return;
10596
John McCall68c6c9a2010-02-02 09:10:11 +000010597 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010598 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010599 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010600 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010601
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010602 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010603 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010604 CheckDestructorAccess(VD->getLocation(), Destructor,
10605 PDiag(diag::err_access_dtor_var)
10606 << VD->getDeclName()
10607 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010608 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010609
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010610 if (!VD->hasGlobalStorage()) return;
10611
10612 // Emit warning for non-trivial dtor in global scope (a real global,
10613 // class-static, function-static).
10614 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10615
10616 // TODO: this should be re-enabled for static locals by !CXAAtExit
10617 if (!VD->isStaticLocal())
10618 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010619}
10620
Douglas Gregor39da0b82009-09-09 23:08:42 +000010621/// \brief Given a constructor and the set of arguments provided for the
10622/// constructor, convert the arguments and add any required default arguments
10623/// to form a proper call to this constructor.
10624///
10625/// \returns true if an error occurred, false otherwise.
10626bool
10627Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10628 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010629 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010630 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010631 bool AllowExplicit,
10632 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010633 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10634 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010635 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010636
10637 const FunctionProtoType *Proto
10638 = Constructor->getType()->getAs<FunctionProtoType>();
10639 assert(Proto && "Constructor without a prototype?");
10640 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010641
10642 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010643 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010644 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010645 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010646 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010647
10648 VariadicCallType CallType =
10649 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010650 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010651 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010652 Proto, 0,
10653 llvm::makeArrayRef(Args, NumArgs),
10654 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010655 CallType, AllowExplicit,
10656 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010657 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010658
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010659 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010660
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010661 CheckConstructorCall(Constructor,
10662 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10663 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010664 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010665
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010666 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010667}
10668
Anders Carlsson20d45d22009-12-12 00:32:00 +000010669static inline bool
10670CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10671 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010672 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010673 if (isa<NamespaceDecl>(DC)) {
10674 return SemaRef.Diag(FnDecl->getLocation(),
10675 diag::err_operator_new_delete_declared_in_namespace)
10676 << FnDecl->getDeclName();
10677 }
10678
10679 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010680 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010681 return SemaRef.Diag(FnDecl->getLocation(),
10682 diag::err_operator_new_delete_declared_static)
10683 << FnDecl->getDeclName();
10684 }
10685
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010686 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010687}
10688
Anders Carlsson156c78e2009-12-13 17:53:43 +000010689static inline bool
10690CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10691 CanQualType ExpectedResultType,
10692 CanQualType ExpectedFirstParamType,
10693 unsigned DependentParamTypeDiag,
10694 unsigned InvalidParamTypeDiag) {
10695 QualType ResultType =
10696 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10697
10698 // Check that the result type is not dependent.
10699 if (ResultType->isDependentType())
10700 return SemaRef.Diag(FnDecl->getLocation(),
10701 diag::err_operator_new_delete_dependent_result_type)
10702 << FnDecl->getDeclName() << ExpectedResultType;
10703
10704 // Check that the result type is what we expect.
10705 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10706 return SemaRef.Diag(FnDecl->getLocation(),
10707 diag::err_operator_new_delete_invalid_result_type)
10708 << FnDecl->getDeclName() << ExpectedResultType;
10709
10710 // A function template must have at least 2 parameters.
10711 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10712 return SemaRef.Diag(FnDecl->getLocation(),
10713 diag::err_operator_new_delete_template_too_few_parameters)
10714 << FnDecl->getDeclName();
10715
10716 // The function decl must have at least 1 parameter.
10717 if (FnDecl->getNumParams() == 0)
10718 return SemaRef.Diag(FnDecl->getLocation(),
10719 diag::err_operator_new_delete_too_few_parameters)
10720 << FnDecl->getDeclName();
10721
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010722 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010723 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10724 if (FirstParamType->isDependentType())
10725 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10726 << FnDecl->getDeclName() << ExpectedFirstParamType;
10727
10728 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010729 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010730 ExpectedFirstParamType)
10731 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10732 << FnDecl->getDeclName() << ExpectedFirstParamType;
10733
10734 return false;
10735}
10736
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010737static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010738CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010739 // C++ [basic.stc.dynamic.allocation]p1:
10740 // A program is ill-formed if an allocation function is declared in a
10741 // namespace scope other than global scope or declared static in global
10742 // scope.
10743 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10744 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010745
10746 CanQualType SizeTy =
10747 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10748
10749 // C++ [basic.stc.dynamic.allocation]p1:
10750 // The return type shall be void*. The first parameter shall have type
10751 // std::size_t.
10752 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10753 SizeTy,
10754 diag::err_operator_new_dependent_param_type,
10755 diag::err_operator_new_param_type))
10756 return true;
10757
10758 // C++ [basic.stc.dynamic.allocation]p1:
10759 // The first parameter shall not have an associated default argument.
10760 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010761 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010762 diag::err_operator_new_default_arg)
10763 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10764
10765 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010766}
10767
10768static bool
Richard Smith444d3842012-10-20 08:26:51 +000010769CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010770 // C++ [basic.stc.dynamic.deallocation]p1:
10771 // A program is ill-formed if deallocation functions are declared in a
10772 // namespace scope other than global scope or declared static in global
10773 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010774 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10775 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010776
10777 // C++ [basic.stc.dynamic.deallocation]p2:
10778 // Each deallocation function shall return void and its first parameter
10779 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010780 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10781 SemaRef.Context.VoidPtrTy,
10782 diag::err_operator_delete_dependent_param_type,
10783 diag::err_operator_delete_param_type))
10784 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010785
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010786 return false;
10787}
10788
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010789/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10790/// of this overloaded operator is well-formed. If so, returns false;
10791/// otherwise, emits appropriate diagnostics and returns true.
10792bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010793 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010794 "Expected an overloaded operator declaration");
10795
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010796 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10797
Mike Stump1eb44332009-09-09 15:08:12 +000010798 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010799 // The allocation and deallocation functions, operator new,
10800 // operator new[], operator delete and operator delete[], are
10801 // described completely in 3.7.3. The attributes and restrictions
10802 // found in the rest of this subclause do not apply to them unless
10803 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010804 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010805 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010806
Anders Carlssona3ccda52009-12-12 00:26:23 +000010807 if (Op == OO_New || Op == OO_Array_New)
10808 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010809
10810 // C++ [over.oper]p6:
10811 // An operator function shall either be a non-static member
10812 // function or be a non-member function and have at least one
10813 // parameter whose type is a class, a reference to a class, an
10814 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010815 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10816 if (MethodDecl->isStatic())
10817 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010818 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010819 } else {
10820 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010821 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10822 ParamEnd = FnDecl->param_end();
10823 Param != ParamEnd; ++Param) {
10824 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010825 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10826 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010827 ClassOrEnumParam = true;
10828 break;
10829 }
10830 }
10831
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010832 if (!ClassOrEnumParam)
10833 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010834 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010835 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010836 }
10837
10838 // C++ [over.oper]p8:
10839 // An operator function cannot have default arguments (8.3.6),
10840 // except where explicitly stated below.
10841 //
Mike Stump1eb44332009-09-09 15:08:12 +000010842 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010843 // (C++ [over.call]p1).
10844 if (Op != OO_Call) {
10845 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10846 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010847 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010848 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010849 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010850 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010851 }
10852 }
10853
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010854 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10855 { false, false, false }
10856#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10857 , { Unary, Binary, MemberOnly }
10858#include "clang/Basic/OperatorKinds.def"
10859 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010860
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010861 bool CanBeUnaryOperator = OperatorUses[Op][0];
10862 bool CanBeBinaryOperator = OperatorUses[Op][1];
10863 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010864
10865 // C++ [over.oper]p8:
10866 // [...] Operator functions cannot have more or fewer parameters
10867 // than the number required for the corresponding operator, as
10868 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010869 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010870 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010871 if (Op != OO_Call &&
10872 ((NumParams == 1 && !CanBeUnaryOperator) ||
10873 (NumParams == 2 && !CanBeBinaryOperator) ||
10874 (NumParams < 1) || (NumParams > 2))) {
10875 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010876 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010877 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010878 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010879 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010880 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010881 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010882 assert(CanBeBinaryOperator &&
10883 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010884 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010885 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010886
Chris Lattner416e46f2008-11-21 07:57:12 +000010887 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010888 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010889 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010890
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010891 // Overloaded operators other than operator() cannot be variadic.
10892 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010893 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010894 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010895 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010896 }
10897
10898 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010899 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10900 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010901 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010902 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010903 }
10904
10905 // C++ [over.inc]p1:
10906 // The user-defined function called operator++ implements the
10907 // prefix and postfix ++ operator. If this function is a member
10908 // function with no parameters, or a non-member function with one
10909 // parameter of class or enumeration type, it defines the prefix
10910 // increment operator ++ for objects of that type. If the function
10911 // is a member function with one parameter (which shall be of type
10912 // int) or a non-member function with two parameters (the second
10913 // of which shall be of type int), it defines the postfix
10914 // increment operator ++ for objects of that type.
10915 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10916 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10917 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010918 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010919 ParamIsInt = BT->getKind() == BuiltinType::Int;
10920
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010921 if (!ParamIsInt)
10922 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010923 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010924 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010925 }
10926
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010927 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010928}
Chris Lattner5a003a42008-12-17 07:09:26 +000010929
Sean Hunta6c058d2010-01-13 09:01:02 +000010930/// CheckLiteralOperatorDeclaration - Check whether the declaration
10931/// of this literal operator function is well-formed. If so, returns
10932/// false; otherwise, emits appropriate diagnostics and returns true.
10933bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010934 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010935 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10936 << FnDecl->getDeclName();
10937 return true;
10938 }
10939
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010940 if (FnDecl->isExternC()) {
10941 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10942 return true;
10943 }
10944
Sean Hunta6c058d2010-01-13 09:01:02 +000010945 bool Valid = false;
10946
Richard Smith36f5cfe2012-03-09 08:00:36 +000010947 // This might be the definition of a literal operator template.
10948 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10949 // This might be a specialization of a literal operator template.
10950 if (!TpDecl)
10951 TpDecl = FnDecl->getPrimaryTemplate();
10952
Richard Smithb328e292013-10-07 19:57:58 +000010953 // template <char...> type operator "" name() and
10954 // template <class T, T...> type operator "" name() are the only valid
10955 // template signatures, and the only valid signatures with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010956 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010957 if (FnDecl->param_size() == 0) {
Richard Smithb328e292013-10-07 19:57:58 +000010958 // Must have one or two template parameters
Sean Hunt216c2782010-04-07 23:11:06 +000010959 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10960 if (Params->size() == 1) {
10961 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010962 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010963
Sean Hunt216c2782010-04-07 23:11:06 +000010964 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010965 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10966 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10967 Valid = true;
Richard Smithb328e292013-10-07 19:57:58 +000010968 } else if (Params->size() == 2) {
10969 TemplateTypeParmDecl *PmType =
10970 dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10971 NonTypeTemplateParmDecl *PmArgs =
10972 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10973
10974 // The second template parameter must be a parameter pack with the
10975 // first template parameter as its type.
10976 if (PmType && PmArgs &&
10977 !PmType->isTemplateParameterPack() &&
10978 PmArgs->isTemplateParameterPack()) {
10979 const TemplateTypeParmType *TArgs =
10980 PmArgs->getType()->getAs<TemplateTypeParmType>();
10981 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10982 TArgs->getIndex() == PmType->getIndex()) {
10983 Valid = true;
10984 if (ActiveTemplateInstantiations.empty())
10985 Diag(FnDecl->getLocation(),
10986 diag::ext_string_literal_operator_template);
10987 }
10988 }
Sean Hunt216c2782010-04-07 23:11:06 +000010989 }
10990 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010991 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010992 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010993 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10994
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010995 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010996
Sean Hunt30019c02010-04-07 22:57:35 +000010997 // unsigned long long int, long double, and any character type are allowed
10998 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010999 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
11000 Context.hasSameType(T, Context.LongDoubleTy) ||
11001 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000011002 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000011003 Context.hasSameType(T, Context.Char16Ty) ||
11004 Context.hasSameType(T, Context.Char32Ty)) {
11005 if (++Param == FnDecl->param_end())
11006 Valid = true;
11007 goto FinishedParams;
11008 }
11009
Sean Hunt30019c02010-04-07 22:57:35 +000011010 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000011011 const PointerType *PT = T->getAs<PointerType>();
11012 if (!PT)
11013 goto FinishedParams;
11014 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000011015 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000011016 goto FinishedParams;
11017 T = T.getUnqualifiedType();
11018
11019 // Move on to the second parameter;
11020 ++Param;
11021
11022 // If there is no second parameter, the first must be a const char *
11023 if (Param == FnDecl->param_end()) {
11024 if (Context.hasSameType(T, Context.CharTy))
11025 Valid = true;
11026 goto FinishedParams;
11027 }
11028
11029 // const char *, const wchar_t*, const char16_t*, and const char32_t*
11030 // are allowed as the first parameter to a two-parameter function
11031 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000011032 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000011033 Context.hasSameType(T, Context.Char16Ty) ||
11034 Context.hasSameType(T, Context.Char32Ty)))
11035 goto FinishedParams;
11036
11037 // The second and final parameter must be an std::size_t
11038 T = (*Param)->getType().getUnqualifiedType();
11039 if (Context.hasSameType(T, Context.getSizeType()) &&
11040 ++Param == FnDecl->param_end())
11041 Valid = true;
11042 }
11043
11044 // FIXME: This diagnostic is absolutely terrible.
11045FinishedParams:
11046 if (!Valid) {
11047 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
11048 << FnDecl->getDeclName();
11049 return true;
11050 }
11051
Richard Smitha9e88b22012-03-09 08:16:22 +000011052 // A parameter-declaration-clause containing a default argument is not
11053 // equivalent to any of the permitted forms.
11054 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
11055 ParamEnd = FnDecl->param_end();
11056 Param != ParamEnd; ++Param) {
11057 if ((*Param)->hasDefaultArg()) {
11058 Diag((*Param)->getDefaultArgRange().getBegin(),
11059 diag::err_literal_operator_default_argument)
11060 << (*Param)->getDefaultArgRange();
11061 break;
11062 }
11063 }
11064
Richard Smith2fb4ae32012-03-08 02:39:21 +000011065 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000011066 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
11067 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000011068 // C++11 [usrlit.suffix]p1:
11069 // Literal suffix identifiers that do not start with an underscore
11070 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000011071 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
11072 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000011073 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000011074
Sean Hunta6c058d2010-01-13 09:01:02 +000011075 return false;
11076}
11077
Douglas Gregor074149e2009-01-05 19:45:36 +000011078/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11079/// linkage specification, including the language and (if present)
11080/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
11081/// the location of the language string literal, which is provided
11082/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
11083/// the '{' brace. Otherwise, this linkage specification does not
11084/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000011085Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11086 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011087 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000011088 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000011089 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000011090 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011091 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000011092 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011093 Language = LinkageSpecDecl::lang_cxx;
11094 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000011095 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000011096 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011097 }
Mike Stump1eb44332009-09-09 15:08:12 +000011098
Chris Lattnercc98eac2008-12-17 07:13:27 +000011099 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000011100
Douglas Gregor074149e2009-01-05 19:45:36 +000011101 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000011102 ExternLoc, LangLoc, Language,
11103 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011104 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000011105 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000011106 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011107}
11108
Abramo Bagnara35f9a192010-07-30 16:47:02 +000011109/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000011110/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11111/// valid, it's the position of the closing '}' brace in a linkage
11112/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000011113Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011114 Decl *LinkageSpec,
11115 SourceLocation RBraceLoc) {
11116 if (LinkageSpec) {
11117 if (RBraceLoc.isValid()) {
11118 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11119 LSDecl->setRBraceLoc(RBraceLoc);
11120 }
Douglas Gregor074149e2009-01-05 19:45:36 +000011121 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011122 }
Douglas Gregor074149e2009-01-05 19:45:36 +000011123 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000011124}
11125
Michael Han684aa732013-02-22 17:15:32 +000011126Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11127 AttributeList *AttrList,
11128 SourceLocation SemiLoc) {
11129 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11130 // Attribute declarations appertain to empty declaration so we handle
11131 // them here.
11132 if (AttrList)
11133 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000011134
Michael Han684aa732013-02-22 17:15:32 +000011135 CurContext->addDecl(ED);
11136 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000011137}
11138
Douglas Gregord308e622009-05-18 20:51:54 +000011139/// \brief Perform semantic analysis for the variable declaration that
11140/// occurs within a C++ catch clause, returning the newly-created
11141/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011142VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000011143 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011144 SourceLocation StartLoc,
11145 SourceLocation Loc,
11146 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000011147 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000011148 QualType ExDeclType = TInfo->getType();
11149
Sebastian Redl4b07b292008-12-22 19:15:10 +000011150 // Arrays and functions decay.
11151 if (ExDeclType->isArrayType())
11152 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11153 else if (ExDeclType->isFunctionType())
11154 ExDeclType = Context.getPointerType(ExDeclType);
11155
11156 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11157 // The exception-declaration shall not denote a pointer or reference to an
11158 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011159 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000011160 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000011161 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011162 Invalid = true;
11163 }
Douglas Gregord308e622009-05-18 20:51:54 +000011164
Sebastian Redl4b07b292008-12-22 19:15:10 +000011165 QualType BaseType = ExDeclType;
11166 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000011167 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000011168 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011169 BaseType = Ptr->getPointeeType();
11170 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011171 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000011172 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011173 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011174 BaseType = Ref->getPointeeType();
11175 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011176 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011177 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011178 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000011179 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000011180 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011181
Mike Stump1eb44332009-09-09 15:08:12 +000011182 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000011183 RequireNonAbstractType(Loc, ExDeclType,
11184 diag::err_abstract_type_in_decl,
11185 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000011186 Invalid = true;
11187
John McCall5a180392010-07-24 00:37:23 +000011188 // Only the non-fragile NeXT runtime currently supports C++ catches
11189 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000011190 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000011191 QualType T = ExDeclType;
11192 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11193 T = RT->getPointeeType();
11194
11195 if (T->isObjCObjectType()) {
11196 Diag(Loc, diag::err_objc_object_catch);
11197 Invalid = true;
11198 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000011199 // FIXME: should this be a test for macosx-fragile specifically?
11200 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000011201 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000011202 }
11203 }
11204
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011205 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000011206 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000011207 ExDecl->setExceptionVariable(true);
11208
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011209 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011210 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011211 Invalid = true;
11212
Douglas Gregorc41b8782011-07-06 18:14:43 +000011213 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000011214 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000011215 // Insulate this from anything else we might currently be parsing.
11216 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11217
Douglas Gregor6d182892010-03-05 23:38:39 +000011218 // C++ [except.handle]p16:
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011219 // The object declared in an exception-declaration or, if the
11220 // exception-declaration does not specify a name, a temporary (12.2) is
Douglas Gregor6d182892010-03-05 23:38:39 +000011221 // copy-initialized (8.5) from the exception object. [...]
11222 // The object is destroyed when the handler exits, after the destruction
11223 // of any automatic objects initialized within the handler.
11224 //
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011225 // We just pretend to initialize the object with itself, then make sure
Douglas Gregor6d182892010-03-05 23:38:39 +000011226 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000011227 QualType initType = ExDeclType;
11228
11229 InitializedEntity entity =
11230 InitializedEntity::InitializeVariable(ExDecl);
11231 InitializationKind initKind =
11232 InitializationKind::CreateCopy(Loc, SourceLocation());
11233
11234 Expr *opaqueValue =
11235 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011236 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11237 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000011238 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000011239 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000011240 else {
11241 // If the constructor used was non-trivial, set this as the
11242 // "initializer".
Nick Lewyckyee0bc3b2013-09-22 10:06:57 +000011243 CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
John McCalle996ffd2011-02-16 08:02:54 +000011244 if (!construct->getConstructor()->isTrivial()) {
11245 Expr *init = MaybeCreateExprWithCleanups(construct);
11246 ExDecl->setInit(init);
11247 }
11248
11249 // And make sure it's destructable.
11250 FinalizeVarWithDestructor(ExDecl, recordType);
11251 }
Douglas Gregor6d182892010-03-05 23:38:39 +000011252 }
11253 }
11254
Douglas Gregord308e622009-05-18 20:51:54 +000011255 if (Invalid)
11256 ExDecl->setInvalidDecl();
11257
11258 return ExDecl;
11259}
11260
11261/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11262/// handler.
John McCalld226f652010-08-21 09:40:31 +000011263Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000011264 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000011265 bool Invalid = D.isInvalidType();
11266
11267 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000011268 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11269 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000011270 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11271 D.getIdentifierLoc());
11272 Invalid = true;
11273 }
11274
Sebastian Redl4b07b292008-12-22 19:15:10 +000011275 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000011276 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000011277 LookupOrdinaryName,
11278 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011279 // The scope should be freshly made just for us. There is just no way
11280 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000011281 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000011282 if (PrevDecl->isTemplateParameter()) {
11283 // Maybe we will complain about the shadowed template parameter.
11284 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000011285 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011286 }
11287 }
11288
Chris Lattnereaaebc72009-04-25 08:06:05 +000011289 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011290 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11291 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000011292 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011293 }
11294
Douglas Gregor83cb9422010-09-09 17:09:21 +000011295 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000011296 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011297 D.getIdentifierLoc(),
11298 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000011299 if (Invalid)
11300 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000011301
Sebastian Redl4b07b292008-12-22 19:15:10 +000011302 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011303 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000011304 PushOnScopeChains(ExDecl, S);
11305 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011306 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000011307
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011308 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000011309 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011310}
Anders Carlssonfb311762009-03-14 00:25:26 +000011311
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011312Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000011313 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000011314 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011315 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000011316 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000011317
Richard Smithe3f470a2012-07-11 22:37:56 +000011318 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11319 return 0;
11320
11321 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11322 AssertMessage, RParenLoc, false);
11323}
11324
11325Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11326 Expr *AssertExpr,
11327 StringLiteral *AssertMessage,
11328 SourceLocation RParenLoc,
11329 bool Failed) {
11330 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11331 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000011332 // In a static_assert-declaration, the constant-expression shall be a
11333 // constant expression that can be contextually converted to bool.
11334 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11335 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011336 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000011337
Richard Smithdaaefc52011-12-14 23:32:26 +000011338 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000011339 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011340 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000011341 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011342 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000011343
Richard Smithe3f470a2012-07-11 22:37:56 +000011344 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011345 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000011346 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000011347 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011348 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000011349 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000011350 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000011351 }
Anders Carlssonc3082412009-03-14 00:33:21 +000011352 }
Mike Stump1eb44332009-09-09 15:08:12 +000011353
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011354 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000011355 AssertExpr, AssertMessage, RParenLoc,
11356 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000011357
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011358 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000011359 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000011360}
Sebastian Redl50de12f2009-03-24 22:27:57 +000011361
Douglas Gregor1d869352010-04-07 16:53:43 +000011362/// \brief Perform semantic analysis of the given friend type declaration.
11363///
11364/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000011365FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000011366 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011367 TypeSourceInfo *TSInfo) {
11368 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11369
11370 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000011371 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000011372
Richard Smith6b130222011-10-18 21:39:00 +000011373 // C++03 [class.friend]p2:
11374 // An elaborated-type-specifier shall be used in a friend declaration
11375 // for a class.*
11376 //
11377 // * The class-key of the elaborated-type-specifier is required.
11378 if (!ActiveTemplateInstantiations.empty()) {
11379 // Do not complain about the form of friend template types during
11380 // template instantiation; we will already have complained when the
11381 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011382 } else {
11383 if (!T->isElaboratedTypeSpecifier()) {
11384 // If we evaluated the type to a record type, suggest putting
11385 // a tag in front.
11386 if (const RecordType *RT = T->getAs<RecordType>()) {
11387 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000011388
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011389 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000011390
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011391 Diag(TypeRange.getBegin(),
11392 getLangOpts().CPlusPlus11 ?
11393 diag::warn_cxx98_compat_unelaborated_friend_type :
11394 diag::ext_unelaborated_friend_type)
11395 << (unsigned) RD->getTagKind()
11396 << T
11397 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11398 InsertionText);
11399 } else {
11400 Diag(FriendLoc,
11401 getLangOpts().CPlusPlus11 ?
11402 diag::warn_cxx98_compat_nonclass_type_friend :
11403 diag::ext_nonclass_type_friend)
11404 << T
11405 << TypeRange;
11406 }
11407 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000011408 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000011409 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011410 diag::warn_cxx98_compat_enum_friend :
11411 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000011412 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000011413 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000011414 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011415
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011416 // C++11 [class.friend]p3:
11417 // A friend declaration that does not declare a function shall have one
11418 // of the following forms:
11419 // friend elaborated-type-specifier ;
11420 // friend simple-type-specifier ;
11421 // friend typename-specifier ;
11422 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11423 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11424 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011425
Douglas Gregor06245bf2010-04-07 17:57:12 +000011426 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011427 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011428 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011429 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011430}
11431
John McCall9a34edb2010-10-19 01:40:49 +000011432/// Handle a friend tag declaration where the scope specifier was
11433/// templated.
11434Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11435 unsigned TagSpec, SourceLocation TagLoc,
11436 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011437 IdentifierInfo *Name,
11438 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011439 AttributeList *Attr,
11440 MultiTemplateParamsArg TempParamLists) {
11441 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11442
11443 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011444 bool Invalid = false;
11445
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011446 if (TemplateParameterList *TemplateParams =
11447 MatchTemplateParametersToScopeSpecifier(
11448 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11449 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011450 if (TemplateParams->size() > 0) {
11451 // This is a declaration of a class template.
11452 if (Invalid)
11453 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011454
Eric Christopher4110e132011-07-21 05:34:24 +000011455 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11456 SS, Name, NameLoc, Attr,
11457 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011458 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011459 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011460 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011461 } else {
11462 // The "template<>" header is extraneous.
11463 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11464 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11465 isExplicitSpecialization = true;
11466 }
11467 }
11468
11469 if (Invalid) return 0;
11470
John McCall9a34edb2010-10-19 01:40:49 +000011471 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011472 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011473 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011474 isAllExplicitSpecializations = false;
11475 break;
11476 }
11477 }
11478
11479 // FIXME: don't ignore attributes.
11480
11481 // If it's explicit specializations all the way down, just forget
11482 // about the template header and build an appropriate non-templated
11483 // friend. TODO: for source fidelity, remember the headers.
11484 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011485 if (SS.isEmpty()) {
11486 bool Owned = false;
11487 bool IsDependent = false;
11488 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11489 Attr, AS_public,
11490 /*ModulePrivateLoc=*/SourceLocation(),
11491 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011492 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011493 /*ScopedEnumUsesClassTag=*/false,
11494 /*UnderlyingType=*/TypeResult());
11495 }
11496
Douglas Gregor2494dd02011-03-01 01:34:45 +000011497 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011498 ElaboratedTypeKeyword Keyword
11499 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011500 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011501 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011502 if (T.isNull())
11503 return 0;
11504
11505 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11506 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011507 DependentNameTypeLoc TL =
11508 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011509 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011510 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011511 TL.setNameLoc(NameLoc);
11512 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011513 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011514 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011515 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011516 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011517 }
11518
11519 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011520 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011521 Friend->setAccess(AS_public);
11522 CurContext->addDecl(Friend);
11523 return Friend;
11524 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011525
11526 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11527
11528
John McCall9a34edb2010-10-19 01:40:49 +000011529
11530 // Handle the case of a templated-scope friend class. e.g.
11531 // template <class T> class A<T>::B;
11532 // FIXME: we don't support these right now.
11533 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11534 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11535 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011536 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011537 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011538 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011539 TL.setNameLoc(NameLoc);
11540
11541 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011542 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011543 Friend->setAccess(AS_public);
11544 Friend->setUnsupportedFriend(true);
11545 CurContext->addDecl(Friend);
11546 return Friend;
11547}
11548
11549
John McCalldd4a3b02009-09-16 22:47:08 +000011550/// Handle a friend type declaration. This works in tandem with
11551/// ActOnTag.
11552///
11553/// Notes on friend class templates:
11554///
11555/// We generally treat friend class declarations as if they were
11556/// declaring a class. So, for example, the elaborated type specifier
11557/// in a friend declaration is required to obey the restrictions of a
11558/// class-head (i.e. no typedefs in the scope chain), template
11559/// parameters are required to match up with simple template-ids, &c.
11560/// However, unlike when declaring a template specialization, it's
11561/// okay to refer to a template specialization without an empty
11562/// template parameter declaration, e.g.
11563/// friend class A<T>::B<unsigned>;
11564/// We permit this as a special case; if there are any template
11565/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011566/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011567Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011568 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011569 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011570
11571 assert(DS.isFriendSpecified());
11572 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11573
John McCalldd4a3b02009-09-16 22:47:08 +000011574 // Try to convert the decl specifier to a type. This works for
11575 // friend templates because ActOnTag never produces a ClassTemplateDecl
11576 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011577 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011578 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11579 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011580 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011581 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011582
Douglas Gregor6ccab972010-12-16 01:14:37 +000011583 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11584 return 0;
11585
John McCalldd4a3b02009-09-16 22:47:08 +000011586 // This is definitely an error in C++98. It's probably meant to
11587 // be forbidden in C++0x, too, but the specification is just
11588 // poorly written.
11589 //
11590 // The problem is with declarations like the following:
11591 // template <T> friend A<T>::foo;
11592 // where deciding whether a class C is a friend or not now hinges
11593 // on whether there exists an instantiation of A that causes
11594 // 'foo' to equal C. There are restrictions on class-heads
11595 // (which we declare (by fiat) elaborated friend declarations to
11596 // be) that makes this tractable.
11597 //
11598 // FIXME: handle "template <> friend class A<T>;", which
11599 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011600 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011601 Diag(Loc, diag::err_tagless_friend_type_template)
11602 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011603 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011604 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011605
John McCall02cace72009-08-28 07:59:38 +000011606 // C++98 [class.friend]p1: A friend of a class is a function
11607 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011608 // This is fixed in DR77, which just barely didn't make the C++03
11609 // deadline. It's also a very silly restriction that seriously
11610 // affects inner classes and which nobody else seems to implement;
11611 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011612 //
11613 // But note that we could warn about it: it's always useless to
11614 // friend one of your own members (it's not, however, worthless to
11615 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011616
John McCalldd4a3b02009-09-16 22:47:08 +000011617 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011618 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011619 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011620 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011621 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011622 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011623 DS.getFriendSpecLoc());
11624 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011625 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011626
11627 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011628 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011629
John McCalldd4a3b02009-09-16 22:47:08 +000011630 D->setAccess(AS_public);
11631 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011632
John McCalld226f652010-08-21 09:40:31 +000011633 return D;
John McCall02cace72009-08-28 07:59:38 +000011634}
11635
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011636NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11637 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011638 const DeclSpec &DS = D.getDeclSpec();
11639
11640 assert(DS.isFriendSpecified());
11641 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11642
11643 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011644 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011645
11646 // C++ [class.friend]p1
11647 // A friend of a class is a function or class....
11648 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011649 // It *doesn't* see through dependent types, which is correct
11650 // according to [temp.arg.type]p3:
11651 // If a declaration acquires a function type through a
11652 // type dependent on a template-parameter and this causes
11653 // a declaration that does not use the syntactic form of a
11654 // function declarator to have a function type, the program
11655 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011656 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011657 Diag(Loc, diag::err_unexpected_friend);
11658
11659 // It might be worthwhile to try to recover by creating an
11660 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011661 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011662 }
11663
11664 // C++ [namespace.memdef]p3
11665 // - If a friend declaration in a non-local class first declares a
11666 // class or function, the friend class or function is a member
11667 // of the innermost enclosing namespace.
11668 // - The name of the friend is not found by simple name lookup
11669 // until a matching declaration is provided in that namespace
11670 // scope (either before or after the class declaration granting
11671 // friendship).
11672 // - If a friend function is called, its name may be found by the
11673 // name lookup that considers functions from namespaces and
11674 // classes associated with the types of the function arguments.
11675 // - When looking for a prior declaration of a class or a function
11676 // declared as a friend, scopes outside the innermost enclosing
11677 // namespace scope are not considered.
11678
John McCall337ec3d2010-10-12 23:13:28 +000011679 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011680 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11681 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011682 assert(Name);
11683
Douglas Gregor6ccab972010-12-16 01:14:37 +000011684 // Check for unexpanded parameter packs.
11685 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11686 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11687 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11688 return 0;
11689
John McCall67d1a672009-08-06 02:15:43 +000011690 // The context we found the declaration in, or in which we should
11691 // create the declaration.
11692 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011693 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011694 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011695 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011696
Richard Smith4e9686b2013-08-09 04:35:01 +000011697 // There are five cases here.
11698 // - There's no scope specifier and we're in a local class. Only look
11699 // for functions declared in the immediately-enclosing block scope.
11700 // We recover from invalid scope qualifiers as if they just weren't there.
11701 FunctionDecl *FunctionContainingLocalClass = 0;
11702 if ((SS.isInvalid() || !SS.isSet()) &&
11703 (FunctionContainingLocalClass =
11704 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11705 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000011706 // If a friend declaration appears in a local class and the name
11707 // specified is an unqualified name, a prior declaration is
11708 // looked up without considering scopes that are outside the
11709 // innermost enclosing non-class scope. For a friend function
11710 // declaration, if there is no prior declaration, the program is
11711 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000011712
11713 // Find the innermost enclosing non-class scope. This is the block
11714 // scope containing the local class definition (or for a nested class,
11715 // the outer local class).
11716 DCScope = S->getFnParent();
11717
11718 // Look up the function name in the scope.
11719 Previous.clear(LookupLocalFriendName);
11720 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11721
11722 if (!Previous.empty()) {
11723 // All possible previous declarations must have the same context:
11724 // either they were declared at block scope or they are members of
11725 // one of the enclosing local classes.
11726 DC = Previous.getRepresentativeDecl()->getDeclContext();
11727 } else {
11728 // This is ill-formed, but provide the context that we would have
11729 // declared the function in, if we were permitted to, for error recovery.
11730 DC = FunctionContainingLocalClass;
11731 }
Richard Smitha41c97a2013-09-20 01:15:31 +000011732 adjustContextForLocalExternDecl(DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011733
11734 // C++ [class.friend]p6:
11735 // A function can be defined in a friend declaration of a class if and
11736 // only if the class is a non-local class (9.8), the function name is
11737 // unqualified, and the function has namespace scope.
11738 if (D.isFunctionDefinition()) {
11739 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11740 }
11741
11742 // - There's no scope specifier, in which case we just go to the
11743 // appropriate scope and look for a function or function template
11744 // there as appropriate.
11745 } else if (SS.isInvalid() || !SS.isSet()) {
11746 // C++11 [namespace.memdef]p3:
11747 // If the name in a friend declaration is neither qualified nor
11748 // a template-id and the declaration is a function or an
11749 // elaborated-type-specifier, the lookup to determine whether
11750 // the entity has been previously declared shall not consider
11751 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000011752 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011753
John McCall29ae6e52010-10-13 05:45:15 +000011754 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011755 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011756
Rafael Espindola11dc6342013-04-25 20:12:36 +000011757 // Skip class contexts. If someone can cite chapter and verse
11758 // for this behavior, that would be nice --- it's what GCC and
11759 // EDG do, and it seems like a reasonable intent, but the spec
11760 // really only says that checks for unqualified existing
11761 // declarations should stop at the nearest enclosing namespace,
11762 // not that they should only consider the nearest enclosing
11763 // namespace.
11764 while (DC->isRecord())
11765 DC = DC->getParent();
11766
11767 DeclContext *LookupDC = DC;
11768 while (LookupDC->isTransparentContext())
11769 LookupDC = LookupDC->getParent();
11770
11771 while (true) {
11772 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011773
Rafael Espindola11dc6342013-04-25 20:12:36 +000011774 if (!Previous.empty()) {
11775 DC = LookupDC;
11776 break;
John McCall8a407372010-10-14 22:22:28 +000011777 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011778
11779 if (isTemplateId) {
11780 if (isa<TranslationUnitDecl>(LookupDC)) break;
11781 } else {
11782 if (LookupDC->isFileContext()) break;
11783 }
11784 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011785 }
11786
John McCall380aaa42010-10-13 06:22:15 +000011787 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011788
John McCall337ec3d2010-10-12 23:13:28 +000011789 // - There's a non-dependent scope specifier, in which case we
11790 // compute it and do a previous lookup there for a function
11791 // or function template.
11792 } else if (!SS.getScopeRep()->isDependent()) {
11793 DC = computeDeclContext(SS);
11794 if (!DC) return 0;
11795
11796 if (RequireCompleteDeclContext(SS, DC)) return 0;
11797
11798 LookupQualifiedName(Previous, DC);
11799
11800 // Ignore things found implicitly in the wrong scope.
11801 // TODO: better diagnostics for this case. Suggesting the right
11802 // qualified scope would be nice...
11803 LookupResult::Filter F = Previous.makeFilter();
11804 while (F.hasNext()) {
11805 NamedDecl *D = F.next();
11806 if (!DC->InEnclosingNamespaceSetOf(
11807 D->getDeclContext()->getRedeclContext()))
11808 F.erase();
11809 }
11810 F.done();
11811
11812 if (Previous.empty()) {
11813 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011814 Diag(Loc, diag::err_qualified_friend_not_found)
11815 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011816 return 0;
11817 }
11818
11819 // C++ [class.friend]p1: A friend of a class is a function or
11820 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011821 if (DC->Equals(CurContext))
11822 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011823 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011824 diag::warn_cxx98_compat_friend_is_member :
11825 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011826
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011827 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011828 // C++ [class.friend]p6:
11829 // A function can be defined in a friend declaration of a class if and
11830 // only if the class is a non-local class (9.8), the function name is
11831 // unqualified, and the function has namespace scope.
11832 SemaDiagnosticBuilder DB
11833 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11834
11835 DB << SS.getScopeRep();
11836 if (DC->isFileContext())
11837 DB << FixItHint::CreateRemoval(SS.getRange());
11838 SS.clear();
11839 }
John McCall337ec3d2010-10-12 23:13:28 +000011840
11841 // - There's a scope specifier that does not match any template
11842 // parameter lists, in which case we use some arbitrary context,
11843 // create a method or method template, and wait for instantiation.
11844 // - There's a scope specifier that does match some template
11845 // parameter lists, which we don't handle right now.
11846 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011847 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011848 // C++ [class.friend]p6:
11849 // A function can be defined in a friend declaration of a class if and
11850 // only if the class is a non-local class (9.8), the function name is
11851 // unqualified, and the function has namespace scope.
11852 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11853 << SS.getScopeRep();
11854 }
11855
John McCall337ec3d2010-10-12 23:13:28 +000011856 DC = CurContext;
11857 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011858 }
Douglas Gregor883af832011-10-10 01:11:59 +000011859
John McCall29ae6e52010-10-13 05:45:15 +000011860 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011861 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011862 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11863 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11864 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011865 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011866 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11867 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011868 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011869 }
John McCall67d1a672009-08-06 02:15:43 +000011870 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011871
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011872 // FIXME: This is an egregious hack to cope with cases where the scope stack
11873 // does not contain the declaration context, i.e., in an out-of-line
11874 // definition of a class.
11875 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11876 if (!DCScope) {
11877 FakeDCScope.setEntity(DC);
11878 DCScope = &FakeDCScope;
11879 }
Richard Smith4e9686b2013-08-09 04:35:01 +000011880
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011881 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011882 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011883 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011884 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011885
Douglas Gregor182ddf02009-09-28 00:08:27 +000011886 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011887
Richard Smith4e9686b2013-08-09 04:35:01 +000011888 // If we performed typo correction, we might have added a scope specifier
11889 // and changed the decl context.
11890 DC = ND->getDeclContext();
11891
John McCallab88d972009-08-31 22:39:49 +000011892 // Add the function declaration to the appropriate lookup tables,
11893 // adjusting the redeclarations list as necessary. We don't
11894 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011895 //
John McCallab88d972009-08-31 22:39:49 +000011896 // Also update the scope-based lookup if the target context's
11897 // lookup context is in lexical scope.
11898 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011899 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011900 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011901 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011902 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011903 }
John McCall02cace72009-08-28 07:59:38 +000011904
11905 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011906 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011907 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011908 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011909 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011910
John McCall1f2e1a92012-08-10 03:15:35 +000011911 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011912 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011913 } else {
11914 if (DC->isRecord()) CheckFriendAccess(ND);
11915
John McCall6102ca12010-10-16 06:59:13 +000011916 FunctionDecl *FD;
11917 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11918 FD = FTD->getTemplatedDecl();
11919 else
11920 FD = cast<FunctionDecl>(ND);
11921
David Majnemerf6a144f2013-06-25 23:09:30 +000011922 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11923 // default argument expression, that declaration shall be a definition
11924 // and shall be the only declaration of the function or function
11925 // template in the translation unit.
11926 if (functionDeclHasDefaultArgument(FD)) {
11927 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11928 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11929 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11930 } else if (!D.isFunctionDefinition())
11931 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11932 }
11933
John McCall6102ca12010-10-16 06:59:13 +000011934 // Mark templated-scope function declarations as unsupported.
11935 if (FD->getNumTemplateParameterLists())
11936 FrD->setUnsupportedFriend(true);
11937 }
John McCall337ec3d2010-10-12 23:13:28 +000011938
John McCalld226f652010-08-21 09:40:31 +000011939 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011940}
11941
John McCalld226f652010-08-21 09:40:31 +000011942void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11943 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011944
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011945 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011946 if (!Fn) {
11947 Diag(DelLoc, diag::err_deleted_non_function);
11948 return;
11949 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011950
Douglas Gregoref96ee02012-01-14 16:38:05 +000011951 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011952 // Don't consider the implicit declaration we generate for explicit
11953 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011954 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11955 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011956 Diag(DelLoc, diag::err_deleted_decl_not_first);
11957 Diag(Prev->getLocation(), diag::note_previous_declaration);
11958 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011959 // If the declaration wasn't the first, we delete the function anyway for
11960 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011961 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011962 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011963
11964 if (Fn->isDeleted())
11965 return;
11966
11967 // See if we're deleting a function which is already known to override a
11968 // non-deleted virtual function.
11969 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11970 bool IssuedDiagnostic = false;
11971 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11972 E = MD->end_overridden_methods();
11973 I != E; ++I) {
11974 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11975 if (!IssuedDiagnostic) {
11976 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11977 IssuedDiagnostic = true;
11978 }
11979 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11980 }
11981 }
11982 }
11983
Sean Hunt10620eb2011-05-06 20:44:56 +000011984 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011985}
Sebastian Redl13e88542009-04-27 21:33:24 +000011986
Sean Hunte4246a62011-05-12 06:15:49 +000011987void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011988 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011989
11990 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011991 if (MD->getParent()->isDependentType()) {
11992 MD->setDefaulted();
11993 MD->setExplicitlyDefaulted();
11994 return;
11995 }
11996
Sean Hunte4246a62011-05-12 06:15:49 +000011997 CXXSpecialMember Member = getSpecialMember(MD);
11998 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011999 if (!MD->isInvalidDecl())
12000 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000012001 return;
12002 }
12003
12004 MD->setDefaulted();
12005 MD->setExplicitlyDefaulted();
12006
Sean Huntcd10dec2011-05-23 23:14:04 +000012007 // If this definition appears within the record, do the checking when
12008 // the record is complete.
12009 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000012010 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000012011 // Find the uninstantiated declaration that actually had the '= default'
12012 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000012013 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000012014
Richard Smith12fef492013-03-27 00:22:47 +000012015 // If the method was defaulted on its first declaration, we will have
12016 // already performed the checking in CheckCompletedCXXClass. Such a
12017 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000012018 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000012019 return;
12020
Richard Smithb9d0b762012-07-27 04:22:15 +000012021 CheckExplicitlyDefaultedSpecialMember(MD);
12022
Richard Smith1d28caf2012-12-11 01:14:52 +000012023 // The exception specification is needed because we are defining the
12024 // function.
12025 ResolveExceptionSpec(DefaultLoc,
12026 MD->getType()->castAs<FunctionProtoType>());
12027
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012028 if (MD->isInvalidDecl())
12029 return;
12030
Sean Hunte4246a62011-05-12 06:15:49 +000012031 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012032 case CXXDefaultConstructor:
12033 DefineImplicitDefaultConstructor(DefaultLoc,
12034 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000012035 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012036 case CXXCopyConstructor:
12037 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000012038 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012039 case CXXCopyAssignment:
12040 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000012041 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012042 case CXXDestructor:
12043 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000012044 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012045 case CXXMoveConstructor:
12046 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000012047 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012048 case CXXMoveAssignment:
12049 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012050 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000012051 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000012052 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000012053 }
12054 } else {
12055 Diag(DefaultLoc, diag::err_default_special_members);
12056 }
12057}
12058
Sebastian Redl13e88542009-04-27 21:33:24 +000012059static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000012060 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000012061 Stmt *SubStmt = *CI;
12062 if (!SubStmt)
12063 continue;
12064 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000012065 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000012066 diag::err_return_in_constructor_handler);
12067 if (!isa<Expr>(SubStmt))
12068 SearchForReturnInStmt(Self, SubStmt);
12069 }
12070}
12071
12072void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
12073 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
12074 CXXCatchStmt *Handler = TryBlock->getHandler(I);
12075 SearchForReturnInStmt(*this, Handler);
12076 }
12077}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012078
David Blaikie299adab2013-01-18 23:03:15 +000012079bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000012080 const CXXMethodDecl *Old) {
12081 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12082 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12083
12084 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12085
12086 // If the calling conventions match, everything is fine
12087 if (NewCC == OldCC)
12088 return false;
12089
Reid Kleckneref072032013-08-27 23:08:25 +000012090 Diag(New->getLocation(),
12091 diag::err_conflicting_overriding_cc_attributes)
12092 << New->getDeclName() << New->getType() << Old->getType();
12093 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12094 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000012095}
12096
Mike Stump1eb44332009-09-09 15:08:12 +000012097bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012098 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000012099 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
12100 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012101
Chandler Carruth73857792010-02-15 11:53:20 +000012102 if (Context.hasSameType(NewTy, OldTy) ||
12103 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012104 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000012105
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012106 // Check if the return types are covariant
12107 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000012108
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012109 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012110 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12111 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012112 NewClassTy = NewPT->getPointeeType();
12113 OldClassTy = OldPT->getPointeeType();
12114 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012115 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12116 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12117 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12118 NewClassTy = NewRT->getPointeeType();
12119 OldClassTy = OldRT->getPointeeType();
12120 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012121 }
12122 }
Mike Stump1eb44332009-09-09 15:08:12 +000012123
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012124 // The return types aren't either both pointers or references to a class type.
12125 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000012126 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012127 diag::err_different_return_type_for_overriding_virtual_function)
12128 << New->getDeclName() << NewTy << OldTy;
12129 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000012130
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012131 return true;
12132 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012133
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012134 // C++ [class.virtual]p6:
12135 // If the return type of D::f differs from the return type of B::f, the
12136 // class type in the return type of D::f shall be complete at the point of
12137 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000012138 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12139 if (!RT->isBeingDefined() &&
12140 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000012141 diag::err_covariant_return_incomplete,
12142 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012143 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000012144 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012145
Douglas Gregora4923eb2009-11-16 21:35:15 +000012146 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012147 // Check if the new class derives from the old class.
12148 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12149 Diag(New->getLocation(),
12150 diag::err_covariant_return_not_derived)
12151 << New->getDeclName() << NewTy << OldTy;
12152 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12153 return true;
12154 }
Mike Stump1eb44332009-09-09 15:08:12 +000012155
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012156 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000012157 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000012158 diag::err_covariant_return_inaccessible_base,
12159 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12160 // FIXME: Should this point to the return type?
12161 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000012162 // FIXME: this note won't trigger for delayed access control
12163 // diagnostics, and it's impossible to get an undelayed error
12164 // here from access control during the original parse because
12165 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012166 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12167 return true;
12168 }
12169 }
Mike Stump1eb44332009-09-09 15:08:12 +000012170
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012171 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012172 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012173 Diag(New->getLocation(),
12174 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012175 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012176 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12177 return true;
12178 };
Mike Stump1eb44332009-09-09 15:08:12 +000012179
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012180
12181 // The new class type must have the same or less qualifiers as the old type.
12182 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12183 Diag(New->getLocation(),
12184 diag::err_covariant_return_type_class_type_more_qualified)
12185 << New->getDeclName() << NewTy << OldTy;
12186 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12187 return true;
12188 };
Mike Stump1eb44332009-09-09 15:08:12 +000012189
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012190 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012191}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012192
Douglas Gregor4ba31362009-12-01 17:24:26 +000012193/// \brief Mark the given method pure.
12194///
12195/// \param Method the method to be marked pure.
12196///
12197/// \param InitRange the source range that covers the "0" initializer.
12198bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000012199 SourceLocation EndLoc = InitRange.getEnd();
12200 if (EndLoc.isValid())
12201 Method->setRangeEnd(EndLoc);
12202
Douglas Gregor4ba31362009-12-01 17:24:26 +000012203 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12204 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000012205 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000012206 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000012207
12208 if (!Method->isInvalidDecl())
12209 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12210 << Method->getDeclName() << InitRange;
12211 return true;
12212}
12213
Douglas Gregor552e2992012-02-21 02:22:07 +000012214/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012215static bool isStaticDataMember(const Decl *D) {
12216 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12217 return Var->isStaticDataMember();
12218
12219 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000012220}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012221
John McCall731ad842009-12-19 09:28:58 +000012222/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12223/// an initializer for the out-of-line declaration 'Dcl'. The scope
12224/// is a fresh scope pushed for just this purpose.
12225///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012226/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12227/// static data member of class X, names should be looked up in the scope of
12228/// class X.
John McCalld226f652010-08-21 09:40:31 +000012229void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012230 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012231 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012232
John McCall731ad842009-12-19 09:28:58 +000012233 // We should only get called for declarations with scope specifiers, like:
12234 // int foo::bar;
12235 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012236 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000012237
12238 // If we are parsing the initializer for a static data member, push a
12239 // new expression evaluation context that is associated with this static
12240 // data member.
12241 if (isStaticDataMember(D))
12242 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012243}
12244
12245/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000012246/// initializer for the out-of-line declaration 'D'.
12247void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012248 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012249 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012250
Douglas Gregor552e2992012-02-21 02:22:07 +000012251 if (isStaticDataMember(D))
12252 PopExpressionEvaluationContext();
12253
John McCall731ad842009-12-19 09:28:58 +000012254 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012255 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012256}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012257
12258/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12259/// C++ if/switch/while/for statement.
12260/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000012261DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012262 // C++ 6.4p2:
12263 // The declarator shall not specify a function or an array.
12264 // The type-specifier-seq shall not contain typedef and shall not declare a
12265 // new class or enumeration.
12266 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12267 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012268
12269 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000012270 if (!Dcl)
12271 return true;
12272
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012273 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12274 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012275 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000012276 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012277 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012278
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012279 return Dcl;
12280}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012281
Douglas Gregordfe65432011-07-28 19:11:31 +000012282void Sema::LoadExternalVTableUses() {
12283 if (!ExternalSource)
12284 return;
12285
12286 SmallVector<ExternalVTableUse, 4> VTables;
12287 ExternalSource->ReadUsedVTables(VTables);
12288 SmallVector<VTableUse, 4> NewUses;
12289 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12290 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12291 = VTablesUsed.find(VTables[I].Record);
12292 // Even if a definition wasn't required before, it may be required now.
12293 if (Pos != VTablesUsed.end()) {
12294 if (!Pos->second && VTables[I].DefinitionRequired)
12295 Pos->second = true;
12296 continue;
12297 }
12298
12299 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12300 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12301 }
12302
12303 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12304}
12305
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012306void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12307 bool DefinitionRequired) {
12308 // Ignore any vtable uses in unevaluated operands or for classes that do
12309 // not have a vtable.
12310 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000012311 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000012312 return;
12313
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012314 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000012315 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012316 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12317 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12318 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12319 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000012320 // If we already had an entry, check to see if we are promoting this vtable
12321 // to required a definition. If so, we need to reappend to the VTableUses
12322 // list, since we may have already processed the first entry.
12323 if (DefinitionRequired && !Pos.first->second) {
12324 Pos.first->second = true;
12325 } else {
12326 // Otherwise, we can early exit.
12327 return;
12328 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012329 }
12330
12331 // Local classes need to have their virtual members marked
12332 // immediately. For all other classes, we mark their virtual members
12333 // at the end of the translation unit.
12334 if (Class->isLocalClass())
12335 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000012336 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012337 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000012338}
12339
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012340bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000012341 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012342 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000012343 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000012344
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012345 // Note: The VTableUses vector could grow as a result of marking
12346 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000012347 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012348 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000012349 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012350 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000012351 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012352 if (!Class)
12353 continue;
12354
12355 SourceLocation Loc = VTableUses[I].second;
12356
Richard Smithb9d0b762012-07-27 04:22:15 +000012357 bool DefineVTable = true;
12358
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012359 // If this class has a key function, but that key function is
12360 // defined in another translation unit, we don't need to emit the
12361 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000012362 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000012363 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000012364 // The key function is in another translation unit.
12365 DefineVTable = false;
12366 TemplateSpecializationKind TSK =
12367 KeyFunction->getTemplateSpecializationKind();
12368 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12369 TSK != TSK_ImplicitInstantiation &&
12370 "Instantiations don't have key functions");
12371 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012372 } else if (!KeyFunction) {
12373 // If we have a class with no key function that is the subject
12374 // of an explicit instantiation declaration, suppress the
12375 // vtable; it will live with the explicit instantiation
12376 // definition.
12377 bool IsExplicitInstantiationDeclaration
12378 = Class->getTemplateSpecializationKind()
12379 == TSK_ExplicitInstantiationDeclaration;
12380 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12381 REnd = Class->redecls_end();
12382 R != REnd; ++R) {
12383 TemplateSpecializationKind TSK
12384 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12385 if (TSK == TSK_ExplicitInstantiationDeclaration)
12386 IsExplicitInstantiationDeclaration = true;
12387 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12388 IsExplicitInstantiationDeclaration = false;
12389 break;
12390 }
12391 }
12392
12393 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000012394 DefineVTable = false;
12395 }
12396
12397 // The exception specifications for all virtual members may be needed even
12398 // if we are not providing an authoritative form of the vtable in this TU.
12399 // We may choose to emit it available_externally anyway.
12400 if (!DefineVTable) {
12401 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12402 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012403 }
12404
12405 // Mark all of the virtual members of this class as referenced, so
12406 // that we can build a vtable. Then, tell the AST consumer that a
12407 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012408 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012409 MarkVirtualMembersReferenced(Loc, Class);
12410 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12411 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12412
12413 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012414 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012415 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000012416 const FunctionDecl *KeyFunctionDef = 0;
12417 if (!KeyFunction ||
12418 (KeyFunction->hasBody(KeyFunctionDef) &&
12419 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012420 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12421 TSK_ExplicitInstantiationDefinition
12422 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12423 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012424 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012425 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012426 VTableUses.clear();
12427
Douglas Gregor78844032011-04-22 22:25:37 +000012428 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012429}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012430
Richard Smithb9d0b762012-07-27 04:22:15 +000012431void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12432 const CXXRecordDecl *RD) {
12433 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12434 E = RD->method_end(); I != E; ++I)
12435 if ((*I)->isVirtual() && !(*I)->isPure())
12436 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12437}
12438
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012439void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12440 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012441 // Mark all functions which will appear in RD's vtable as used.
12442 CXXFinalOverriderMap FinalOverriders;
12443 RD->getFinalOverriders(FinalOverriders);
12444 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12445 E = FinalOverriders.end();
12446 I != E; ++I) {
12447 for (OverridingMethods::const_iterator OI = I->second.begin(),
12448 OE = I->second.end();
12449 OI != OE; ++OI) {
12450 assert(OI->second.size() > 0 && "no final overrider");
12451 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012452
Richard Smithff817f72012-07-07 06:59:51 +000012453 // C++ [basic.def.odr]p2:
12454 // [...] A virtual member function is used if it is not pure. [...]
12455 if (!Overrider->isPure())
12456 MarkFunctionReferenced(Loc, Overrider);
12457 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012458 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012459
12460 // Only classes that have virtual bases need a VTT.
12461 if (RD->getNumVBases() == 0)
12462 return;
12463
12464 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12465 e = RD->bases_end(); i != e; ++i) {
12466 const CXXRecordDecl *Base =
12467 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012468 if (Base->getNumVBases() == 0)
12469 continue;
12470 MarkVirtualMembersReferenced(Loc, Base);
12471 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012472}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012473
12474/// SetIvarInitializers - This routine builds initialization ASTs for the
12475/// Objective-C implementation whose ivars need be initialized.
12476void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012477 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012478 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012479 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012480 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012481 CollectIvarsToConstructOrDestruct(OID, ivars);
12482 if (ivars.empty())
12483 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012484 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012485 for (unsigned i = 0; i < ivars.size(); i++) {
12486 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012487 if (Field->isInvalidDecl())
12488 continue;
12489
Sean Huntcbb67482011-01-08 20:30:50 +000012490 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012491 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12492 InitializationKind InitKind =
12493 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012494
12495 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12496 ExprResult MemberInit =
12497 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012498 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012499 // Note, MemberInit could actually come back empty if no initialization
12500 // is required (e.g., because it would call a trivial default constructor)
12501 if (!MemberInit.get() || MemberInit.isInvalid())
12502 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012503
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012504 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012505 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12506 SourceLocation(),
12507 MemberInit.takeAs<Expr>(),
12508 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012509 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012510
12511 // Be sure that the destructor is accessible and is marked as referenced.
12512 if (const RecordType *RecordTy
12513 = Context.getBaseElementType(Field->getType())
12514 ->getAs<RecordType>()) {
12515 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012516 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012517 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012518 CheckDestructorAccess(Field->getLocation(), Destructor,
12519 PDiag(diag::err_access_dtor_ivar)
12520 << Context.getBaseElementType(Field->getType()));
12521 }
12522 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012523 }
12524 ObjCImplementation->setIvarInitializers(Context,
12525 AllToInit.data(), AllToInit.size());
12526 }
12527}
Sean Huntfe57eef2011-05-04 05:57:24 +000012528
Sean Huntebcbe1d2011-05-04 23:29:54 +000012529static
12530void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12531 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12532 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12533 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12534 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012535 if (Ctor->isInvalidDecl())
12536 return;
12537
Richard Smitha8eaf002012-08-23 06:16:52 +000012538 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12539
12540 // Target may not be determinable yet, for instance if this is a dependent
12541 // call in an uninstantiated template.
12542 if (Target) {
12543 const FunctionDecl *FNTarget = 0;
12544 (void)Target->hasBody(FNTarget);
12545 Target = const_cast<CXXConstructorDecl*>(
12546 cast_or_null<CXXConstructorDecl>(FNTarget));
12547 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012548
12549 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12550 // Avoid dereferencing a null pointer here.
12551 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12552
12553 if (!Current.insert(Canonical))
12554 return;
12555
12556 // We know that beyond here, we aren't chaining into a cycle.
12557 if (!Target || !Target->isDelegatingConstructor() ||
12558 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012559 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012560 Current.clear();
12561 // We've hit a cycle.
12562 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12563 Current.count(TCanonical)) {
12564 // If we haven't diagnosed this cycle yet, do so now.
12565 if (!Invalid.count(TCanonical)) {
12566 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012567 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012568 << Ctor;
12569
Richard Smitha8eaf002012-08-23 06:16:52 +000012570 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012571 if (TCanonical != Canonical)
12572 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12573
12574 CXXConstructorDecl *C = Target;
12575 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012576 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012577 (void)C->getTargetConstructor()->hasBody(FNTarget);
12578 assert(FNTarget && "Ctor cycle through bodiless function");
12579
Richard Smitha8eaf002012-08-23 06:16:52 +000012580 C = const_cast<CXXConstructorDecl*>(
12581 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012582 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12583 }
12584 }
12585
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012586 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012587 Current.clear();
12588 } else {
12589 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12590 }
12591}
12592
12593
Sean Huntfe57eef2011-05-04 05:57:24 +000012594void Sema::CheckDelegatingCtorCycles() {
12595 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12596
Douglas Gregor0129b562011-07-27 21:57:17 +000012597 for (DelegatingCtorDeclsType::iterator
12598 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012599 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012600 I != E; ++I)
12601 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012602
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012603 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12604 CE = Invalid.end();
12605 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012606 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012607}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012608
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012609namespace {
12610 /// \brief AST visitor that finds references to the 'this' expression.
12611 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12612 Sema &S;
12613
12614 public:
12615 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12616
12617 bool VisitCXXThisExpr(CXXThisExpr *E) {
12618 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12619 << E->isImplicit();
12620 return false;
12621 }
12622 };
12623}
12624
12625bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12626 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12627 if (!TSInfo)
12628 return false;
12629
12630 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012631 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012632 if (!ProtoTL)
12633 return false;
12634
12635 // C++11 [expr.prim.general]p3:
12636 // [The expression this] shall not appear before the optional
12637 // cv-qualifier-seq and it shall not appear within the declaration of a
12638 // static member function (although its type and value category are defined
12639 // within a static member function as they are within a non-static member
12640 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012641 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012642 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012643 FindCXXThisExpr Finder(*this);
12644
12645 // If the return type came after the cv-qualifier-seq, check it now.
12646 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012647 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012648 return true;
12649
12650 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012651 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12652 return true;
12653
12654 return checkThisInStaticMemberFunctionAttributes(Method);
12655}
12656
12657bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12658 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12659 if (!TSInfo)
12660 return false;
12661
12662 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012663 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012664 if (!ProtoTL)
12665 return false;
12666
David Blaikie39e6ab42013-02-18 22:06:02 +000012667 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012668 FindCXXThisExpr Finder(*this);
12669
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012670 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012671 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012672 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012673 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012674 case EST_DynamicNone:
12675 case EST_MSAny:
12676 case EST_None:
12677 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012678
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012679 case EST_ComputedNoexcept:
12680 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12681 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012682
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012683 case EST_Dynamic:
12684 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012685 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012686 E != EEnd; ++E) {
12687 if (!Finder.TraverseType(*E))
12688 return true;
12689 }
12690 break;
12691 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012692
12693 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012694}
12695
12696bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12697 FindCXXThisExpr Finder(*this);
12698
12699 // Check attributes.
12700 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12701 A != AEnd; ++A) {
12702 // FIXME: This should be emitted by tblgen.
12703 Expr *Arg = 0;
12704 ArrayRef<Expr *> Args;
12705 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12706 Arg = G->getArg();
12707 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12708 Arg = G->getArg();
12709 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12710 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12711 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12712 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12713 else if (ExclusiveLockFunctionAttr *ELF
12714 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12715 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12716 else if (SharedLockFunctionAttr *SLF
12717 = dyn_cast<SharedLockFunctionAttr>(*A))
12718 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12719 else if (ExclusiveTrylockFunctionAttr *ETLF
12720 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12721 Arg = ETLF->getSuccessValue();
12722 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12723 } else if (SharedTrylockFunctionAttr *STLF
12724 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12725 Arg = STLF->getSuccessValue();
12726 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12727 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12728 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12729 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12730 Arg = LR->getArg();
12731 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12732 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12733 else if (ExclusiveLocksRequiredAttr *ELR
12734 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12735 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12736 else if (SharedLocksRequiredAttr *SLR
12737 = dyn_cast<SharedLocksRequiredAttr>(*A))
12738 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12739
12740 if (Arg && !Finder.TraverseStmt(Arg))
12741 return true;
12742
12743 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12744 if (!Finder.TraverseStmt(Args[I]))
12745 return true;
12746 }
12747 }
12748
12749 return false;
12750}
12751
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012752void
12753Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12754 ArrayRef<ParsedType> DynamicExceptions,
12755 ArrayRef<SourceRange> DynamicExceptionRanges,
12756 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012757 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012758 FunctionProtoType::ExtProtoInfo &EPI) {
12759 Exceptions.clear();
12760 EPI.ExceptionSpecType = EST;
12761 if (EST == EST_Dynamic) {
12762 Exceptions.reserve(DynamicExceptions.size());
12763 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12764 // FIXME: Preserve type source info.
12765 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12766
12767 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12768 collectUnexpandedParameterPacks(ET, Unexpanded);
12769 if (!Unexpanded.empty()) {
12770 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12771 UPPC_ExceptionType,
12772 Unexpanded);
12773 continue;
12774 }
12775
12776 // Check that the type is valid for an exception spec, and
12777 // drop it if not.
12778 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12779 Exceptions.push_back(ET);
12780 }
12781 EPI.NumExceptions = Exceptions.size();
12782 EPI.Exceptions = Exceptions.data();
12783 return;
12784 }
12785
12786 if (EST == EST_ComputedNoexcept) {
12787 // If an error occurred, there's no expression here.
12788 if (NoexceptExpr) {
12789 assert((NoexceptExpr->isTypeDependent() ||
12790 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12791 Context.BoolTy) &&
12792 "Parser should have made sure that the expression is boolean");
12793 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12794 EPI.ExceptionSpecType = EST_BasicNoexcept;
12795 return;
12796 }
12797
12798 if (!NoexceptExpr->isValueDependent())
12799 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012800 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012801 /*AllowFold*/ false).take();
12802 EPI.NoexceptExpr = NoexceptExpr;
12803 }
12804 return;
12805 }
12806}
12807
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012808/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12809Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12810 // Implicitly declared functions (e.g. copy constructors) are
12811 // __host__ __device__
12812 if (D->isImplicit())
12813 return CFT_HostDevice;
12814
12815 if (D->hasAttr<CUDAGlobalAttr>())
12816 return CFT_Global;
12817
12818 if (D->hasAttr<CUDADeviceAttr>()) {
12819 if (D->hasAttr<CUDAHostAttr>())
12820 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012821 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012822 }
12823
12824 return CFT_Host;
12825}
12826
12827bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12828 CUDAFunctionTarget CalleeTarget) {
12829 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12830 // Callable from the device only."
12831 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12832 return true;
12833
12834 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12835 // Callable from the host only."
12836 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12837 // Callable from the host only."
12838 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12839 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12840 return true;
12841
12842 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12843 return true;
12844
12845 return false;
12846}
John McCall76da55d2013-04-16 07:28:30 +000012847
12848/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12849///
12850MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12851 SourceLocation DeclStart,
12852 Declarator &D, Expr *BitWidth,
12853 InClassInitStyle InitStyle,
12854 AccessSpecifier AS,
12855 AttributeList *MSPropertyAttr) {
12856 IdentifierInfo *II = D.getIdentifier();
12857 if (!II) {
12858 Diag(DeclStart, diag::err_anonymous_property);
12859 return NULL;
12860 }
12861 SourceLocation Loc = D.getIdentifierLoc();
12862
12863 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12864 QualType T = TInfo->getType();
12865 if (getLangOpts().CPlusPlus) {
12866 CheckExtraCXXDefaultArguments(D);
12867
12868 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12869 UPPC_DataMemberType)) {
12870 D.setInvalidType();
12871 T = Context.IntTy;
12872 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12873 }
12874 }
12875
12876 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12877
12878 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12879 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12880 diag::err_invalid_thread)
12881 << DeclSpec::getSpecifierName(TSCS);
12882
12883 // Check to see if this name was declared as a member previously
12884 NamedDecl *PrevDecl = 0;
12885 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12886 LookupName(Previous, S);
12887 switch (Previous.getResultKind()) {
12888 case LookupResult::Found:
12889 case LookupResult::FoundUnresolvedValue:
12890 PrevDecl = Previous.getAsSingle<NamedDecl>();
12891 break;
12892
12893 case LookupResult::FoundOverloaded:
12894 PrevDecl = Previous.getRepresentativeDecl();
12895 break;
12896
12897 case LookupResult::NotFound:
12898 case LookupResult::NotFoundInCurrentInstantiation:
12899 case LookupResult::Ambiguous:
12900 break;
12901 }
12902
12903 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12904 // Maybe we will complain about the shadowed template parameter.
12905 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12906 // Just pretend that we didn't see the previous declaration.
12907 PrevDecl = 0;
12908 }
12909
12910 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12911 PrevDecl = 0;
12912
12913 SourceLocation TSSL = D.getLocStart();
12914 MSPropertyDecl *NewPD;
12915 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12916 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12917 II, T, TInfo, TSSL,
12918 Data.GetterId, Data.SetterId);
12919 ProcessDeclAttributes(TUScope, NewPD, D);
12920 NewPD->setAccess(AS);
12921
12922 if (NewPD->isInvalidDecl())
12923 Record->setInvalidDecl();
12924
12925 if (D.getDeclSpec().isModulePrivateSpecified())
12926 NewPD->setModulePrivate();
12927
12928 if (NewPD->isInvalidDecl() && PrevDecl) {
12929 // Don't introduce NewFD into scope; there's already something
12930 // with the same name in the same scope.
12931 } else if (II) {
12932 PushOnScopeChains(NewPD, S);
12933 } else
12934 Record->addDecl(NewPD);
12935
12936 return NewPD;
12937}