blob: 34374aa99eb91231c2b415a8868a852bd6ec1b33 [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"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000017#include "clang/AST/ASTMutationListener.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/CharUnits.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000020#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Aaron Ballmanfff32482012-12-09 17:45:41 +000029#include "clang/Basic/TargetInfo.h"
Richard Smith4ac537b2013-07-23 08:14:48 +000030#include "clang/Lex/LiteralSupport.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000040#include "llvm/ADT/SmallString.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000041#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000042#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000043
44using namespace clang;
45
Chris Lattner8123a952008-04-10 02:22:51 +000046//===----------------------------------------------------------------------===//
47// CheckDefaultArgumentVisitor
48//===----------------------------------------------------------------------===//
49
Chris Lattner9e979552008-04-12 23:52:44 +000050namespace {
51 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
52 /// the default argument of a parameter to determine whether it
53 /// contains any ill-formed subexpressions. For example, this will
54 /// diagnose the use of local variables or parameters within the
55 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000056 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000057 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000058 Expr *DefaultArg;
59 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000060
Chris Lattner9e979552008-04-12 23:52:44 +000061 public:
Mike Stump1eb44332009-09-09 15:08:12 +000062 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000063 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000064
Chris Lattner9e979552008-04-12 23:52:44 +000065 bool VisitExpr(Expr *Node);
66 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000067 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000068 bool VisitLambdaExpr(LambdaExpr *Lambda);
John McCall045d2522013-04-09 01:56:28 +000069 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
Chris Lattner9e979552008-04-12 23:52:44 +000070 };
Chris Lattner8123a952008-04-10 02:22:51 +000071
Chris Lattner9e979552008-04-12 23:52:44 +000072 /// VisitExpr - Visit all of the children of this expression.
73 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
74 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000075 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000076 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000077 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000078 }
79
Chris Lattner9e979552008-04-12 23:52:44 +000080 /// VisitDeclRefExpr - Visit a reference to a declaration, to
81 /// determine whether this declaration can be used in the default
82 /// argument expression.
83 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000084 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000085 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
86 // C++ [dcl.fct.default]p9
87 // Default arguments are evaluated each time the function is
88 // called. The order of evaluation of function arguments is
89 // unspecified. Consequently, parameters of a function shall not
90 // be used in default argument expressions, even if they are not
91 // evaluated. Parameters of a function declared before a default
92 // argument expression are in scope and can hide namespace and
93 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000094 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000096 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000097 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000098 // C++ [dcl.fct.default]p7
99 // Local variables shall not be used in default argument
100 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +0000101 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +0000102 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000103 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000104 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000105 }
Chris Lattner8123a952008-04-10 02:22:51 +0000106
Douglas Gregor3996f232008-11-04 13:41:56 +0000107 return false;
108 }
Chris Lattner9e979552008-04-12 23:52:44 +0000109
Douglas Gregor796da182008-11-04 14:32:21 +0000110 /// VisitCXXThisExpr - Visit a C++ "this" expression.
111 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
112 // C++ [dcl.fct.default]p8:
113 // The keyword this shall not be used in a default argument of a
114 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000115 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000116 diag::err_param_default_argument_references_this)
117 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000118 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000119
John McCall045d2522013-04-09 01:56:28 +0000120 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
121 bool Invalid = false;
122 for (PseudoObjectExpr::semantics_iterator
123 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
124 Expr *E = *i;
125
126 // Look through bindings.
127 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
128 E = OVE->getSourceExpr();
129 assert(E && "pseudo-object binding without source expression?");
130 }
131
132 Invalid |= Visit(E);
133 }
134 return Invalid;
135 }
136
Douglas Gregorf0459f82012-02-10 23:30:22 +0000137 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
138 // C++11 [expr.lambda.prim]p13:
139 // A lambda-expression appearing in a default argument shall not
140 // implicitly or explicitly capture any entity.
141 if (Lambda->capture_begin() == Lambda->capture_end())
142 return false;
143
144 return S->Diag(Lambda->getLocStart(),
145 diag::err_lambda_capture_default_arg);
146 }
Chris Lattner8123a952008-04-10 02:22:51 +0000147}
148
Richard Smith0b0ca472013-04-10 06:11:48 +0000149void
150Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
151 const CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000152 // If we have an MSAny spec already, don't bother.
153 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000154 return;
155
156 const FunctionProtoType *Proto
157 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000158 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
159 if (!Proto)
160 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000161
162 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
163
164 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000165 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000166 ClearExceptions();
167 ComputedEST = EST;
168 return;
169 }
170
Richard Smith7a614d82011-06-11 17:19:42 +0000171 // FIXME: If the call to this decl is using any of its default arguments, we
172 // need to search them for potentially-throwing calls.
173
Sean Hunt001cad92011-05-10 00:49:42 +0000174 // If this function has a basic noexcept, it doesn't affect the outcome.
175 if (EST == EST_BasicNoexcept)
176 return;
177
178 // If we have a throw-all spec at this point, ignore the function.
179 if (ComputedEST == EST_None)
180 return;
181
182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
184 if (EST == EST_DynamicNone) {
185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
187 return;
188 }
189
190 // Check out noexcept specs.
191 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000192 FunctionProtoType::NoexceptResult NR =
193 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000194 assert(NR != FunctionProtoType::NR_NoNoexcept &&
195 "Must have noexcept result for EST_ComputedNoexcept.");
196 assert(NR != FunctionProtoType::NR_Dependent &&
197 "Should not generate implicit declarations for dependent cases, "
198 "and don't know how to handle them anyway.");
199
200 // noexcept(false) -> no spec on the new function
201 if (NR == FunctionProtoType::NR_Throw) {
202 ClearExceptions();
203 ComputedEST = EST_None;
204 }
205 // noexcept(true) won't change anything either.
206 return;
207 }
208
209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
214 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
215 EEnd = Proto->exception_end();
216 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000217 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000218 Exceptions.push_back(*E);
219}
220
Richard Smith7a614d82011-06-11 17:19:42 +0000221void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000222 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000223 return;
224
225 // FIXME:
226 //
227 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000228 // [An] implicit exception-specification specifies the type-id T if and
229 // only if T is allowed by the exception-specification of a function directly
230 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000231 // function it directly invokes allows all exceptions, and f shall allow no
232 // exceptions if every function it directly invokes allows no exceptions.
233 //
234 // Note in particular that if an implicit exception-specification is generated
235 // for a function containing a throw-expression, that specification can still
236 // be noexcept(true).
237 //
238 // Note also that 'directly invoked' is not defined in the standard, and there
239 // is no indication that we should only consider potentially-evaluated calls.
240 //
241 // Ultimately we should implement the intent of the standard: the exception
242 // specification should be the set of exceptions which can be thrown by the
243 // implicit definition. For now, we assume that any non-nothrow expression can
244 // throw any exception.
245
Richard Smithe6975e92012-04-17 00:58:00 +0000246 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000247 ComputedEST = EST_None;
248}
249
Anders Carlssoned961f92009-08-25 02:29:20 +0000250bool
John McCall9ae2f072010-08-23 23:25:46 +0000251Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000252 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000253 if (RequireCompleteType(Param->getLocation(), Param->getType(),
254 diag::err_typecheck_decl_incomplete_type)) {
255 Param->setInvalidDecl();
256 return true;
257 }
258
Anders Carlssoned961f92009-08-25 02:29:20 +0000259 // C++ [dcl.fct.default]p5
260 // A default argument expression is implicitly converted (clause
261 // 4) to the parameter type. The default argument expression has
262 // the same semantic constraints as the initializer expression in
263 // a declaration of a variable of the parameter type, using the
264 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000265 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
266 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000267 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
268 EqualLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000269 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000270 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000271 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000272 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000273 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000274
Richard Smith6c3af3d2013-01-17 01:17:56 +0000275 CheckCompletedExpr(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000276 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Anders Carlssoned961f92009-08-25 02:29:20 +0000278 // Okay: add the default argument to the parameter
279 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000281 // We have already instantiated this parameter; provide each of the
282 // instantiations with the uninstantiated default argument.
283 UnparsedDefaultArgInstantiationsMap::iterator InstPos
284 = UnparsedDefaultArgInstantiations.find(Param);
285 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
286 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
287 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
288
289 // We're done tracking this parameter's instantiations.
290 UnparsedDefaultArgInstantiations.erase(InstPos);
291 }
292
Anders Carlsson9351c172009-08-25 03:18:48 +0000293 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000294}
295
Chris Lattner8123a952008-04-10 02:22:51 +0000296/// ActOnParamDefaultArgument - Check whether the default argument
297/// provided for a function parameter is well-formed. If so, attach it
298/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000299void
John McCalld226f652010-08-21 09:40:31 +0000300Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000301 Expr *DefaultArg) {
302 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000303 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000304
John McCalld226f652010-08-21 09:40:31 +0000305 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000306 UnparsedDefaultArgLocs.erase(Param);
307
Chris Lattner3d1cee32008-04-08 05:04:30 +0000308 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000309 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000310 Diag(EqualLoc, diag::err_param_default_argument)
311 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000312 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000313 return;
314 }
315
Douglas Gregor6f526752010-12-16 08:48:57 +0000316 // Check for unexpanded parameter packs.
317 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
318 Param->setInvalidDecl();
319 return;
320 }
321
Anders Carlsson66e30672009-08-25 01:02:06 +0000322 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000323 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
324 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000325 Param->setInvalidDecl();
326 return;
327 }
Mike Stump1eb44332009-09-09 15:08:12 +0000328
John McCall9ae2f072010-08-23 23:25:46 +0000329 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000330}
331
Douglas Gregor61366e92008-12-24 00:01:03 +0000332/// ActOnParamUnparsedDefaultArgument - We've seen a default
333/// argument for a function parameter, but we can't parse it yet
334/// because we're inside a class definition. Note that this default
335/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000336void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000337 SourceLocation EqualLoc,
338 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000339 if (!param)
340 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000341
John McCalld226f652010-08-21 09:40:31 +0000342 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000343 if (Param)
344 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Anders Carlsson5e300d12009-06-12 16:51:40 +0000346 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000347}
348
Douglas Gregor72b505b2008-12-16 21:30:33 +0000349/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
350/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000351void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000352 if (!param)
353 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000354
John McCalld226f652010-08-21 09:40:31 +0000355 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Anders Carlsson5e300d12009-06-12 16:51:40 +0000357 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Anders Carlsson5e300d12009-06-12 16:51:40 +0000359 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000360}
361
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000362/// CheckExtraCXXDefaultArguments - Check for any extra default
363/// arguments in the declarator, which is not a function declaration
364/// or definition and therefore is not permitted to have default
365/// arguments. This routine should be invoked for every declarator
366/// that is not a function declaration or definition.
367void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
368 // C++ [dcl.fct.default]p3
369 // A default argument expression shall be specified only in the
370 // parameter-declaration-clause of a function declaration or in a
371 // template-parameter (14.1). It shall not be specified for a
372 // parameter pack. If it is specified in a
373 // parameter-declaration-clause, it shall not occur within a
374 // declarator or abstract-declarator of a parameter-declaration.
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000375 bool MightBeFunction = D.isFunctionDeclarationContext();
Chris Lattnerb28317a2009-03-28 19:18:32 +0000376 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000377 DeclaratorChunk &chunk = D.getTypeObject(i);
378 if (chunk.Kind == DeclaratorChunk::Function) {
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000379 if (MightBeFunction) {
380 // This is a function declaration. It can have default arguments, but
381 // keep looking in case its return type is a function type with default
382 // arguments.
383 MightBeFunction = false;
384 continue;
385 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000386 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
387 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000388 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000389 if (Param->hasUnparsedDefaultArg()) {
390 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000391 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000392 << SourceRange((*Toks)[1].getLocation(),
393 Toks->back().getLocation());
Douglas Gregor72b505b2008-12-16 21:30:33 +0000394 delete Toks;
395 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000396 } else if (Param->getDefaultArg()) {
397 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
398 << Param->getDefaultArg()->getSourceRange();
399 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000400 }
401 }
Richard Smith3cdbbdc2013-03-06 01:37:38 +0000402 } else if (chunk.Kind != DeclaratorChunk::Paren) {
403 MightBeFunction = false;
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000404 }
405 }
406}
407
David Majnemerf6a144f2013-06-25 23:09:30 +0000408static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
409 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
410 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
411 if (!PVD->hasDefaultArg())
412 return false;
413 if (!PVD->hasInheritedDefaultArg())
414 return true;
415 }
416 return false;
417}
418
Craig Topper1a6eac82012-09-21 04:33:26 +0000419/// MergeCXXFunctionDecl - Merge two declarations of the same C++
420/// function, once we already know that they have the same
421/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
422/// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000423bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
424 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000425 bool Invalid = false;
426
Chris Lattner3d1cee32008-04-08 05:04:30 +0000427 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000428 // For non-template functions, default arguments can be added in
429 // later declarations of a function in the same
430 // scope. Declarations in different scopes have completely
431 // distinct sets of default arguments. That is, declarations in
432 // inner scopes do not acquire default arguments from
433 // declarations in outer scopes, and vice versa. In a given
434 // function declaration, all parameters subsequent to a
435 // parameter with a default argument shall have default
436 // arguments supplied in this or previous declarations. A
437 // default argument shall not be redefined by a later
438 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000439 //
440 // C++ [dcl.fct.default]p6:
Richard Smitha41c97a2013-09-20 01:15:31 +0000441 // Except for member functions of class templates, the default arguments
442 // in a member function definition that appears outside of the class
443 // definition are added to the set of default arguments provided by the
Douglas Gregor6cc15182009-09-11 18:44:32 +0000444 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000445 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
446 ParmVarDecl *OldParam = Old->getParamDecl(p);
447 ParmVarDecl *NewParam = New->getParamDecl(p);
448
James Molloy9cda03f2012-03-13 08:55:35 +0000449 bool OldParamHasDfl = OldParam->hasDefaultArg();
450 bool NewParamHasDfl = NewParam->hasDefaultArg();
451
452 NamedDecl *ND = Old;
Richard Smitha41c97a2013-09-20 01:15:31 +0000453
454 // The declaration context corresponding to the scope is the semantic
455 // parent, unless this is a local function declaration, in which case
456 // it is that surrounding function.
457 DeclContext *ScopeDC = New->getLexicalDeclContext();
458 if (!ScopeDC->isFunctionOrMethod())
459 ScopeDC = New->getDeclContext();
460 if (S && !isDeclInScope(ND, ScopeDC, S) &&
461 !New->getDeclContext()->isRecord())
James Molloy9cda03f2012-03-13 08:55:35 +0000462 // Ignore default parameters of old decl if they are not in
Richard Smitha41c97a2013-09-20 01:15:31 +0000463 // the same scope and this is not an out-of-line definition of
464 // a member function.
James Molloy9cda03f2012-03-13 08:55:35 +0000465 OldParamHasDfl = false;
466
467 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000468
Francois Pichet8d051e02011-04-10 03:03:52 +0000469 unsigned DiagDefaultParamID =
470 diag::err_param_default_argument_redefinition;
471
472 // MSVC accepts that default parameters be redefined for member functions
473 // of template class. The new default parameter's value is ignored.
474 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000475 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000476 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
477 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000478 // Merge the old default argument into the new parameter.
479 NewParam->setHasInheritedDefaultArg();
480 if (OldParam->hasUninstantiatedDefaultArg())
481 NewParam->setUninstantiatedDefaultArg(
482 OldParam->getUninstantiatedDefaultArg());
483 else
484 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000485 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000486 Invalid = false;
487 }
488 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000489
Francois Pichet8cf90492011-04-10 04:58:30 +0000490 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
491 // hint here. Alternatively, we could walk the type-source information
492 // for NewParam to find the last source location in the type... but it
493 // isn't worth the effort right now. This is the kind of test case that
494 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000495 // int f(int);
496 // void g(int (*fp)(int) = f);
497 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000498 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000499 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000500
501 // Look for the function declaration where the default argument was
502 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000503 for (FunctionDecl *Older = Old->getPreviousDecl();
504 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000505 if (!Older->getParamDecl(p)->hasDefaultArg())
506 break;
507
508 OldParam = Older->getParamDecl(p);
509 }
510
511 Diag(OldParam->getLocation(), diag::note_previous_definition)
512 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000513 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000514 // Merge the old default argument into the new parameter.
515 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000516 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000517 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000518 if (OldParam->hasUninstantiatedDefaultArg())
519 NewParam->setUninstantiatedDefaultArg(
520 OldParam->getUninstantiatedDefaultArg());
521 else
John McCall3d6c1782010-05-04 01:53:42 +0000522 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000523 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000524 if (New->getDescribedFunctionTemplate()) {
525 // Paragraph 4, quoted above, only applies to non-template functions.
526 Diag(NewParam->getLocation(),
527 diag::err_param_default_argument_template_redecl)
528 << NewParam->getDefaultArgRange();
529 Diag(Old->getLocation(), diag::note_template_prev_declaration)
530 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000531 } else if (New->getTemplateSpecializationKind()
532 != TSK_ImplicitInstantiation &&
533 New->getTemplateSpecializationKind() != TSK_Undeclared) {
534 // C++ [temp.expr.spec]p21:
535 // Default function arguments shall not be specified in a declaration
536 // or a definition for one of the following explicit specializations:
537 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000538 // - the explicit specialization of a member function template;
539 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000540 // template where the class template specialization to which the
541 // member function specialization belongs is implicitly
542 // instantiated.
543 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
544 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
545 << New->getDeclName()
546 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000547 } else if (New->getDeclContext()->isDependentContext()) {
548 // C++ [dcl.fct.default]p6 (DR217):
549 // Default arguments for a member function of a class template shall
550 // be specified on the initial declaration of the member function
551 // within the class template.
552 //
553 // Reading the tea leaves a bit in DR217 and its reference to DR205
554 // leads me to the conclusion that one cannot add default function
555 // arguments for an out-of-line definition of a member function of a
556 // dependent type.
557 int WhichKind = 2;
558 if (CXXRecordDecl *Record
559 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
560 if (Record->getDescribedClassTemplate())
561 WhichKind = 0;
562 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
563 WhichKind = 1;
564 else
565 WhichKind = 2;
566 }
567
568 Diag(NewParam->getLocation(),
569 diag::err_param_default_argument_member_template_redecl)
570 << WhichKind
571 << NewParam->getDefaultArgRange();
572 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000573 }
574 }
575
Richard Smithb8abff62012-11-28 03:45:24 +0000576 // DR1344: If a default argument is added outside a class definition and that
577 // default argument makes the function a special member function, the program
578 // is ill-formed. This can only happen for constructors.
579 if (isa<CXXConstructorDecl>(New) &&
580 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
581 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
582 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
583 if (NewSM != OldSM) {
584 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
585 assert(NewParam->hasDefaultArg());
586 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
587 << NewParam->getDefaultArgRange() << NewSM;
588 Diag(Old->getLocation(), diag::note_previous_declaration);
589 }
590 }
591
Richard Smithff234882012-02-20 23:28:05 +0000592 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000593 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000594 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000595 if (New->isConstexpr() != Old->isConstexpr()) {
596 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
597 << New << New->isConstexpr();
598 Diag(Old->getLocation(), diag::note_previous_declaration);
599 Invalid = true;
600 }
601
David Majnemerf6a144f2013-06-25 23:09:30 +0000602 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000603 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000604 // the only declaration of the function or function template in the
605 // translation unit.
606 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
607 functionDeclHasDefaultArgument(Old)) {
608 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
609 Diag(Old->getLocation(), diag::note_previous_declaration);
610 Invalid = true;
611 }
612
Douglas Gregore13ad832010-02-12 07:32:17 +0000613 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000614 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000615
Douglas Gregorcda9c672009-02-16 17:45:42 +0000616 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000617}
618
Sebastian Redl60618fa2011-03-12 11:50:43 +0000619/// \brief Merge the exception specifications of two variable declarations.
620///
621/// This is called when there's a redeclaration of a VarDecl. The function
622/// checks if the redeclaration might have an exception specification and
623/// validates compatibility and merges the specs if necessary.
624void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
625 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000626 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000627 return;
628
629 assert(Context.hasSameType(New->getType(), Old->getType()) &&
630 "Should only be called if types are otherwise the same.");
631
632 QualType NewType = New->getType();
633 QualType OldType = Old->getType();
634
635 // We're only interested in pointers and references to functions, as well
636 // as pointers to member functions.
637 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
638 NewType = R->getPointeeType();
639 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
640 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
641 NewType = P->getPointeeType();
642 OldType = OldType->getAs<PointerType>()->getPointeeType();
643 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
644 NewType = M->getPointeeType();
645 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
646 }
647
648 if (!NewType->isFunctionProtoType())
649 return;
650
651 // There's lots of special cases for functions. For function pointers, system
652 // libraries are hopefully not as broken so that we don't need these
653 // workarounds.
654 if (CheckEquivalentExceptionSpec(
655 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
656 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
657 New->setInvalidDecl();
658 }
659}
660
Chris Lattner3d1cee32008-04-08 05:04:30 +0000661/// CheckCXXDefaultArguments - Verify that the default arguments for a
662/// function declaration are well-formed according to C++
663/// [dcl.fct.default].
664void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
665 unsigned NumParams = FD->getNumParams();
666 unsigned p;
667
668 // Find first parameter with a default argument
669 for (p = 0; p < NumParams; ++p) {
670 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000671 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000672 break;
673 }
674
675 // C++ [dcl.fct.default]p4:
676 // In a given function declaration, all parameters
677 // subsequent to a parameter with a default argument shall
678 // have default arguments supplied in this or previous
679 // declarations. A default argument shall not be redefined
680 // by a later declaration (not even to the same value).
681 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000682 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000683 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000684 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000685 if (Param->isInvalidDecl())
686 /* We already complained about this parameter. */;
687 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000688 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000689 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000690 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000691 else
Mike Stump1eb44332009-09-09 15:08:12 +0000692 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000693 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattner3d1cee32008-04-08 05:04:30 +0000695 LastMissingDefaultArg = p;
696 }
697 }
698
699 if (LastMissingDefaultArg > 0) {
700 // Some default arguments were missing. Clear out all of the
701 // default arguments up to (and including) the last missing
702 // default argument, so that we leave the function parameters
703 // in a semantically valid state.
704 for (p = 0; p <= LastMissingDefaultArg; ++p) {
705 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000706 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000707 Param->setDefaultArg(0);
708 }
709 }
710 }
711}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000712
Richard Smith9f569cc2011-10-01 02:31:28 +0000713// CheckConstexprParameterTypes - Check whether a function's parameter types
714// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000715// diagnostic and return false.
716static bool CheckConstexprParameterTypes(Sema &SemaRef,
717 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000718 unsigned ArgIndex = 0;
719 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
720 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
721 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
722 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
723 SourceLocation ParamLoc = PD->getLocation();
724 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000725 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000726 diag::err_constexpr_non_literal_param,
727 ArgIndex+1, PD->getSourceRange(),
728 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000729 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000730 }
Joao Matos17d35c32012-08-31 22:18:20 +0000731 return true;
732}
733
734/// \brief Get diagnostic %select index for tag kind for
735/// record diagnostic message.
736/// WARNING: Indexes apply to particular diagnostics only!
737///
738/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000739static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000740 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000741 case TTK_Struct: return 0;
742 case TTK_Interface: return 1;
743 case TTK_Class: return 2;
744 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000745 }
Joao Matos17d35c32012-08-31 22:18:20 +0000746}
747
748// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
749// the requirements of a constexpr function definition or a constexpr
750// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000751// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000752//
Richard Smith86c3ae42012-02-13 03:54:03 +0000753// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
754bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000755 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
756 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000757 // C++11 [dcl.constexpr]p4:
758 // The definition of a constexpr constructor shall satisfy the following
759 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000760 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000761 const CXXRecordDecl *RD = MD->getParent();
762 if (RD->getNumVBases()) {
763 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
764 << isa<CXXConstructorDecl>(NewFD)
765 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
766 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
767 E = RD->vbases_end(); I != E; ++I)
768 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000769 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000770 return false;
771 }
Richard Smith35340502012-01-13 04:54:00 +0000772 }
773
774 if (!isa<CXXConstructorDecl>(NewFD)) {
775 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000776 // The definition of a constexpr function shall satisfy the following
777 // constraints:
778 // - it shall not be virtual;
779 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
780 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000781 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000782
Richard Smith86c3ae42012-02-13 03:54:03 +0000783 // If it's not obvious why this function is virtual, find an overridden
784 // function which uses the 'virtual' keyword.
785 const CXXMethodDecl *WrittenVirtual = Method;
786 while (!WrittenVirtual->isVirtualAsWritten())
787 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
788 if (WrittenVirtual != Method)
789 Diag(WrittenVirtual->getLocation(),
790 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000791 return false;
792 }
793
794 // - its return type shall be a literal type;
795 QualType RT = NewFD->getResultType();
796 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000797 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000798 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000799 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000800 }
801
Richard Smith35340502012-01-13 04:54:00 +0000802 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000803 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000804 return false;
805
Richard Smith9f569cc2011-10-01 02:31:28 +0000806 return true;
807}
808
809/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000810/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000811///
Richard Smitha10b9782013-04-22 15:31:51 +0000812/// \return true if the body is OK (maybe only as an extension), false if we
813/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000814static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000815 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
816 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000817 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
818 // contain only
819 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
820 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
821 switch ((*DclIt)->getKind()) {
822 case Decl::StaticAssert:
823 case Decl::Using:
824 case Decl::UsingShadow:
825 case Decl::UsingDirective:
826 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000827 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000828 // - static_assert-declarations
829 // - using-declarations,
830 // - using-directives,
831 continue;
832
833 case Decl::Typedef:
834 case Decl::TypeAlias: {
835 // - typedef declarations and alias-declarations that do not define
836 // classes or enumerations,
837 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
838 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
839 // Don't allow variably-modified types in constexpr functions.
840 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
841 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
842 << TL.getSourceRange() << TL.getType()
843 << isa<CXXConstructorDecl>(Dcl);
844 return false;
845 }
846 continue;
847 }
848
849 case Decl::Enum:
850 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000851 // C++1y allows types to be defined, not just declared.
852 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
853 SemaRef.Diag(DS->getLocStart(),
854 SemaRef.getLangOpts().CPlusPlus1y
855 ? diag::warn_cxx11_compat_constexpr_type_definition
856 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000857 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000858 continue;
859
Richard Smitha10b9782013-04-22 15:31:51 +0000860 case Decl::EnumConstant:
861 case Decl::IndirectField:
862 case Decl::ParmVar:
863 // These can only appear with other declarations which are banned in
864 // C++11 and permitted in C++1y, so ignore them.
865 continue;
866
867 case Decl::Var: {
868 // C++1y [dcl.constexpr]p3 allows anything except:
869 // a definition of a variable of non-literal type or of static or
870 // thread storage duration or for which no initialization is performed.
871 VarDecl *VD = cast<VarDecl>(*DclIt);
872 if (VD->isThisDeclarationADefinition()) {
873 if (VD->isStaticLocal()) {
874 SemaRef.Diag(VD->getLocation(),
875 diag::err_constexpr_local_var_static)
876 << isa<CXXConstructorDecl>(Dcl)
877 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
878 return false;
879 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000880 if (!VD->getType()->isDependentType() &&
881 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000882 VD->getLocation(), VD->getType(),
883 diag::err_constexpr_local_var_non_literal_type,
884 isa<CXXConstructorDecl>(Dcl)))
885 return false;
886 if (!VD->hasInit()) {
887 SemaRef.Diag(VD->getLocation(),
888 diag::err_constexpr_local_var_no_init)
889 << isa<CXXConstructorDecl>(Dcl);
890 return false;
891 }
892 }
893 SemaRef.Diag(VD->getLocation(),
894 SemaRef.getLangOpts().CPlusPlus1y
895 ? diag::warn_cxx11_compat_constexpr_local_var
896 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000897 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000898 continue;
899 }
900
901 case Decl::NamespaceAlias:
902 case Decl::Function:
903 // These are disallowed in C++11 and permitted in C++1y. Allow them
904 // everywhere as an extension.
905 if (!Cxx1yLoc.isValid())
906 Cxx1yLoc = DS->getLocStart();
907 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000908
909 default:
910 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
911 << isa<CXXConstructorDecl>(Dcl);
912 return false;
913 }
914 }
915
916 return true;
917}
918
919/// Check that the given field is initialized within a constexpr constructor.
920///
921/// \param Dcl The constexpr constructor being checked.
922/// \param Field The field being checked. This may be a member of an anonymous
923/// struct or union nested within the class being checked.
924/// \param Inits All declarations, including anonymous struct/union members and
925/// indirect members, for which any initialization was provided.
926/// \param Diagnosed Set to true if an error is produced.
927static void CheckConstexprCtorInitializer(Sema &SemaRef,
928 const FunctionDecl *Dcl,
929 FieldDecl *Field,
930 llvm::SmallSet<Decl*, 16> &Inits,
931 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000932 if (Field->isInvalidDecl())
933 return;
934
Douglas Gregord61db332011-10-10 17:22:13 +0000935 if (Field->isUnnamedBitfield())
936 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000937
938 if (Field->isAnonymousStructOrUnion() &&
939 Field->getType()->getAsCXXRecordDecl()->isEmpty())
940 return;
941
Richard Smith9f569cc2011-10-01 02:31:28 +0000942 if (!Inits.count(Field)) {
943 if (!Diagnosed) {
944 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
945 Diagnosed = true;
946 }
947 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
948 } else if (Field->isAnonymousStructOrUnion()) {
949 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
950 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
951 I != E; ++I)
952 // If an anonymous union contains an anonymous struct of which any member
953 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000954 if (!RD->isUnion() || Inits.count(*I))
955 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000956 }
957}
958
Richard Smitha10b9782013-04-22 15:31:51 +0000959/// Check the provided statement is allowed in a constexpr function
960/// definition.
961static bool
962CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000963 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000964 SourceLocation &Cxx1yLoc) {
965 // - its function-body shall be [...] a compound-statement that contains only
966 switch (S->getStmtClass()) {
967 case Stmt::NullStmtClass:
968 // - null statements,
969 return true;
970
971 case Stmt::DeclStmtClass:
972 // - static_assert-declarations
973 // - using-declarations,
974 // - using-directives,
975 // - typedef declarations and alias-declarations that do not define
976 // classes or enumerations,
977 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
978 return false;
979 return true;
980
981 case Stmt::ReturnStmtClass:
982 // - and exactly one return statement;
983 if (isa<CXXConstructorDecl>(Dcl)) {
984 // C++1y allows return statements in constexpr constructors.
985 if (!Cxx1yLoc.isValid())
986 Cxx1yLoc = S->getLocStart();
987 return true;
988 }
989
990 ReturnStmts.push_back(S->getLocStart());
991 return true;
992
993 case Stmt::CompoundStmtClass: {
994 // C++1y allows compound-statements.
995 if (!Cxx1yLoc.isValid())
996 Cxx1yLoc = S->getLocStart();
997
998 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
999 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
1000 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1001 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
1002 Cxx1yLoc))
1003 return false;
1004 }
1005 return true;
1006 }
1007
1008 case Stmt::AttributedStmtClass:
1009 if (!Cxx1yLoc.isValid())
1010 Cxx1yLoc = S->getLocStart();
1011 return true;
1012
1013 case Stmt::IfStmtClass: {
1014 // C++1y allows if-statements.
1015 if (!Cxx1yLoc.isValid())
1016 Cxx1yLoc = S->getLocStart();
1017
1018 IfStmt *If = cast<IfStmt>(S);
1019 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1020 Cxx1yLoc))
1021 return false;
1022 if (If->getElse() &&
1023 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1024 Cxx1yLoc))
1025 return false;
1026 return true;
1027 }
1028
1029 case Stmt::WhileStmtClass:
1030 case Stmt::DoStmtClass:
1031 case Stmt::ForStmtClass:
1032 case Stmt::CXXForRangeStmtClass:
1033 case Stmt::ContinueStmtClass:
1034 // C++1y allows all of these. We don't allow them as extensions in C++11,
1035 // because they don't make sense without variable mutation.
1036 if (!SemaRef.getLangOpts().CPlusPlus1y)
1037 break;
1038 if (!Cxx1yLoc.isValid())
1039 Cxx1yLoc = S->getLocStart();
1040 for (Stmt::child_range Children = S->children(); Children; ++Children)
1041 if (*Children &&
1042 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1043 Cxx1yLoc))
1044 return false;
1045 return true;
1046
1047 case Stmt::SwitchStmtClass:
1048 case Stmt::CaseStmtClass:
1049 case Stmt::DefaultStmtClass:
1050 case Stmt::BreakStmtClass:
1051 // C++1y allows switch-statements, and since they don't need variable
1052 // mutation, we can reasonably allow them in C++11 as an extension.
1053 if (!Cxx1yLoc.isValid())
1054 Cxx1yLoc = S->getLocStart();
1055 for (Stmt::child_range Children = S->children(); Children; ++Children)
1056 if (*Children &&
1057 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1058 Cxx1yLoc))
1059 return false;
1060 return true;
1061
1062 default:
1063 if (!isa<Expr>(S))
1064 break;
1065
1066 // C++1y allows expression-statements.
1067 if (!Cxx1yLoc.isValid())
1068 Cxx1yLoc = S->getLocStart();
1069 return true;
1070 }
1071
1072 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1073 << isa<CXXConstructorDecl>(Dcl);
1074 return false;
1075}
1076
Richard Smith9f569cc2011-10-01 02:31:28 +00001077/// Check the body for the given constexpr function declaration only contains
1078/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1079///
1080/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001081bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001082 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001083 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001084 // The definition of a constexpr function shall satisfy the following
1085 // constraints: [...]
1086 // - its function-body shall be = delete, = default, or a
1087 // compound-statement
1088 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001089 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001090 // In the definition of a constexpr constructor, [...]
1091 // - its function-body shall not be a function-try-block;
1092 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1093 << isa<CXXConstructorDecl>(Dcl);
1094 return false;
1095 }
1096
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001097 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001098
1099 // - its function-body shall be [...] a compound-statement that contains only
1100 // [... list of cases ...]
1101 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1102 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001103 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1104 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001105 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1106 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001107 }
1108
Richard Smitha10b9782013-04-22 15:31:51 +00001109 if (Cxx1yLoc.isValid())
1110 Diag(Cxx1yLoc,
1111 getLangOpts().CPlusPlus1y
1112 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1113 : diag::ext_constexpr_body_invalid_stmt)
1114 << isa<CXXConstructorDecl>(Dcl);
1115
Richard Smith9f569cc2011-10-01 02:31:28 +00001116 if (const CXXConstructorDecl *Constructor
1117 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1118 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001119 // DR1359:
1120 // - every non-variant non-static data member and base class sub-object
1121 // shall be initialized;
1122 // - if the class is a non-empty union, or for each non-empty anonymous
1123 // union member of a non-union class, exactly one non-static data member
1124 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001125 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001126 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001127 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1128 return false;
1129 }
Richard Smith6e433752011-10-10 16:38:04 +00001130 } else if (!Constructor->isDependentContext() &&
1131 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001132 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1133
1134 // Skip detailed checking if we have enough initializers, and we would
1135 // allow at most one initializer per member.
1136 bool AnyAnonStructUnionMembers = false;
1137 unsigned Fields = 0;
1138 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1139 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001140 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001141 AnyAnonStructUnionMembers = true;
1142 break;
1143 }
1144 }
1145 if (AnyAnonStructUnionMembers ||
1146 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1147 // Check initialization of non-static data members. Base classes are
1148 // always initialized so do not need to be checked. Dependent bases
1149 // might not have initializers in the member initializer list.
1150 llvm::SmallSet<Decl*, 16> Inits;
1151 for (CXXConstructorDecl::init_const_iterator
1152 I = Constructor->init_begin(), E = Constructor->init_end();
1153 I != E; ++I) {
1154 if (FieldDecl *FD = (*I)->getMember())
1155 Inits.insert(FD);
1156 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1157 Inits.insert(ID->chain_begin(), ID->chain_end());
1158 }
1159
1160 bool Diagnosed = false;
1161 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1162 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001163 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001164 if (Diagnosed)
1165 return false;
1166 }
1167 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001168 } else {
1169 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001170 // C++1y doesn't require constexpr functions to contain a 'return'
1171 // statement. We still do, unless the return type is void, because
1172 // otherwise if there's no return statement, the function cannot
1173 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001174 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001175 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001176 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1177 : diag::err_constexpr_body_no_return);
1178 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001179 }
1180 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001181 Diag(ReturnStmts.back(),
1182 getLangOpts().CPlusPlus1y
1183 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1184 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001185 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1186 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001187 }
1188 }
1189
Richard Smith5ba73e12012-02-04 00:33:54 +00001190 // C++11 [dcl.constexpr]p5:
1191 // if no function argument values exist such that the function invocation
1192 // substitution would produce a constant expression, the program is
1193 // ill-formed; no diagnostic required.
1194 // C++11 [dcl.constexpr]p3:
1195 // - every constructor call and implicit conversion used in initializing the
1196 // return value shall be one of those allowed in a constant expression.
1197 // C++11 [dcl.constexpr]p4:
1198 // - every constructor involved in initializing non-static data members and
1199 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001200 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001201 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001202 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001203 << isa<CXXConstructorDecl>(Dcl);
1204 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1205 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001206 // Don't return false here: we allow this for compatibility in
1207 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001208 }
1209
Richard Smith9f569cc2011-10-01 02:31:28 +00001210 return true;
1211}
1212
Douglas Gregorb48fe382008-10-31 09:07:45 +00001213/// isCurrentClassName - Determine whether the identifier II is the
1214/// name of the class type currently being defined. In the case of
1215/// nested classes, this will only return true if II is the name of
1216/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001217bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1218 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001219 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001220
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001221 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001222 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001223 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001224 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1225 } else
1226 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1227
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001228 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001229 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001230 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001231}
1232
Douglas Gregor229d47a2012-11-10 07:24:09 +00001233/// \brief Determine whether the given class is a base class of the given
1234/// class, including looking at dependent bases.
1235static bool findCircularInheritance(const CXXRecordDecl *Class,
1236 const CXXRecordDecl *Current) {
1237 SmallVector<const CXXRecordDecl*, 8> Queue;
1238
1239 Class = Class->getCanonicalDecl();
1240 while (true) {
1241 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1242 E = Current->bases_end();
1243 I != E; ++I) {
1244 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1245 if (!Base)
1246 continue;
1247
1248 Base = Base->getDefinition();
1249 if (!Base)
1250 continue;
1251
1252 if (Base->getCanonicalDecl() == Class)
1253 return true;
1254
1255 Queue.push_back(Base);
1256 }
1257
1258 if (Queue.empty())
1259 return false;
1260
Robert Wilhelm344472e2013-08-23 16:11:15 +00001261 Current = Queue.pop_back_val();
Douglas Gregor229d47a2012-11-10 07:24:09 +00001262 }
1263
1264 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001265}
1266
Mike Stump1eb44332009-09-09 15:08:12 +00001267/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001268///
1269/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1270/// and returns NULL otherwise.
1271CXXBaseSpecifier *
1272Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1273 SourceRange SpecifierRange,
1274 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001275 TypeSourceInfo *TInfo,
1276 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001277 QualType BaseType = TInfo->getType();
1278
Douglas Gregor2943aed2009-03-03 04:44:36 +00001279 // C++ [class.union]p1:
1280 // A union shall not have base classes.
1281 if (Class->isUnion()) {
1282 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1283 << SpecifierRange;
1284 return 0;
1285 }
1286
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001287 if (EllipsisLoc.isValid() &&
1288 !TInfo->getType()->containsUnexpandedParameterPack()) {
1289 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1290 << TInfo->getTypeLoc().getSourceRange();
1291 EllipsisLoc = SourceLocation();
1292 }
Douglas Gregord777e282012-11-10 01:18:17 +00001293
1294 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1295
1296 if (BaseType->isDependentType()) {
1297 // Make sure that we don't have circular inheritance among our dependent
1298 // bases. For non-dependent bases, the check for completeness below handles
1299 // this.
1300 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1301 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1302 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001303 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001304 Diag(BaseLoc, diag::err_circular_inheritance)
1305 << BaseType << Context.getTypeDeclType(Class);
1306
1307 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1308 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1309 << BaseType;
1310
1311 return 0;
1312 }
1313 }
1314
Mike Stump1eb44332009-09-09 15:08:12 +00001315 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001316 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001317 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001318 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001319
1320 // Base specifiers must be record types.
1321 if (!BaseType->isRecordType()) {
1322 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1323 return 0;
1324 }
1325
1326 // C++ [class.union]p1:
1327 // A union shall not be used as a base class.
1328 if (BaseType->isUnionType()) {
1329 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1330 return 0;
1331 }
1332
1333 // C++ [class.derived]p2:
1334 // The class-name in a base-specifier shall not be an incompletely
1335 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001336 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001337 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001338 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001339 return 0;
John McCall572fc622010-08-17 07:23:57 +00001340 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001341
Eli Friedman1d954f62009-08-15 21:55:26 +00001342 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001343 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001344 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001345 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001346 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001347 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001348 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001349
Anders Carlsson1d209272011-03-25 14:55:14 +00001350 // C++ [class]p3:
1351 // If a class is marked final and it appears as a base-type-specifier in
1352 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001353 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001354 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1355 << CXXBaseDecl->getDeclName();
1356 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1357 << CXXBaseDecl->getDeclName();
1358 return 0;
1359 }
1360
John McCall572fc622010-08-17 07:23:57 +00001361 if (BaseDecl->isInvalidDecl())
1362 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001363
1364 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001365 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001366 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001367 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001368}
1369
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001370/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1371/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001372/// example:
1373/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001374/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001375BaseResult
John McCalld226f652010-08-21 09:40:31 +00001376Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001377 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001378 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001379 ParsedType basetype, SourceLocation BaseLoc,
1380 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001381 if (!classdecl)
1382 return true;
1383
Douglas Gregor40808ce2009-03-09 23:48:35 +00001384 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001385 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001386 if (!Class)
1387 return true;
1388
Richard Smith05321402013-02-19 23:47:15 +00001389 // We do not support any C++11 attributes on base-specifiers yet.
1390 // Diagnose any attributes we see.
1391 if (!Attributes.empty()) {
1392 for (AttributeList *Attr = Attributes.getList(); Attr;
1393 Attr = Attr->getNext()) {
1394 if (Attr->isInvalid() ||
1395 Attr->getKind() == AttributeList::IgnoredAttribute)
1396 continue;
1397 Diag(Attr->getLoc(),
1398 Attr->getKind() == AttributeList::UnknownAttribute
1399 ? diag::warn_unknown_attribute_ignored
1400 : diag::err_base_specifier_attribute)
1401 << Attr->getName();
1402 }
1403 }
1404
Nick Lewycky56062202010-07-26 16:56:01 +00001405 TypeSourceInfo *TInfo = 0;
1406 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001407
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001408 if (EllipsisLoc.isInvalid() &&
1409 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001410 UPPC_BaseType))
1411 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001412
Douglas Gregor2943aed2009-03-03 04:44:36 +00001413 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001414 Virtual, Access, TInfo,
1415 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001416 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001417 else
1418 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Douglas Gregor2943aed2009-03-03 04:44:36 +00001420 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001421}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001422
Douglas Gregor2943aed2009-03-03 04:44:36 +00001423/// \brief Performs the actual work of attaching the given base class
1424/// specifiers to a C++ class.
1425bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1426 unsigned NumBases) {
1427 if (NumBases == 0)
1428 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001429
1430 // Used to keep track of which base types we have already seen, so
1431 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001432 // that the key is always the unqualified canonical type of the base
1433 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001434 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1435
1436 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001437 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001438 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001439 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001440 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001441 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001442 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001443
1444 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1445 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001446 // C++ [class.mi]p3:
1447 // A class shall not be specified as a direct base class of a
1448 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001449 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001450 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001451 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001452 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001453
1454 // Delete the duplicate base class specifier; we're going to
1455 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001456 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001457
1458 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001459 } else {
1460 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001461 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001462 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001463 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1464 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1465 if (Class->isInterface() &&
1466 (!RD->isInterface() ||
1467 KnownBase->getAccessSpecifier() != AS_public)) {
1468 // The Microsoft extension __interface does not permit bases that
1469 // are not themselves public interfaces.
1470 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1471 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1472 << RD->getSourceRange();
1473 Invalid = true;
1474 }
1475 if (RD->hasAttr<WeakAttr>())
1476 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1477 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001478 }
1479 }
1480
1481 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001482 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001483
1484 // Delete the remaining (good) base class specifiers, since their
1485 // data has been copied into the CXXRecordDecl.
1486 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001487 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001488
1489 return Invalid;
1490}
1491
1492/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1493/// class, after checking whether there are any duplicate base
1494/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001495void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001496 unsigned NumBases) {
1497 if (!ClassDecl || !Bases || !NumBases)
1498 return;
1499
1500 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001501 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001502}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001503
Douglas Gregora8f32e02009-10-06 17:59:45 +00001504/// \brief Determine whether the type \p Derived is a C++ class that is
1505/// derived from the type \p Base.
1506bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001507 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001508 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001509
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001510 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001511 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001512 return false;
1513
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001514 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001515 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001516 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001517
1518 // If either the base or the derived type is invalid, don't try to
1519 // check whether one is derived from the other.
1520 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1521 return false;
1522
John McCall86ff3082010-02-04 22:26:26 +00001523 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1524 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001525}
1526
1527/// \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, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001530 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001531 return false;
1532
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;
1540
Douglas Gregora8f32e02009-10-06 17:59:45 +00001541 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1542}
1543
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001544void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001545 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001546 assert(BasePathArray.empty() && "Base path array must be empty!");
1547 assert(Paths.isRecordingPaths() && "Must record paths!");
1548
1549 const CXXBasePath &Path = Paths.front();
1550
1551 // We first go backward and check if we have a virtual base.
1552 // FIXME: It would be better if CXXBasePath had the base specifier for
1553 // the nearest virtual base.
1554 unsigned Start = 0;
1555 for (unsigned I = Path.size(); I != 0; --I) {
1556 if (Path[I - 1].Base->isVirtual()) {
1557 Start = I - 1;
1558 break;
1559 }
1560 }
1561
1562 // Now add all bases.
1563 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001564 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001565}
1566
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001567/// \brief Determine whether the given base path includes a virtual
1568/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001569bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1570 for (CXXCastPath::const_iterator B = BasePath.begin(),
1571 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001572 B != BEnd; ++B)
1573 if ((*B)->isVirtual())
1574 return true;
1575
1576 return false;
1577}
1578
Douglas Gregora8f32e02009-10-06 17:59:45 +00001579/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1580/// conversion (where Derived and Base are class types) is
1581/// well-formed, meaning that the conversion is unambiguous (and
1582/// that all of the base classes are accessible). Returns true
1583/// and emits a diagnostic if the code is ill-formed, returns false
1584/// otherwise. Loc is the location where this routine should point to
1585/// if there is an error, and Range is the source range to highlight
1586/// if there is an error.
1587bool
1588Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001589 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001590 unsigned AmbigiousBaseConvID,
1591 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001592 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001593 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001594 // First, determine whether the path from Derived to Base is
1595 // ambiguous. This is slightly more expensive than checking whether
1596 // the Derived to Base conversion exists, because here we need to
1597 // explore multiple paths to determine if there is an ambiguity.
1598 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1599 /*DetectVirtual=*/false);
1600 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1601 assert(DerivationOkay &&
1602 "Can only be used with a derived-to-base conversion");
1603 (void)DerivationOkay;
1604
1605 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001606 if (InaccessibleBaseID) {
1607 // Check that the base class can be accessed.
1608 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1609 InaccessibleBaseID)) {
1610 case AR_inaccessible:
1611 return true;
1612 case AR_accessible:
1613 case AR_dependent:
1614 case AR_delayed:
1615 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001616 }
John McCall6b2accb2010-02-10 09:31:12 +00001617 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001618
1619 // Build a base path if necessary.
1620 if (BasePath)
1621 BuildBasePathArray(Paths, *BasePath);
1622 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001623 }
1624
David Majnemer2f686692013-06-22 06:43:58 +00001625 if (AmbigiousBaseConvID) {
1626 // We know that the derived-to-base conversion is ambiguous, and
1627 // we're going to produce a diagnostic. Perform the derived-to-base
1628 // search just one more time to compute all of the possible paths so
1629 // that we can print them out. This is more expensive than any of
1630 // the previous derived-to-base checks we've done, but at this point
1631 // performance isn't as much of an issue.
1632 Paths.clear();
1633 Paths.setRecordingPaths(true);
1634 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1635 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1636 (void)StillOkay;
1637
1638 // Build up a textual representation of the ambiguous paths, e.g.,
1639 // D -> B -> A, that will be used to illustrate the ambiguous
1640 // conversions in the diagnostic. We only print one of the paths
1641 // to each base class subobject.
1642 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1643
1644 Diag(Loc, AmbigiousBaseConvID)
1645 << Derived << Base << PathDisplayStr << Range << Name;
1646 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001647 return true;
1648}
1649
1650bool
1651Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001652 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001653 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001654 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001655 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001656 IgnoreAccess ? 0
1657 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001658 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001659 Loc, Range, DeclarationName(),
1660 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001661}
1662
1663
1664/// @brief Builds a string representing ambiguous paths from a
1665/// specific derived class to different subobjects of the same base
1666/// class.
1667///
1668/// This function builds a string that can be used in error messages
1669/// to show the different paths that one can take through the
1670/// inheritance hierarchy to go from the derived class to different
1671/// subobjects of a base class. The result looks something like this:
1672/// @code
1673/// struct D -> struct B -> struct A
1674/// struct D -> struct C -> struct A
1675/// @endcode
1676std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1677 std::string PathDisplayStr;
1678 std::set<unsigned> DisplayedPaths;
1679 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1680 Path != Paths.end(); ++Path) {
1681 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1682 // We haven't displayed a path to this particular base
1683 // class subobject yet.
1684 PathDisplayStr += "\n ";
1685 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1686 for (CXXBasePath::const_iterator Element = Path->begin();
1687 Element != Path->end(); ++Element)
1688 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1689 }
1690 }
1691
1692 return PathDisplayStr;
1693}
1694
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001695//===----------------------------------------------------------------------===//
1696// C++ class member Handling
1697//===----------------------------------------------------------------------===//
1698
Abramo Bagnara6206d532010-06-05 05:09:32 +00001699/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001700bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1701 SourceLocation ASLoc,
1702 SourceLocation ColonLoc,
1703 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001704 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001705 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001706 ASLoc, ColonLoc);
1707 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001708 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001709}
1710
Richard Smitha4b39652012-08-06 03:25:17 +00001711/// CheckOverrideControl - Check C++11 override control semantics.
Eli Friedmandae92712013-09-05 23:51:03 +00001712void Sema::CheckOverrideControl(NamedDecl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001713 if (D->isInvalidDecl())
1714 return;
1715
Eli Friedmandae92712013-09-05 23:51:03 +00001716 // We only care about "override" and "final" declarations.
1717 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1718 return;
Anders Carlsson9e682d92011-01-20 05:57:14 +00001719
Eli Friedmandae92712013-09-05 23:51:03 +00001720 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001721
Eli Friedmandae92712013-09-05 23:51:03 +00001722 // We can't check dependent instance methods.
1723 if (MD && MD->isInstance() &&
1724 (MD->getParent()->hasAnyDependentBases() ||
1725 MD->getType()->isDependentType()))
1726 return;
1727
1728 if (MD && !MD->isVirtual()) {
1729 // If we have a non-virtual method, check if if hides a virtual method.
1730 // (In that case, it's most likely the method has the wrong type.)
1731 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1732 FindHiddenVirtualMethods(MD, OverloadedMethods);
1733
1734 if (!OverloadedMethods.empty()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001735 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1736 Diag(OA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001737 diag::override_keyword_hides_virtual_member_function)
1738 << "override" << (OverloadedMethods.size() > 1);
1739 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
Richard Smitha4b39652012-08-06 03:25:17 +00001740 Diag(FA->getLocation(),
Eli Friedmandae92712013-09-05 23:51:03 +00001741 diag::override_keyword_hides_virtual_member_function)
1742 << "final" << (OverloadedMethods.size() > 1);
Richard Smitha4b39652012-08-06 03:25:17 +00001743 }
Eli Friedmandae92712013-09-05 23:51:03 +00001744 NoteHiddenVirtualMethods(MD, OverloadedMethods);
1745 MD->setInvalidDecl();
1746 return;
1747 }
1748 // Fall through into the general case diagnostic.
1749 // FIXME: We might want to attempt typo correction here.
1750 }
1751
1752 if (!MD || !MD->isVirtual()) {
1753 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1754 Diag(OA->getLocation(),
1755 diag::override_keyword_only_allowed_on_virtual_member_functions)
1756 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1757 D->dropAttr<OverrideAttr>();
1758 }
1759 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1760 Diag(FA->getLocation(),
1761 diag::override_keyword_only_allowed_on_virtual_member_functions)
1762 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1763 D->dropAttr<FinalAttr>();
Richard Smitha4b39652012-08-06 03:25:17 +00001764 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001765 return;
1766 }
Richard Smitha4b39652012-08-06 03:25:17 +00001767
Richard Smitha4b39652012-08-06 03:25:17 +00001768 // C++11 [class.virtual]p5:
1769 // If a virtual function is marked with the virt-specifier override and
1770 // does not override a member function of a base class, the program is
1771 // ill-formed.
1772 bool HasOverriddenMethods =
1773 MD->begin_overridden_methods() != MD->end_overridden_methods();
1774 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1775 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1776 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001777}
1778
Richard Smitha4b39652012-08-06 03:25:17 +00001779/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001780/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001781/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001782bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1783 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001784 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001785 return false;
1786
1787 Diag(New->getLocation(), diag::err_final_function_overridden)
1788 << New->getDeclName();
1789 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1790 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001791}
1792
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001793static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001794 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1795 // FIXME: Destruction of ObjC lifetime types has side-effects.
1796 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1797 return !RD->isCompleteDefinition() ||
1798 !RD->hasTrivialDefaultConstructor() ||
1799 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001800 return false;
1801}
1802
John McCall76da55d2013-04-16 07:28:30 +00001803static AttributeList *getMSPropertyAttr(AttributeList *list) {
1804 for (AttributeList* it = list; it != 0; it = it->getNext())
1805 if (it->isDeclspecPropertyAttribute())
1806 return it;
1807 return 0;
1808}
1809
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001810/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1811/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001812/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001813/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1814/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001815NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001816Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001817 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001818 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001819 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001820 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001821 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1822 DeclarationName Name = NameInfo.getName();
1823 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001824
1825 // For anonymous bitfields, the location should point to the type.
1826 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001827 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001828
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001829 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001830
John McCall4bde1e12010-06-04 08:34:12 +00001831 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001832 assert(!DS.isFriendSpecified());
1833
Richard Smith1ab0d902011-06-25 02:28:38 +00001834 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001835
John McCalle402e722012-09-25 07:32:39 +00001836 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1837 // The Microsoft extension __interface only permits public member functions
1838 // and prohibits constructors, destructors, operators, non-public member
1839 // functions, static methods and data members.
1840 unsigned InvalidDecl;
1841 bool ShowDeclName = true;
1842 if (!isFunc)
1843 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1844 else if (AS != AS_public)
1845 InvalidDecl = 2;
1846 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1847 InvalidDecl = 3;
1848 else switch (Name.getNameKind()) {
1849 case DeclarationName::CXXConstructorName:
1850 InvalidDecl = 4;
1851 ShowDeclName = false;
1852 break;
1853
1854 case DeclarationName::CXXDestructorName:
1855 InvalidDecl = 5;
1856 ShowDeclName = false;
1857 break;
1858
1859 case DeclarationName::CXXOperatorName:
1860 case DeclarationName::CXXConversionFunctionName:
1861 InvalidDecl = 6;
1862 break;
1863
1864 default:
1865 InvalidDecl = 0;
1866 break;
1867 }
1868
1869 if (InvalidDecl) {
1870 if (ShowDeclName)
1871 Diag(Loc, diag::err_invalid_member_in_interface)
1872 << (InvalidDecl-1) << Name;
1873 else
1874 Diag(Loc, diag::err_invalid_member_in_interface)
1875 << (InvalidDecl-1) << "";
1876 return 0;
1877 }
1878 }
1879
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001880 // C++ 9.2p6: A member shall not be declared to have automatic storage
1881 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001882 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1883 // data members and cannot be applied to names declared const or static,
1884 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001885 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001886 case DeclSpec::SCS_unspecified:
1887 case DeclSpec::SCS_typedef:
1888 case DeclSpec::SCS_static:
1889 break;
1890 case DeclSpec::SCS_mutable:
1891 if (isFunc) {
1892 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Richard Smithec642442013-04-12 22:46:28 +00001894 // FIXME: It would be nicer if the keyword was ignored only for this
1895 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001896 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001897 }
1898 break;
1899 default:
1900 Diag(DS.getStorageClassSpecLoc(),
1901 diag::err_storageclass_invalid_for_member);
1902 D.getMutableDeclSpec().ClearStorageClassSpecs();
1903 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001904 }
1905
Sebastian Redl669d5d72008-11-14 23:42:31 +00001906 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1907 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001908 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001909
David Blaikie1d87fba2013-01-30 01:22:18 +00001910 if (DS.isConstexprSpecified() && isInstField) {
1911 SemaDiagnosticBuilder B =
1912 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1913 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1914 if (InitStyle == ICIS_NoInit) {
1915 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1916 D.getMutableDeclSpec().ClearConstexprSpec();
1917 const char *PrevSpec;
1918 unsigned DiagID;
1919 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1920 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001921 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001922 assert(!Failed && "Making a constexpr member const shouldn't fail");
1923 } else {
1924 B << 1;
1925 const char *PrevSpec;
1926 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001927 if (D.getMutableDeclSpec().SetStorageClassSpec(
1928 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001929 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001930 "This is the only DeclSpec that should fail to be applied");
1931 B << 1;
1932 } else {
1933 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1934 isInstField = false;
1935 }
1936 }
1937 }
1938
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001939 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001940 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001941 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001942
1943 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001944 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001945 Diag(Loc, diag::err_bad_variable_name)
1946 << Name;
1947 return 0;
1948 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001949
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001950 IdentifierInfo *II = Name.getAsIdentifierInfo();
1951
Douglas Gregorf2503652011-09-21 14:40:46 +00001952 // Member field could not be with "template" keyword.
1953 // So TemplateParameterLists should be empty in this case.
1954 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001955 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001956 if (TemplateParams->size()) {
1957 // There is no such thing as a member field template.
1958 Diag(D.getIdentifierLoc(), diag::err_template_member)
1959 << II
1960 << SourceRange(TemplateParams->getTemplateLoc(),
1961 TemplateParams->getRAngleLoc());
1962 } else {
1963 // There is an extraneous 'template<>' for this member.
1964 Diag(TemplateParams->getTemplateLoc(),
1965 diag::err_template_member_noparams)
1966 << II
1967 << SourceRange(TemplateParams->getTemplateLoc(),
1968 TemplateParams->getRAngleLoc());
1969 }
1970 return 0;
1971 }
1972
Douglas Gregor922fff22010-10-13 22:19:53 +00001973 if (SS.isSet() && !SS.isInvalid()) {
1974 // The user provided a superfluous scope specifier inside a class
1975 // definition:
1976 //
1977 // class X {
1978 // int X::member;
1979 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001980 if (DeclContext *DC = computeDeclContext(SS, false))
1981 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001982 else
1983 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1984 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001985
Douglas Gregor922fff22010-10-13 22:19:53 +00001986 SS.clear();
1987 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001988
John McCall76da55d2013-04-16 07:28:30 +00001989 AttributeList *MSPropertyAttr =
1990 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00001991 if (MSPropertyAttr) {
1992 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1993 BitWidth, InitStyle, AS, MSPropertyAttr);
1994 if (!Member)
1995 return 0;
1996 isInstField = false;
1997 } else {
1998 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1999 BitWidth, InitStyle, AS);
2000 assert(Member && "HandleField never returns null");
2001 }
2002 } else {
2003 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2004
2005 Member = HandleDeclarator(S, D, TemplateParameterLists);
2006 if (!Member)
2007 return 0;
2008
2009 // Non-instance-fields can't have a bitfield.
2010 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002011 if (Member->isInvalidDecl()) {
2012 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00002013 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00002014 // C++ 9.6p3: A bit-field shall not be a static member.
2015 // "static member 'A' cannot be a bit-field"
2016 Diag(Loc, diag::err_static_not_bitfield)
2017 << Name << BitWidth->getSourceRange();
2018 } else if (isa<TypedefDecl>(Member)) {
2019 // "typedef member 'x' cannot be a bit-field"
2020 Diag(Loc, diag::err_typedef_not_bitfield)
2021 << Name << BitWidth->getSourceRange();
2022 } else {
2023 // A function typedef ("typedef int f(); f a;").
2024 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2025 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00002026 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00002027 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00002028 }
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Chris Lattner8b963ef2009-03-05 23:01:03 +00002030 BitWidth = 0;
2031 Member->setInvalidDecl();
2032 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002033
2034 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Larisse Voufoef4579c2013-08-06 01:03:05 +00002036 // If we have declared a member function template or static data member
2037 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002038 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2039 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002040 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2041 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002042 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002043
Richard Smitha4b39652012-08-06 03:25:17 +00002044 if (VS.isOverrideSpecified())
2045 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2046 if (VS.isFinalSpecified())
2047 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002048
Douglas Gregorf5251602011-03-08 17:10:18 +00002049 if (VS.getLastLocation().isValid()) {
2050 // Update the end location of a method that has a virt-specifiers.
2051 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2052 MD->setRangeEnd(VS.getLastLocation());
2053 }
Richard Smitha4b39652012-08-06 03:25:17 +00002054
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002055 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002056
Douglas Gregor10bd3682008-11-17 22:58:34 +00002057 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002058
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002059 if (isInstField) {
2060 FieldDecl *FD = cast<FieldDecl>(Member);
2061 FieldCollector->Add(FD);
2062
2063 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2064 FD->getLocation())
2065 != DiagnosticsEngine::Ignored) {
2066 // Remember all explicit private FieldDecls that have a name, no side
2067 // effects and are not part of a dependent type declaration.
2068 if (!FD->isImplicit() && FD->getDeclName() &&
2069 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002070 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002071 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002072 !InitializationHasSideEffects(*FD))
2073 UnusedPrivateFields.insert(FD);
2074 }
2075 }
2076
John McCalld226f652010-08-21 09:40:31 +00002077 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002078}
2079
Hans Wennborg471f9852012-09-18 15:58:06 +00002080namespace {
2081 class UninitializedFieldVisitor
2082 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2083 Sema &S;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002084 // If VD is null, this visitor will only update the Decls set.
Hans Wennborg471f9852012-09-18 15:58:06 +00002085 ValueDecl *VD;
Richard Trieufbb08b52013-09-13 03:20:53 +00002086 bool isReferenceType;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002087 // List of Decls to generate a warning on.
2088 llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
2089 bool WarnOnSelfReference;
2090 // If non-null, add a note to the warning pointing back to the constructor.
2091 const CXXConstructorDecl *Constructor;
Hans Wennborg471f9852012-09-18 15:58:06 +00002092 public:
2093 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002094 UninitializedFieldVisitor(Sema &S, ValueDecl *VD,
2095 llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2096 bool WarnOnSelfReference,
2097 const CXXConstructorDecl *Constructor)
2098 : Inherited(S.Context), S(S), VD(VD), isReferenceType(false), Decls(Decls),
2099 WarnOnSelfReference(WarnOnSelfReference), Constructor(Constructor) {
2100 // When VD is null, this visitor is used to detect initialization of other
2101 // fields.
2102 if (VD) {
2103 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2104 this->VD = IFD->getAnonField();
2105 else
2106 this->VD = VD;
2107 isReferenceType = this->VD->getType()->isReferenceType();
2108 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002109 }
2110
Richard Trieu3ddec882013-09-16 20:46:50 +00002111 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002112 if (!VD)
2113 return;
2114
Richard Trieu3ddec882013-09-16 20:46:50 +00002115 if (CheckReferenceOnly && !isReferenceType)
2116 return;
2117
Richard Trieufbb08b52013-09-13 03:20:53 +00002118 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2119 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002120
Richard Trieufbb08b52013-09-13 03:20:53 +00002121 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2122 // or union.
2123 MemberExpr *FieldME = ME;
2124
2125 Expr *Base = ME;
2126 while (isa<MemberExpr>(Base)) {
2127 ME = cast<MemberExpr>(Base);
2128
2129 if (isa<VarDecl>(ME->getMemberDecl()))
2130 return;
2131
2132 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2133 if (!FD->isAnonymousStructOrUnion())
2134 FieldME = ME;
2135
2136 Base = ME->getBase();
2137 }
2138
Richard Trieu3ddec882013-09-16 20:46:50 +00002139 if (!isa<CXXThisExpr>(Base))
2140 return;
2141
Richard Trieuef8f90c2013-09-20 03:03:06 +00002142 ValueDecl* FoundVD = FieldME->getMemberDecl();
2143
2144 if (VD == FoundVD) {
2145 if (!WarnOnSelfReference)
2146 return;
2147
Richard Trieu3ddec882013-09-16 20:46:50 +00002148 unsigned diag = isReferenceType
Richard Trieufbb08b52013-09-13 03:20:53 +00002149 ? diag::warn_reference_field_is_uninit
2150 : diag::warn_field_is_uninit;
2151 S.Diag(FieldME->getExprLoc(), diag) << VD;
Richard Trieuef8f90c2013-09-20 03:03:06 +00002152 if (Constructor)
2153 S.Diag(Constructor->getLocation(),
2154 diag::note_uninit_in_this_constructor);
2155 return;
2156 }
2157
2158 if (CheckReferenceOnly)
2159 return;
2160
2161 if (Decls.count(FoundVD)) {
2162 S.Diag(FieldME->getExprLoc(), diag::warn_field_is_uninit) << FoundVD;
2163 if (Constructor)
2164 S.Diag(Constructor->getLocation(),
2165 diag::note_uninit_in_this_constructor);
2166
Richard Trieufbb08b52013-09-13 03:20:53 +00002167 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002168 }
2169
2170 void HandleValue(Expr *E) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002171 if (!VD)
2172 return;
2173
Hans Wennborg471f9852012-09-18 15:58:06 +00002174 E = E->IgnoreParens();
2175
2176 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002177 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002178 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002179 }
2180
2181 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2182 HandleValue(CO->getTrueExpr());
2183 HandleValue(CO->getFalseExpr());
2184 return;
2185 }
2186
2187 if (BinaryConditionalOperator *BCO =
2188 dyn_cast<BinaryConditionalOperator>(E)) {
2189 HandleValue(BCO->getCommon());
2190 HandleValue(BCO->getFalseExpr());
2191 return;
2192 }
2193
2194 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2195 switch (BO->getOpcode()) {
2196 default:
2197 return;
2198 case(BO_PtrMemD):
2199 case(BO_PtrMemI):
2200 HandleValue(BO->getLHS());
2201 return;
2202 case(BO_Comma):
2203 HandleValue(BO->getRHS());
2204 return;
2205 }
2206 }
2207 }
2208
Richard Trieufbb08b52013-09-13 03:20:53 +00002209 void VisitMemberExpr(MemberExpr *ME) {
Richard Trieu3ddec882013-09-16 20:46:50 +00002210 HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002211
2212 Inherited::VisitMemberExpr(ME);
2213 }
2214
Hans Wennborg471f9852012-09-18 15:58:06 +00002215 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2216 if (E->getCastKind() == CK_LValueToRValue)
2217 HandleValue(E->getSubExpr());
2218
2219 Inherited::VisitImplicitCastExpr(E);
2220 }
2221
Richard Trieufbb08b52013-09-13 03:20:53 +00002222 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Richard Trieuef8f90c2013-09-20 03:03:06 +00002223 if (E->getConstructor()->isCopyConstructor())
Richard Trieufbb08b52013-09-13 03:20:53 +00002224 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2225 if (ICE->getCastKind() == CK_NoOp)
2226 if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
Richard Trieu3ddec882013-09-16 20:46:50 +00002227 HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
Richard Trieufbb08b52013-09-13 03:20:53 +00002228
2229 Inherited::VisitCXXConstructExpr(E);
2230 }
2231
Hans Wennborg471f9852012-09-18 15:58:06 +00002232 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2233 Expr *Callee = E->getCallee();
2234 if (isa<MemberExpr>(Callee))
2235 HandleValue(Callee);
2236
2237 Inherited::VisitCXXMemberCallExpr(E);
2238 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00002239
2240 void VisitBinaryOperator(BinaryOperator *E) {
2241 // If a field assignment is detected, remove the field from the
2242 // uninitiailized field set.
2243 if (E->getOpcode() == BO_Assign)
2244 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2245 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2246 Decls.erase(FD);
2247
2248 Inherited::VisitBinaryOperator(E);
2249 }
Hans Wennborg471f9852012-09-18 15:58:06 +00002250 };
Richard Trieuef8f90c2013-09-20 03:03:06 +00002251 static void CheckInitExprContainsUninitializedFields(
2252 Sema &S, Expr *E, ValueDecl *VD, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2253 bool WarnOnSelfReference, const CXXConstructorDecl *Constructor = 0) {
2254 if (Decls.size() == 0 && !WarnOnSelfReference)
2255 return;
2256
Richard Trieufbb08b52013-09-13 03:20:53 +00002257 if (E)
Richard Trieuef8f90c2013-09-20 03:03:06 +00002258 UninitializedFieldVisitor(S, VD, Decls, WarnOnSelfReference, Constructor)
2259 .Visit(E);
Hans Wennborg471f9852012-09-18 15:58:06 +00002260 }
2261} // namespace
2262
Richard Smith7a614d82011-06-11 17:19:42 +00002263/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002264/// in-class initializer for a non-static C++ class member, and after
2265/// instantiating an in-class initializer in a class template. Such actions
2266/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002267void
Richard Smithca523302012-06-10 03:12:00 +00002268Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002269 Expr *InitExpr) {
2270 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002271 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2272 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002273
2274 if (!InitExpr) {
2275 FD->setInvalidDecl();
2276 FD->removeInClassInitializer();
2277 return;
2278 }
2279
Peter Collingbournefef21892011-10-23 18:59:44 +00002280 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2281 FD->setInvalidDecl();
2282 FD->removeInClassInitializer();
2283 return;
2284 }
2285
Richard Smith7a614d82011-06-11 17:19:42 +00002286 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002287 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002288 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002289 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002290 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002291 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002292 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2293 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002294 if (Init.isInvalid()) {
2295 FD->setInvalidDecl();
2296 return;
2297 }
Richard Smith7a614d82011-06-11 17:19:42 +00002298 }
2299
Richard Smith41956372013-01-14 22:39:08 +00002300 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002301 // The initialization of each base and member constitutes a
2302 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002303 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002304 if (Init.isInvalid()) {
2305 FD->setInvalidDecl();
2306 return;
2307 }
2308
2309 InitExpr = Init.release();
2310
2311 FD->setInClassInitializer(InitExpr);
2312}
2313
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002314/// \brief Find the direct and/or virtual base specifiers that
2315/// correspond to the given base type, for use in base initialization
2316/// within a constructor.
2317static bool FindBaseInitializer(Sema &SemaRef,
2318 CXXRecordDecl *ClassDecl,
2319 QualType BaseType,
2320 const CXXBaseSpecifier *&DirectBaseSpec,
2321 const CXXBaseSpecifier *&VirtualBaseSpec) {
2322 // First, check for a direct base class.
2323 DirectBaseSpec = 0;
2324 for (CXXRecordDecl::base_class_const_iterator Base
2325 = ClassDecl->bases_begin();
2326 Base != ClassDecl->bases_end(); ++Base) {
2327 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2328 // We found a direct base of this type. That's what we're
2329 // initializing.
2330 DirectBaseSpec = &*Base;
2331 break;
2332 }
2333 }
2334
2335 // Check for a virtual base class.
2336 // FIXME: We might be able to short-circuit this if we know in advance that
2337 // there are no virtual bases.
2338 VirtualBaseSpec = 0;
2339 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2340 // We haven't found a base yet; search the class hierarchy for a
2341 // virtual base class.
2342 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2343 /*DetectVirtual=*/false);
2344 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2345 BaseType, Paths)) {
2346 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2347 Path != Paths.end(); ++Path) {
2348 if (Path->back().Base->isVirtual()) {
2349 VirtualBaseSpec = Path->back().Base;
2350 break;
2351 }
2352 }
2353 }
2354 }
2355
2356 return DirectBaseSpec || VirtualBaseSpec;
2357}
2358
Sebastian Redl6df65482011-09-24 17:48:25 +00002359/// \brief Handle a C++ member initializer using braced-init-list syntax.
2360MemInitResult
2361Sema::ActOnMemInitializer(Decl *ConstructorD,
2362 Scope *S,
2363 CXXScopeSpec &SS,
2364 IdentifierInfo *MemberOrBase,
2365 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002366 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002367 SourceLocation IdLoc,
2368 Expr *InitList,
2369 SourceLocation EllipsisLoc) {
2370 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002371 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002372 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002373}
2374
2375/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002376MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002377Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002378 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002379 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002380 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002381 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002382 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002383 SourceLocation IdLoc,
2384 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002385 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002386 SourceLocation RParenLoc,
2387 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002388 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002389 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002390 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002391 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002392}
2393
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002394namespace {
2395
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002396// Callback to only accept typo corrections that can be a valid C++ member
2397// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002398class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002399public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002400 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2401 : ClassDecl(ClassDecl) {}
2402
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002403 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002404 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2405 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2406 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002407 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002408 }
2409 return false;
2410 }
2411
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002412private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002413 CXXRecordDecl *ClassDecl;
2414};
2415
2416}
2417
Sebastian Redl6df65482011-09-24 17:48:25 +00002418/// \brief Handle a C++ member initializer.
2419MemInitResult
2420Sema::BuildMemInitializer(Decl *ConstructorD,
2421 Scope *S,
2422 CXXScopeSpec &SS,
2423 IdentifierInfo *MemberOrBase,
2424 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002425 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002426 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002427 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002428 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002429 if (!ConstructorD)
2430 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002431
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002432 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002433
2434 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002435 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002436 if (!Constructor) {
2437 // The user wrote a constructor initializer on a function that is
2438 // not a C++ constructor. Ignore the error for now, because we may
2439 // have more member initializers coming; we'll diagnose it just
2440 // once in ActOnMemInitializers.
2441 return true;
2442 }
2443
2444 CXXRecordDecl *ClassDecl = Constructor->getParent();
2445
2446 // C++ [class.base.init]p2:
2447 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002448 // constructor's class and, if not found in that scope, are looked
2449 // up in the scope containing the constructor's definition.
2450 // [Note: if the constructor's class contains a member with the
2451 // same name as a direct or virtual base class of the class, a
2452 // mem-initializer-id naming the member or base class and composed
2453 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002454 // mem-initializer-id for the hidden base class may be specified
2455 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002456 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002457 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002458 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002459 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002460 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002461 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002462 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2463 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002464 if (EllipsisLoc.isValid())
2465 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002466 << MemberOrBase
2467 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002468
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002469 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002470 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002471 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002472 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002473 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002474 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002475 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002476
2477 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002478 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002479 } else if (DS.getTypeSpecType() == TST_decltype) {
2480 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002481 } else {
2482 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2483 LookupParsedName(R, S, &SS);
2484
2485 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2486 if (!TyD) {
2487 if (R.isAmbiguous()) return true;
2488
John McCallfd225442010-04-09 19:01:14 +00002489 // We don't want access-control diagnostics here.
2490 R.suppressDiagnostics();
2491
Douglas Gregor7a886e12010-01-19 06:46:48 +00002492 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2493 bool NotUnknownSpecialization = false;
2494 DeclContext *DC = computeDeclContext(SS, false);
2495 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2496 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2497
2498 if (!NotUnknownSpecialization) {
2499 // When the scope specifier can refer to a member of an unknown
2500 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002501 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2502 SS.getWithLocInContext(Context),
2503 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002504 if (BaseType.isNull())
2505 return true;
2506
Douglas Gregor7a886e12010-01-19 06:46:48 +00002507 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002508 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002509 }
2510 }
2511
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002512 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002513 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002514 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002515 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002516 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002517 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002518 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002519 // We have found a non-static data member with a similar
2520 // name to what was typed; complain and initialize that
2521 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002522 diagnoseTypo(Corr,
2523 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2524 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002525 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002526 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002527 const CXXBaseSpecifier *DirectBaseSpec;
2528 const CXXBaseSpecifier *VirtualBaseSpec;
2529 if (FindBaseInitializer(*this, ClassDecl,
2530 Context.getTypeDeclType(Type),
2531 DirectBaseSpec, VirtualBaseSpec)) {
2532 // We have found a direct or virtual base class with a
2533 // similar name to what was typed; complain and initialize
2534 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002535 diagnoseTypo(Corr,
2536 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2537 << MemberOrBase << false,
2538 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002539
Richard Smith2d670972013-08-17 00:46:16 +00002540 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2541 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002542 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002543 diag::note_base_class_specified_here)
2544 << BaseSpec->getType()
2545 << BaseSpec->getSourceRange();
2546
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002547 TyD = Type;
2548 }
2549 }
2550 }
2551
Douglas Gregor7a886e12010-01-19 06:46:48 +00002552 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002553 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002554 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002555 return true;
2556 }
John McCall2b194412009-12-21 10:41:20 +00002557 }
2558
Douglas Gregor7a886e12010-01-19 06:46:48 +00002559 if (BaseType.isNull()) {
2560 BaseType = Context.getTypeDeclType(TyD);
2561 if (SS.isSet()) {
2562 NestedNameSpecifier *Qualifier =
2563 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002564
Douglas Gregor7a886e12010-01-19 06:46:48 +00002565 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002566 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002567 }
John McCall2b194412009-12-21 10:41:20 +00002568 }
2569 }
Mike Stump1eb44332009-09-09 15:08:12 +00002570
John McCalla93c9342009-12-07 02:54:59 +00002571 if (!TInfo)
2572 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002573
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002574 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002575}
2576
Chandler Carruth81c64772011-09-03 01:14:15 +00002577/// Checks a member initializer expression for cases where reference (or
2578/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002579static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2580 Expr *Init,
2581 SourceLocation IdLoc) {
2582 QualType MemberTy = Member->getType();
2583
2584 // We only handle pointers and references currently.
2585 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2586 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2587 return;
2588
2589 const bool IsPointer = MemberTy->isPointerType();
2590 if (IsPointer) {
2591 if (const UnaryOperator *Op
2592 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2593 // The only case we're worried about with pointers requires taking the
2594 // address.
2595 if (Op->getOpcode() != UO_AddrOf)
2596 return;
2597
2598 Init = Op->getSubExpr();
2599 } else {
2600 // We only handle address-of expression initializers for pointers.
2601 return;
2602 }
2603 }
2604
Richard Smitha4bb99c2013-06-12 21:51:50 +00002605 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002606 // We only warn when referring to a non-reference parameter declaration.
2607 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2608 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002609 return;
2610
2611 S.Diag(Init->getExprLoc(),
2612 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2613 : diag::warn_bind_ref_member_to_parameter)
2614 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002615 } else {
2616 // Other initializers are fine.
2617 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002618 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002619
2620 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2621 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002622}
2623
John McCallf312b1e2010-08-26 23:41:50 +00002624MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002625Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002626 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002627 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2628 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2629 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002630 "Member must be a FieldDecl or IndirectFieldDecl");
2631
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002632 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002633 return true;
2634
Douglas Gregor464b2f02010-11-05 22:21:31 +00002635 if (Member->isInvalidDecl())
2636 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002637
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002638 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002639 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002640 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002641 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002642 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002643 } else {
2644 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002645 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002646 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002647
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002648 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002649
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002650 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002651 // Can't check initialization for a member of dependent type or when
2652 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002653 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002654 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002655 bool InitList = false;
2656 if (isa<InitListExpr>(Init)) {
2657 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002658 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002659 }
2660
Chandler Carruth894aed92010-12-06 09:23:57 +00002661 // Initialize the member.
2662 InitializedEntity MemberEntity =
2663 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2664 : InitializedEntity::InitializeMember(IndirectMember, 0);
2665 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002666 InitList ? InitializationKind::CreateDirectList(IdLoc)
2667 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2668 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002669
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002670 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2671 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002672 if (MemberInit.isInvalid())
2673 return true;
2674
Richard Smith8a07cd32013-06-12 20:42:33 +00002675 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2676
Richard Smith41956372013-01-14 22:39:08 +00002677 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002678 // The initialization of each base and member constitutes a
2679 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002680 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002681 if (MemberInit.isInvalid())
2682 return true;
2683
Richard Smithc83c2302012-12-19 01:39:02 +00002684 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002685 }
2686
Chandler Carruth894aed92010-12-06 09:23:57 +00002687 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002688 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2689 InitRange.getBegin(), Init,
2690 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002691 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002692 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2693 InitRange.getBegin(), Init,
2694 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002695 }
Eli Friedman59c04372009-07-29 19:44:27 +00002696}
2697
John McCallf312b1e2010-08-26 23:41:50 +00002698MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002699Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002700 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002701 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002702 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002703 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002704 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002705 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002706
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002707 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002708 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002709 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2710 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002711 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002712 }
2713
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002714 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002715 // Initialize the object.
2716 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2717 QualType(ClassDecl->getTypeForDecl(), 0));
2718 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002719 InitList ? InitializationKind::CreateDirectList(NameLoc)
2720 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2721 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002722 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002723 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002724 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002725 if (DelegationInit.isInvalid())
2726 return true;
2727
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002728 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2729 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002730
Richard Smith41956372013-01-14 22:39:08 +00002731 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002732 // The initialization of each base and member constitutes a
2733 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002734 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2735 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002736 if (DelegationInit.isInvalid())
2737 return true;
2738
Eli Friedmand21016f2012-05-19 23:35:23 +00002739 // If we are in a dependent context, template instantiation will
2740 // perform this type-checking again. Just save the arguments that we
2741 // received in a ParenListExpr.
2742 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2743 // of the information that we have about the base
2744 // initializer. However, deconstructing the ASTs is a dicey process,
2745 // and this approach is far more likely to get the corner cases right.
2746 if (CurContext->isDependentContext())
2747 DelegationInit = Owned(Init);
2748
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002749 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002750 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002751 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002752}
2753
2754MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002755Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002756 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002757 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002758 SourceLocation BaseLoc
2759 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002760
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002761 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2762 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2763 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2764
2765 // C++ [class.base.init]p2:
2766 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002767 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002768 // of that class, the mem-initializer is ill-formed. A
2769 // mem-initializer-list can initialize a base class using any
2770 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002771 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002772
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002773 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002774 if (EllipsisLoc.isValid()) {
2775 // This is a pack expansion.
2776 if (!BaseType->containsUnexpandedParameterPack()) {
2777 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002778 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002779
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002780 EllipsisLoc = SourceLocation();
2781 }
2782 } else {
2783 // Check for any unexpanded parameter packs.
2784 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2785 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002786
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002787 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002788 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002789 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002790
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002791 // Check for direct and virtual base classes.
2792 const CXXBaseSpecifier *DirectBaseSpec = 0;
2793 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2794 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002795 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2796 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002797 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002798
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002799 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2800 VirtualBaseSpec);
2801
2802 // C++ [base.class.init]p2:
2803 // Unless the mem-initializer-id names a nonstatic data member of the
2804 // constructor's class or a direct or virtual base of that class, the
2805 // mem-initializer is ill-formed.
2806 if (!DirectBaseSpec && !VirtualBaseSpec) {
2807 // If the class has any dependent bases, then it's possible that
2808 // one of those types will resolve to the same type as
2809 // BaseType. Therefore, just treat this as a dependent base
2810 // class initialization. FIXME: Should we try to check the
2811 // initialization anyway? It seems odd.
2812 if (ClassDecl->hasAnyDependentBases())
2813 Dependent = true;
2814 else
2815 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2816 << BaseType << Context.getTypeDeclType(ClassDecl)
2817 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2818 }
2819 }
2820
2821 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002822 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Sebastian Redl6df65482011-09-24 17:48:25 +00002824 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2825 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002826 InitRange.getBegin(), Init,
2827 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002828 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002829
2830 // C++ [base.class.init]p2:
2831 // If a mem-initializer-id is ambiguous because it designates both
2832 // a direct non-virtual base class and an inherited virtual base
2833 // class, the mem-initializer is ill-formed.
2834 if (DirectBaseSpec && VirtualBaseSpec)
2835 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002836 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002837
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002838 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002839 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002840 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002841
2842 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002843 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002844 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002845 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002846 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002847 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002848 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002849
2850 InitializedEntity BaseEntity =
2851 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2852 InitializationKind Kind =
2853 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2854 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2855 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002856 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2857 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002858 if (BaseInit.isInvalid())
2859 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002860
Richard Smith41956372013-01-14 22:39:08 +00002861 // C++11 [class.base.init]p7:
2862 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002863 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002864 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002865 if (BaseInit.isInvalid())
2866 return true;
2867
2868 // If we are in a dependent context, template instantiation will
2869 // perform this type-checking again. Just save the arguments that we
2870 // received in a ParenListExpr.
2871 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2872 // of the information that we have about the base
2873 // initializer. However, deconstructing the ASTs is a dicey process,
2874 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002875 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002876 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002877
Sean Huntcbb67482011-01-08 20:30:50 +00002878 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002879 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002880 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002881 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002882 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002883}
2884
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002885// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002886static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2887 if (T.isNull()) T = E->getType();
2888 QualType TargetType = SemaRef.BuildReferenceType(
2889 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002890 SourceLocation ExprLoc = E->getLocStart();
2891 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2892 TargetType, ExprLoc);
2893
2894 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2895 SourceRange(ExprLoc, ExprLoc),
2896 E->getSourceRange()).take();
2897}
2898
Anders Carlssone5ef7402010-04-23 03:10:23 +00002899/// ImplicitInitializerKind - How an implicit base or member initializer should
2900/// initialize its base or member.
2901enum ImplicitInitializerKind {
2902 IIK_Default,
2903 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002904 IIK_Move,
2905 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002906};
2907
Anders Carlssondefefd22010-04-23 02:00:02 +00002908static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002909BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002910 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002911 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002912 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002913 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002914 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002915 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2916 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002917
John McCall60d7b3a2010-08-24 06:29:42 +00002918 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002919
2920 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002921 case IIK_Inherit: {
2922 const CXXRecordDecl *Inherited =
2923 Constructor->getInheritedConstructor()->getParent();
2924 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2925 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2926 // C++11 [class.inhctor]p8:
2927 // Each expression in the expression-list is of the form
2928 // static_cast<T&&>(p), where p is the name of the corresponding
2929 // constructor parameter and T is the declared type of p.
2930 SmallVector<Expr*, 16> Args;
2931 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2932 ParmVarDecl *PD = Constructor->getParamDecl(I);
2933 ExprResult ArgExpr =
2934 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2935 VK_LValue, SourceLocation());
2936 if (ArgExpr.isInvalid())
2937 return true;
2938 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2939 }
2940
2941 InitializationKind InitKind = InitializationKind::CreateDirect(
2942 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002943 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002944 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2945 break;
2946 }
2947 }
2948 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002949 case IIK_Default: {
2950 InitializationKind InitKind
2951 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002952 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2953 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002954 break;
2955 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002956
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002957 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002958 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002959 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002960 ParmVarDecl *Param = Constructor->getParamDecl(0);
2961 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002962
Anders Carlssone5ef7402010-04-23 03:10:23 +00002963 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002964 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002965 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002966 Constructor->getLocation(), ParamType,
2967 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002968
Eli Friedman5f2987c2012-02-02 03:46:19 +00002969 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2970
Anders Carlssonc7957502010-04-24 22:02:54 +00002971 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002972 QualType ArgTy =
2973 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2974 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002975
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002976 if (Moving) {
2977 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2978 }
2979
John McCallf871d0c2010-08-07 06:22:56 +00002980 CXXCastPath BasePath;
2981 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002982 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2983 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002984 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002985 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002986
Anders Carlssone5ef7402010-04-23 03:10:23 +00002987 InitializationKind InitKind
2988 = InitializationKind::CreateDirect(Constructor->getLocation(),
2989 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002990 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2991 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002992 break;
2993 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002994 }
John McCall9ae2f072010-08-23 23:25:46 +00002995
Douglas Gregor53c374f2010-12-07 00:41:46 +00002996 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002997 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002998 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002999
Anders Carlssondefefd22010-04-23 02:00:02 +00003000 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00003001 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00003002 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3003 SourceLocation()),
3004 BaseSpec->isVirtual(),
3005 SourceLocation(),
3006 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003007 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00003008 SourceLocation());
3009
Anders Carlssondefefd22010-04-23 02:00:02 +00003010 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00003011}
3012
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003013static bool RefersToRValueRef(Expr *MemRef) {
3014 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3015 return Referenced->getType()->isRValueReferenceType();
3016}
3017
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003018static bool
3019BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003020 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003021 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00003022 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003023 if (Field->isInvalidDecl())
3024 return true;
3025
Chandler Carruthf186b542010-06-29 23:50:44 +00003026 SourceLocation Loc = Constructor->getLocation();
3027
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003028 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3029 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003030 ParmVarDecl *Param = Constructor->getParamDecl(0);
3031 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00003032
3033 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003034 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3035 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00003036
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003037 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003038 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00003039 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00003040 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003041
Eli Friedman5f2987c2012-02-02 03:46:19 +00003042 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3043
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003044 if (Moving) {
3045 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3046 }
3047
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003048 // Build a reference to this field within the parameter.
3049 CXXScopeSpec SS;
3050 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3051 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003052 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3053 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003054 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00003055 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00003056 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003057 ParamType, Loc,
3058 /*IsArrow=*/false,
3059 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00003060 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003061 /*FirstQualifierInScope=*/0,
3062 MemberLookup,
3063 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003064 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003065 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003066
3067 // C++11 [class.copy]p15:
3068 // - if a member m has rvalue reference type T&&, it is direct-initialized
3069 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00003070 if (RefersToRValueRef(CtorArg.get())) {
3071 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003072 }
3073
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003074 // When the field we are copying is an array, create index variables for
3075 // each dimension of the array. We use these index variables to subscript
3076 // the source array, and other clients (e.g., CodeGen) will perform the
3077 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003078 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003079 QualType BaseType = Field->getType();
3080 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003081 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003082 while (const ConstantArrayType *Array
3083 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003084 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003085 // Create the iteration variable for this array index.
3086 IdentifierInfo *IterationVarName = 0;
3087 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003088 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003089 llvm::raw_svector_ostream OS(Str);
3090 OS << "__i" << IndexVariables.size();
3091 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3092 }
3093 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003094 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003095 IterationVarName, SizeType,
3096 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003097 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003098 IndexVariables.push_back(IterationVar);
3099
3100 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003101 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003102 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003103 assert(!IterationVarRef.isInvalid() &&
3104 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003105 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3106 assert(!IterationVarRef.isInvalid() &&
3107 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003108
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003109 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003110 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003111 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003112 Loc);
3113 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003114 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003115
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003116 BaseType = Array->getElementType();
3117 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003118
3119 // The array subscript expression is an lvalue, which is wrong for moving.
3120 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003121 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003122
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003123 // Construct the entity that we will be initializing. For an array, this
3124 // will be first element in the array, which may require several levels
3125 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003126 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003127 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003128 if (Indirect)
3129 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3130 else
3131 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003132 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3133 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3134 0,
3135 Entities.back()));
3136
3137 // Direct-initialize to use the copy constructor.
3138 InitializationKind InitKind =
3139 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3140
Sebastian Redl74e611a2011-09-04 18:14:28 +00003141 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003142 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003143
John McCall60d7b3a2010-08-24 06:29:42 +00003144 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003145 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003146 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003147 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003148 if (MemberInit.isInvalid())
3149 return true;
3150
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003151 if (Indirect) {
3152 assert(IndexVariables.size() == 0 &&
3153 "Indirect field improperly initialized");
3154 CXXMemberInit
3155 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3156 Loc, Loc,
3157 MemberInit.takeAs<Expr>(),
3158 Loc);
3159 } else
3160 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3161 Loc, MemberInit.takeAs<Expr>(),
3162 Loc,
3163 IndexVariables.data(),
3164 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003165 return false;
3166 }
3167
Richard Smith07b0fdc2013-03-18 21:12:30 +00003168 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3169 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003170
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003171 QualType FieldBaseElementType =
3172 SemaRef.Context.getBaseElementType(Field->getType());
3173
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003174 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003175 InitializedEntity InitEntity
3176 = Indirect? InitializedEntity::InitializeMember(Indirect)
3177 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003178 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003179 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003180
3181 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3182 ExprResult MemberInit =
3183 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003184
Douglas Gregor53c374f2010-12-07 00:41:46 +00003185 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003186 if (MemberInit.isInvalid())
3187 return true;
3188
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003189 if (Indirect)
3190 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3191 Indirect, Loc,
3192 Loc,
3193 MemberInit.get(),
3194 Loc);
3195 else
3196 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3197 Field, Loc, Loc,
3198 MemberInit.get(),
3199 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003200 return false;
3201 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003202
Sean Hunt1f2f3842011-05-17 00:19:05 +00003203 if (!Field->getParent()->isUnion()) {
3204 if (FieldBaseElementType->isReferenceType()) {
3205 SemaRef.Diag(Constructor->getLocation(),
3206 diag::err_uninitialized_member_in_ctor)
3207 << (int)Constructor->isImplicit()
3208 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3209 << 0 << Field->getDeclName();
3210 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3211 return true;
3212 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003213
Sean Hunt1f2f3842011-05-17 00:19:05 +00003214 if (FieldBaseElementType.isConstQualified()) {
3215 SemaRef.Diag(Constructor->getLocation(),
3216 diag::err_uninitialized_member_in_ctor)
3217 << (int)Constructor->isImplicit()
3218 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3219 << 1 << Field->getDeclName();
3220 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3221 return true;
3222 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003223 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003224
David Blaikie4e4d0842012-03-11 07:00:24 +00003225 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003226 FieldBaseElementType->isObjCRetainableType() &&
3227 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3228 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003229 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003230 // Default-initialize Objective-C pointers to NULL.
3231 CXXMemberInit
3232 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3233 Loc, Loc,
3234 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3235 Loc);
3236 return false;
3237 }
3238
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003239 // Nothing to initialize.
3240 CXXMemberInit = 0;
3241 return false;
3242}
John McCallf1860e52010-05-20 23:23:51 +00003243
3244namespace {
3245struct BaseAndFieldInfo {
3246 Sema &S;
3247 CXXConstructorDecl *Ctor;
3248 bool AnyErrorsInInits;
3249 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003250 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003251 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003252
3253 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3254 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003255 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3256 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003257 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003258 else if (Generated && Ctor->isMoveConstructor())
3259 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003260 else if (Ctor->getInheritedConstructor())
3261 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003262 else
3263 IIK = IIK_Default;
3264 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003265
3266 bool isImplicitCopyOrMove() const {
3267 switch (IIK) {
3268 case IIK_Copy:
3269 case IIK_Move:
3270 return true;
3271
3272 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003273 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003274 return false;
3275 }
David Blaikie30263482012-01-20 21:50:17 +00003276
3277 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003278 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003279
3280 bool addFieldInitializer(CXXCtorInitializer *Init) {
3281 AllToInit.push_back(Init);
3282
3283 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003284 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003285 S.UnusedPrivateFields.remove(Init->getAnyMember());
3286
3287 return false;
3288 }
John McCallf1860e52010-05-20 23:23:51 +00003289};
3290}
3291
Richard Smitha4950662011-09-19 13:34:43 +00003292/// \brief Determine whether the given indirect field declaration is somewhere
3293/// within an anonymous union.
3294static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3295 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3296 CEnd = F->chain_end();
3297 C != CEnd; ++C)
3298 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3299 if (Record->isUnion())
3300 return true;
3301
3302 return false;
3303}
3304
Douglas Gregorddb21472011-11-02 23:04:16 +00003305/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3306/// array type.
3307static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3308 if (T->isIncompleteArrayType())
3309 return true;
3310
3311 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3312 if (!ArrayT->getSize())
3313 return true;
3314
3315 T = ArrayT->getElementType();
3316 }
3317
3318 return false;
3319}
3320
Richard Smith7a614d82011-06-11 17:19:42 +00003321static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003322 FieldDecl *Field,
3323 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003324 if (Field->isInvalidDecl())
3325 return false;
John McCallf1860e52010-05-20 23:23:51 +00003326
Chandler Carruthe861c602010-06-30 02:59:29 +00003327 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003328 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3329 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003330
Richard Smith0b8220a2012-08-07 21:30:42 +00003331 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003332 // has a brace-or-equal-initializer, the entity is initialized as specified
3333 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003334 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003335 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3336 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003337 CXXCtorInitializer *Init;
3338 if (Indirect)
3339 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3340 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003341 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003342 SourceLocation());
3343 else
3344 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3345 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003346 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003347 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003348 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003349 }
3350
Richard Smithc115f632011-09-18 11:14:50 +00003351 // Don't build an implicit initializer for union members if none was
3352 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003353 if (Field->getParent()->isUnion() ||
3354 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003355 return false;
3356
Douglas Gregorddb21472011-11-02 23:04:16 +00003357 // Don't initialize incomplete or zero-length arrays.
3358 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3359 return false;
3360
John McCallf1860e52010-05-20 23:23:51 +00003361 // Don't try to build an implicit initializer if there were semantic
3362 // errors in any of the initializers (and therefore we might be
3363 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003364 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003365 return false;
3366
Sean Huntcbb67482011-01-08 20:30:50 +00003367 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003368 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3369 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003370 return true;
John McCallf1860e52010-05-20 23:23:51 +00003371
Richard Smith0b8220a2012-08-07 21:30:42 +00003372 if (!Init)
3373 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003374
Richard Smith0b8220a2012-08-07 21:30:42 +00003375 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003376}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003377
3378bool
3379Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3380 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003381 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003382 Constructor->setNumCtorInitializers(1);
3383 CXXCtorInitializer **initializer =
3384 new (Context) CXXCtorInitializer*[1];
3385 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3386 Constructor->setCtorInitializers(initializer);
3387
Sean Huntb76af9c2011-05-03 23:05:34 +00003388 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003389 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003390 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3391 }
3392
Sean Huntc1598702011-05-05 00:05:47 +00003393 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003394
Sean Hunt059ce0d2011-05-01 07:04:31 +00003395 return false;
3396}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003397
David Blaikie93c86172013-01-17 05:26:25 +00003398bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3399 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003400 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003401 // Just store the initializers as written, they will be checked during
3402 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003403 if (!Initializers.empty()) {
3404 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003405 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003406 new (Context) CXXCtorInitializer*[Initializers.size()];
3407 memcpy(baseOrMemberInitializers, Initializers.data(),
3408 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003409 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003410 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003411
3412 // Let template instantiation know whether we had errors.
3413 if (AnyErrors)
3414 Constructor->setInvalidDecl();
3415
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003416 return false;
3417 }
3418
John McCallf1860e52010-05-20 23:23:51 +00003419 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003420
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003421 // We need to build the initializer AST according to order of construction
3422 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003423 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003424 if (!ClassDecl)
3425 return true;
3426
Eli Friedman80c30da2009-11-09 19:20:36 +00003427 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003428
David Blaikie93c86172013-01-17 05:26:25 +00003429 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003430 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003431
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003432 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003433 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003434 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003435 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003436 }
3437
Anders Carlsson711f34a2010-04-21 19:52:01 +00003438 // Keep track of the direct virtual bases.
3439 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3440 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3441 E = ClassDecl->bases_end(); I != E; ++I) {
3442 if (I->isVirtual())
3443 DirectVBases.insert(I);
3444 }
3445
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003446 // Push virtual bases before others.
3447 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3448 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3449
Sean Huntcbb67482011-01-08 20:30:50 +00003450 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003451 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003452 // [class.base.init]p7, per DR257:
3453 // A mem-initializer where the mem-initializer-id names a virtual base
3454 // class is ignored during execution of a constructor of any class that
3455 // is not the most derived class.
3456 if (ClassDecl->isAbstract()) {
3457 // FIXME: Provide a fixit to remove the base specifier. This requires
3458 // tracking the location of the associated comma for a base specifier.
3459 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3460 << VBase->getType() << ClassDecl;
3461 DiagnoseAbstractType(ClassDecl);
3462 }
3463
John McCallf1860e52010-05-20 23:23:51 +00003464 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003465 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3466 // [class.base.init]p8, per DR257:
3467 // If a given [...] base class is not named by a mem-initializer-id
3468 // [...] and the entity is not a virtual base class of an abstract
3469 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003470 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003471 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003472 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003473 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003474 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003475 HadError = true;
3476 continue;
3477 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003478
John McCallf1860e52010-05-20 23:23:51 +00003479 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003480 }
3481 }
Mike Stump1eb44332009-09-09 15:08:12 +00003482
John McCallf1860e52010-05-20 23:23:51 +00003483 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003484 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3485 E = ClassDecl->bases_end(); Base != E; ++Base) {
3486 // Virtuals are in the virtual base list and already constructed.
3487 if (Base->isVirtual())
3488 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003489
Sean Huntcbb67482011-01-08 20:30:50 +00003490 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003491 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3492 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003493 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003494 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003495 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003496 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003497 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003498 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003499 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003500 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +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 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003507 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3508 MemEnd = ClassDecl->decls_end();
3509 Mem != MemEnd; ++Mem) {
3510 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003511 // C++ [class.bit]p2:
3512 // A declaration for a bit-field that omits the identifier declares an
3513 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3514 // initialized.
3515 if (F->isUnnamedBitfield())
3516 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003517
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003518 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003519 // handle anonymous struct/union fields based on their individual
3520 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003521 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003522 continue;
3523
3524 if (CollectFieldInitializer(*this, Info, F))
3525 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003526 continue;
3527 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003528
3529 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003530 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003531 continue;
3532
3533 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3534 if (F->getType()->isIncompleteArrayType()) {
3535 assert(ClassDecl->hasFlexibleArrayMember() &&
3536 "Incomplete array type is not valid");
3537 continue;
3538 }
3539
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003540 // Initialize each field of an anonymous struct individually.
3541 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3542 HadError = true;
3543
3544 continue;
3545 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003546 }
Mike Stump1eb44332009-09-09 15:08:12 +00003547
David Blaikie93c86172013-01-17 05:26:25 +00003548 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003549 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003550 Constructor->setNumCtorInitializers(NumInitializers);
3551 CXXCtorInitializer **baseOrMemberInitializers =
3552 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003553 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003554 NumInitializers * sizeof(CXXCtorInitializer*));
3555 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003556
John McCallef027fe2010-03-16 21:39:52 +00003557 // Constructors implicitly reference the base and member
3558 // destructors.
3559 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3560 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003561 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003562
3563 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003564}
3565
David Blaikieee000bb2013-01-17 08:49:22 +00003566static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003567 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003568 const RecordDecl *RD = RT->getDecl();
3569 if (RD->isAnonymousStructOrUnion()) {
3570 for (RecordDecl::field_iterator Field = RD->field_begin(),
3571 E = RD->field_end(); Field != E; ++Field)
3572 PopulateKeysForFields(*Field, IdealInits);
3573 return;
3574 }
Eli Friedman6347f422009-07-21 19:28:10 +00003575 }
David Blaikieee000bb2013-01-17 08:49:22 +00003576 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003577}
3578
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003579static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3580 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003581}
3582
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003583static const void *GetKeyForMember(ASTContext &Context,
3584 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003585 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003586 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003587
David Blaikieee000bb2013-01-17 08:49:22 +00003588 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003589}
3590
David Blaikie93c86172013-01-17 05:26:25 +00003591static void DiagnoseBaseOrMemInitializerOrder(
3592 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3593 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003594 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003595 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003596
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003597 // Don't check initializers order unless the warning is enabled at the
3598 // location of at least one initializer.
3599 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003600 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003601 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003602 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3603 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003604 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003605 ShouldCheckOrder = true;
3606 break;
3607 }
3608 }
3609 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003610 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003611
John McCalld6ca8da2010-04-10 07:37:23 +00003612 // Build the list of bases and members in the order that they'll
3613 // actually be initialized. The explicit initializers should be in
3614 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003615 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Anders Carlsson071d6102010-04-02 03:38:04 +00003617 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3618
John McCalld6ca8da2010-04-10 07:37:23 +00003619 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003620 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003621 ClassDecl->vbases_begin(),
3622 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003623 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003624
John McCalld6ca8da2010-04-10 07:37:23 +00003625 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003626 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003627 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003628 if (Base->isVirtual())
3629 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003630 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003631 }
Mike Stump1eb44332009-09-09 15:08:12 +00003632
John McCalld6ca8da2010-04-10 07:37:23 +00003633 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003634 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003635 E = ClassDecl->field_end(); Field != E; ++Field) {
3636 if (Field->isUnnamedBitfield())
3637 continue;
3638
David Blaikieee000bb2013-01-17 08:49:22 +00003639 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003640 }
3641
John McCalld6ca8da2010-04-10 07:37:23 +00003642 unsigned NumIdealInits = IdealInitKeys.size();
3643 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003644
Sean Huntcbb67482011-01-08 20:30:50 +00003645 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003646 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003647 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003648 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003649
3650 // Scan forward to try to find this initializer in the idealized
3651 // initializers list.
3652 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3653 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003654 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003655
3656 // If we didn't find this initializer, it must be because we
3657 // scanned past it on a previous iteration. That can only
3658 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003659 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003660 Sema::SemaDiagnosticBuilder D =
3661 SemaRef.Diag(PrevInit->getSourceLocation(),
3662 diag::warn_initializer_out_of_order);
3663
Francois Pichet00eb3f92010-12-04 09:14:42 +00003664 if (PrevInit->isAnyMemberInitializer())
3665 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003666 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003667 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003668
Francois Pichet00eb3f92010-12-04 09:14:42 +00003669 if (Init->isAnyMemberInitializer())
3670 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003671 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003672 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003673
3674 // Move back to the initializer's location in the ideal list.
3675 for (IdealIndex = 0; 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 assert(IdealIndex != NumIdealInits &&
3680 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003681 }
John McCalld6ca8da2010-04-10 07:37:23 +00003682
3683 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003684 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003685}
3686
John McCall3c3ccdb2010-04-10 09:28:51 +00003687namespace {
3688bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003689 CXXCtorInitializer *Init,
3690 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003691 if (!PrevInit) {
3692 PrevInit = Init;
3693 return false;
3694 }
3695
Douglas Gregordc392c12013-03-25 23:28:23 +00003696 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003697 S.Diag(Init->getSourceLocation(),
3698 diag::err_multiple_mem_initialization)
3699 << Field->getDeclName()
3700 << Init->getSourceRange();
3701 else {
John McCallf4c73712011-01-19 06:33:43 +00003702 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003703 assert(BaseClass && "neither field nor base");
3704 S.Diag(Init->getSourceLocation(),
3705 diag::err_multiple_base_initialization)
3706 << QualType(BaseClass, 0)
3707 << Init->getSourceRange();
3708 }
3709 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3710 << 0 << PrevInit->getSourceRange();
3711
3712 return true;
3713}
3714
Sean Huntcbb67482011-01-08 20:30:50 +00003715typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003716typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3717
3718bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003719 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003720 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003721 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003722 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003723 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003724
3725 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003726 if (Parent->isUnion()) {
3727 UnionEntry &En = Unions[Parent];
3728 if (En.first && En.first != Child) {
3729 S.Diag(Init->getSourceLocation(),
3730 diag::err_multiple_mem_union_initialization)
3731 << Field->getDeclName()
3732 << Init->getSourceRange();
3733 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3734 << 0 << En.second->getSourceRange();
3735 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003736 }
3737 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003738 En.first = Child;
3739 En.second = Init;
3740 }
David Blaikie6fe29652011-11-17 06:01:57 +00003741 if (!Parent->isAnonymousStructOrUnion())
3742 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003743 }
3744
3745 Child = Parent;
3746 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003747 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003748
3749 return false;
3750}
3751}
3752
Richard Trieu225e9822013-09-16 21:54:53 +00003753// Diagnose value-uses of fields to initialize themselves, e.g.
3754// foo(foo)
3755// where foo is not also a parameter to the constructor.
Richard Trieuef8f90c2013-09-20 03:03:06 +00003756// Also diagnose across field uninitialized use such as
3757// x(y), y(x)
Richard Trieu225e9822013-09-16 21:54:53 +00003758// TODO: implement -Wuninitialized and fold this into that framework.
Richard Trieu225e9822013-09-16 21:54:53 +00003759static void DiagnoseUnitializedFields(
3760 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3761
3762 if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
3763 Constructor->getLocation())
3764 == DiagnosticsEngine::Ignored) {
3765 return;
3766 }
3767
Richard Trieuef8f90c2013-09-20 03:03:06 +00003768 const CXXRecordDecl *RD = Constructor->getParent();
3769
3770 // Holds fields that are uninitialized.
3771 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3772
3773 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
3774 I != E; ++I) {
3775 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
3776 UninitializedFields.insert(FD);
3777 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
3778 UninitializedFields.insert(IFD->getAnonField());
3779 }
3780 }
3781
3782 // Fields already checked when processing the in class initializers.
3783 llvm::SmallPtrSet<ValueDecl*, 4>
3784 InClassUninitializedFields = UninitializedFields;
3785
3786 for (CXXConstructorDecl::init_const_iterator FieldInit =
3787 Constructor->init_begin(),
Richard Trieu225e9822013-09-16 21:54:53 +00003788 FieldInitEnd = Constructor->init_end();
3789 FieldInit != FieldInitEnd; ++FieldInit) {
3790
Richard Trieuef8f90c2013-09-20 03:03:06 +00003791 FieldDecl *Field = (*FieldInit)->getAnyMember();
Richard Trieu225e9822013-09-16 21:54:53 +00003792 Expr *InitExpr = (*FieldInit)->getInit();
3793
Richard Trieuef8f90c2013-09-20 03:03:06 +00003794 if (!Field) {
3795 CheckInitExprContainsUninitializedFields(
3796 SemaRef, InitExpr, 0, UninitializedFields,
3797 false/*WarnOnSelfReference*/);
3798 continue;
Richard Trieu225e9822013-09-16 21:54:53 +00003799 }
Richard Trieuef8f90c2013-09-20 03:03:06 +00003800
3801 if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3802 // This field is initialized with an in-class initailzer. Remove the
3803 // fields already checked to prevent duplicate warnings.
3804 llvm::SmallPtrSet<ValueDecl*, 4> DiffSet = UninitializedFields;
3805 for (llvm::SmallPtrSet<ValueDecl*, 4>::iterator
3806 I = InClassUninitializedFields.begin(),
3807 E = InClassUninitializedFields.end();
3808 I != E; ++I) {
3809 DiffSet.erase(*I);
3810 }
3811 CheckInitExprContainsUninitializedFields(
3812 SemaRef, Default->getExpr(), Field, DiffSet,
3813 DiffSet.count(Field), Constructor);
3814
3815 // Update the unitialized field sets.
3816 CheckInitExprContainsUninitializedFields(
3817 SemaRef, Default->getExpr(), 0, UninitializedFields,
3818 false);
3819 CheckInitExprContainsUninitializedFields(
3820 SemaRef, Default->getExpr(), 0, InClassUninitializedFields,
3821 false);
3822 } else {
3823 CheckInitExprContainsUninitializedFields(
3824 SemaRef, InitExpr, Field, UninitializedFields,
3825 UninitializedFields.count(Field));
3826 if (Expr* InClassInit = Field->getInClassInitializer()) {
3827 CheckInitExprContainsUninitializedFields(
3828 SemaRef, InClassInit, 0, InClassUninitializedFields,
3829 false);
3830 }
3831 }
3832 UninitializedFields.erase(Field);
3833 InClassUninitializedFields.erase(Field);
Richard Trieu225e9822013-09-16 21:54:53 +00003834 }
3835}
3836
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003837/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003838void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003839 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003840 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003841 bool AnyErrors) {
3842 if (!ConstructorDecl)
3843 return;
3844
3845 AdjustDeclIfTemplate(ConstructorDecl);
3846
3847 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003848 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003849
3850 if (!Constructor) {
3851 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3852 return;
3853 }
3854
John McCall3c3ccdb2010-04-10 09:28:51 +00003855 // Mapping for the duplicate initializers check.
3856 // For member initializers, this is keyed with a FieldDecl*.
3857 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003858 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003859
3860 // Mapping for the inconsistent anonymous-union initializers check.
3861 RedundantUnionMap MemberUnions;
3862
Anders Carlssonea356fb2010-04-02 05:42:15 +00003863 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003864 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003865 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003866
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003867 // Set the source order index.
3868 Init->setSourceOrder(i);
3869
Francois Pichet00eb3f92010-12-04 09:14:42 +00003870 if (Init->isAnyMemberInitializer()) {
3871 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003872 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3873 CheckRedundantUnionInit(*this, Init, MemberUnions))
3874 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003875 } else if (Init->isBaseInitializer()) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003876 const void *Key =
3877 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall3c3ccdb2010-04-10 09:28:51 +00003878 if (CheckRedundantInit(*this, Init, Members[Key]))
3879 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003880 } else {
3881 assert(Init->isDelegatingInitializer());
3882 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003883 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003884 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003885 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003886 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003887 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003888 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003889 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003890 // Return immediately as the initializer is set.
3891 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003892 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003893 }
3894
Anders Carlssonea356fb2010-04-02 05:42:15 +00003895 if (HadError)
3896 return;
3897
David Blaikie93c86172013-01-17 05:26:25 +00003898 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003899
David Blaikie93c86172013-01-17 05:26:25 +00003900 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Richard Trieu225e9822013-09-16 21:54:53 +00003901
3902 DiagnoseUnitializedFields(*this, Constructor);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003903}
3904
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003905void
John McCallef027fe2010-03-16 21:39:52 +00003906Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3907 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003908 // Ignore dependent contexts. Also ignore unions, since their members never
3909 // have destructors implicitly called.
3910 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003911 return;
John McCall58e6f342010-03-16 05:22:47 +00003912
3913 // FIXME: all the access-control diagnostics are positioned on the
3914 // field/base declaration. That's probably good; that said, the
3915 // user might reasonably want to know why the destructor is being
3916 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003917
Anders Carlsson9f853df2009-11-17 04:44:12 +00003918 // Non-static data members.
3919 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3920 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003921 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003922 if (Field->isInvalidDecl())
3923 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003924
3925 // Don't destroy incomplete or zero-length arrays.
3926 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3927 continue;
3928
Anders Carlsson9f853df2009-11-17 04:44:12 +00003929 QualType FieldType = Context.getBaseElementType(Field->getType());
3930
3931 const RecordType* RT = FieldType->getAs<RecordType>();
3932 if (!RT)
3933 continue;
3934
3935 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003936 if (FieldClassDecl->isInvalidDecl())
3937 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003938 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003939 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003940 // The destructor for an implicit anonymous union member is never invoked.
3941 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3942 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003943
Douglas Gregordb89f282010-07-01 22:47:18 +00003944 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003945 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003946 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003947 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003948 << Field->getDeclName()
3949 << FieldType);
3950
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003951 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003952 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003953 }
3954
John McCall58e6f342010-03-16 05:22:47 +00003955 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3956
Anders Carlsson9f853df2009-11-17 04:44:12 +00003957 // Bases.
3958 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3959 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003960 // Bases are always records in a well-formed non-dependent class.
3961 const RecordType *RT = Base->getType()->getAs<RecordType>();
3962
3963 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003964 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003965 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003966
John McCall58e6f342010-03-16 05:22:47 +00003967 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003968 // If our base class is invalid, we probably can't get its dtor anyway.
3969 if (BaseClassDecl->isInvalidDecl())
3970 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003971 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003972 continue;
John McCall58e6f342010-03-16 05:22:47 +00003973
Douglas Gregordb89f282010-07-01 22:47:18 +00003974 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003975 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003976
3977 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003978 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003979 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003980 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003981 << Base->getSourceRange(),
3982 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003983
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003984 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003985 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003986 }
3987
3988 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003989 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3990 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003991
3992 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003993 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003994
3995 // Ignore direct virtual bases.
3996 if (DirectVirtualBases.count(RT))
3997 continue;
3998
John McCall58e6f342010-03-16 05:22:47 +00003999 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004000 // If our base class is invalid, we probably can't get its dtor anyway.
4001 if (BaseClassDecl->isInvalidDecl())
4002 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00004003 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004004 continue;
John McCall58e6f342010-03-16 05:22:47 +00004005
Douglas Gregordb89f282010-07-01 22:47:18 +00004006 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00004007 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00004008 if (CheckDestructorAccess(
4009 ClassDecl->getLocation(), Dtor,
4010 PDiag(diag::err_access_dtor_vbase)
4011 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
4012 Context.getTypeDeclType(ClassDecl)) ==
4013 AR_accessible) {
4014 CheckDerivedToBaseConversion(
4015 Context.getTypeDeclType(ClassDecl), VBase->getType(),
4016 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
4017 SourceRange(), DeclarationName(), 0);
4018 }
John McCall58e6f342010-03-16 05:22:47 +00004019
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004020 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00004021 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00004022 }
4023}
4024
John McCalld226f652010-08-21 09:40:31 +00004025void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00004026 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004027 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004028
Mike Stump1eb44332009-09-09 15:08:12 +00004029 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00004030 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00004031 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00004032}
4033
Mike Stump1eb44332009-09-09 15:08:12 +00004034bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00004035 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004036 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4037 unsigned DiagID;
4038 AbstractDiagSelID SelID;
4039
4040 public:
4041 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4042 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00004043
4044 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman2217f852012-08-14 02:06:07 +00004045 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004046 if (SelID == -1)
4047 S.Diag(Loc, DiagID) << T;
4048 else
4049 S.Diag(Loc, DiagID) << SelID << T;
4050 }
4051 } Diagnoser(DiagID, SelID);
4052
4053 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004054}
4055
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00004056bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004057 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00004058 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004059 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004060
Anders Carlsson11f21a02009-03-23 19:10:31 +00004061 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004062 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00004063
Ted Kremenek6217b802009-07-29 21:53:49 +00004064 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004065 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004066 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004067 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00004068
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004069 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004070 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00004071 }
Mike Stump1eb44332009-09-09 15:08:12 +00004072
Ted Kremenek6217b802009-07-29 21:53:49 +00004073 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004074 if (!RT)
4075 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004076
John McCall86ff3082010-02-04 22:26:26 +00004077 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004078
John McCall94c3b562010-08-18 09:41:07 +00004079 // We can't answer whether something is abstract until it has a
4080 // definition. If it's currently being defined, we'll walk back
4081 // over all the declarations when we have a full definition.
4082 const CXXRecordDecl *Def = RD->getDefinition();
4083 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00004084 return false;
4085
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004086 if (!RD->isAbstract())
4087 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004088
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00004089 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00004090 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00004091
John McCall94c3b562010-08-18 09:41:07 +00004092 return true;
4093}
4094
4095void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4096 // Check if we've already emitted the list of pure virtual functions
4097 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004098 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00004099 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004100
Richard Smithcbc820a2013-07-22 02:56:56 +00004101 // If the diagnostic is suppressed, don't emit the notes. We're only
4102 // going to emit them once, so try to attach them to a diagnostic we're
4103 // actually going to show.
4104 if (Diags.isLastDiagnosticIgnored())
4105 return;
4106
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004107 CXXFinalOverriderMap FinalOverriders;
4108 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00004109
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004110 // Keep a set of seen pure methods so we won't diagnose the same method
4111 // more than once.
4112 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4113
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004114 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4115 MEnd = FinalOverriders.end();
4116 M != MEnd;
4117 ++M) {
4118 for (OverridingMethods::iterator SO = M->second.begin(),
4119 SOEnd = M->second.end();
4120 SO != SOEnd; ++SO) {
4121 // C++ [class.abstract]p4:
4122 // A class is abstract if it contains or inherits at least one
4123 // pure virtual function for which the final overrider is pure
4124 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00004125
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004126 //
4127 if (SO->second.size() != 1)
4128 continue;
4129
4130 if (!SO->second.front().Method->isPure())
4131 continue;
4132
Anders Carlssonffdb2d22010-06-03 01:00:02 +00004133 if (!SeenPureMethods.insert(SO->second.front().Method))
4134 continue;
4135
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004136 Diag(SO->second.front().Method->getLocation(),
4137 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00004138 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00004139 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004140 }
4141
4142 if (!PureVirtualClassDiagSet)
4143 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4144 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00004145}
4146
Anders Carlsson8211eff2009-03-24 01:19:16 +00004147namespace {
John McCall94c3b562010-08-18 09:41:07 +00004148struct AbstractUsageInfo {
4149 Sema &S;
4150 CXXRecordDecl *Record;
4151 CanQualType AbstractType;
4152 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00004153
John McCall94c3b562010-08-18 09:41:07 +00004154 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4155 : S(S), Record(Record),
4156 AbstractType(S.Context.getCanonicalType(
4157 S.Context.getTypeDeclType(Record))),
4158 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00004159
John McCall94c3b562010-08-18 09:41:07 +00004160 void DiagnoseAbstractType() {
4161 if (Invalid) return;
4162 S.DiagnoseAbstractType(Record);
4163 Invalid = true;
4164 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00004165
John McCall94c3b562010-08-18 09:41:07 +00004166 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4167};
4168
4169struct CheckAbstractUsage {
4170 AbstractUsageInfo &Info;
4171 const NamedDecl *Ctx;
4172
4173 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4174 : Info(Info), Ctx(Ctx) {}
4175
4176 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4177 switch (TL.getTypeLocClass()) {
4178#define ABSTRACT_TYPELOC(CLASS, PARENT)
4179#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004180 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004181#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004182 }
John McCall94c3b562010-08-18 09:41:07 +00004183 }
Mike Stump1eb44332009-09-09 15:08:12 +00004184
John McCall94c3b562010-08-18 09:41:07 +00004185 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4186 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4187 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00004188 if (!TL.getArg(I))
4189 continue;
4190
John McCall94c3b562010-08-18 09:41:07 +00004191 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4192 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004193 }
John McCall94c3b562010-08-18 09:41:07 +00004194 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004195
John McCall94c3b562010-08-18 09:41:07 +00004196 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4197 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4198 }
Mike Stump1eb44332009-09-09 15:08:12 +00004199
John McCall94c3b562010-08-18 09:41:07 +00004200 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4201 // Visit the type parameters from a permissive context.
4202 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4203 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4204 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4205 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4206 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4207 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004208 }
John McCall94c3b562010-08-18 09:41:07 +00004209 }
Mike Stump1eb44332009-09-09 15:08:12 +00004210
John McCall94c3b562010-08-18 09:41:07 +00004211 // Visit pointee types from a permissive context.
4212#define CheckPolymorphic(Type) \
4213 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4214 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4215 }
4216 CheckPolymorphic(PointerTypeLoc)
4217 CheckPolymorphic(ReferenceTypeLoc)
4218 CheckPolymorphic(MemberPointerTypeLoc)
4219 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004220 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004221
John McCall94c3b562010-08-18 09:41:07 +00004222 /// Handle all the types we haven't given a more specific
4223 /// implementation for above.
4224 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4225 // Every other kind of type that we haven't called out already
4226 // that has an inner type is either (1) sugar or (2) contains that
4227 // inner type in some way as a subobject.
4228 if (TypeLoc Next = TL.getNextTypeLoc())
4229 return Visit(Next, Sel);
4230
4231 // If there's no inner type and we're in a permissive context,
4232 // don't diagnose.
4233 if (Sel == Sema::AbstractNone) return;
4234
4235 // Check whether the type matches the abstract type.
4236 QualType T = TL.getType();
4237 if (T->isArrayType()) {
4238 Sel = Sema::AbstractArrayType;
4239 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004240 }
John McCall94c3b562010-08-18 09:41:07 +00004241 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4242 if (CT != Info.AbstractType) return;
4243
4244 // It matched; do some magic.
4245 if (Sel == Sema::AbstractArrayType) {
4246 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4247 << T << TL.getSourceRange();
4248 } else {
4249 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4250 << Sel << T << TL.getSourceRange();
4251 }
4252 Info.DiagnoseAbstractType();
4253 }
4254};
4255
4256void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4257 Sema::AbstractDiagSelID Sel) {
4258 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4259}
4260
4261}
4262
4263/// Check for invalid uses of an abstract type in a method declaration.
4264static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4265 CXXMethodDecl *MD) {
4266 // No need to do the check on definitions, which require that
4267 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004268 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004269 return;
4270
4271 // For safety's sake, just ignore it if we don't have type source
4272 // information. This should never happen for non-implicit methods,
4273 // but...
4274 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4275 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4276}
4277
4278/// Check for invalid uses of an abstract type within a class definition.
4279static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4280 CXXRecordDecl *RD) {
4281 for (CXXRecordDecl::decl_iterator
4282 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4283 Decl *D = *I;
4284 if (D->isImplicit()) continue;
4285
4286 // Methods and method templates.
4287 if (isa<CXXMethodDecl>(D)) {
4288 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4289 } else if (isa<FunctionTemplateDecl>(D)) {
4290 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4291 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4292
4293 // Fields and static variables.
4294 } else if (isa<FieldDecl>(D)) {
4295 FieldDecl *FD = cast<FieldDecl>(D);
4296 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4297 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4298 } else if (isa<VarDecl>(D)) {
4299 VarDecl *VD = cast<VarDecl>(D);
4300 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4301 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4302
4303 // Nested classes and class templates.
4304 } else if (isa<CXXRecordDecl>(D)) {
4305 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4306 } else if (isa<ClassTemplateDecl>(D)) {
4307 CheckAbstractClassUsage(Info,
4308 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4309 }
4310 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004311}
4312
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004313/// \brief Perform semantic checks on a class definition that has been
4314/// completing, introducing implicitly-declared members, checking for
4315/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004316void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004317 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004318 return;
4319
John McCall94c3b562010-08-18 09:41:07 +00004320 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4321 AbstractUsageInfo Info(*this, Record);
4322 CheckAbstractClassUsage(Info, Record);
4323 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004324
4325 // If this is not an aggregate type and has no user-declared constructor,
4326 // complain about any non-static data members of reference or const scalar
4327 // type, since they will never get initializers.
4328 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004329 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4330 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004331 bool Complained = false;
4332 for (RecordDecl::field_iterator F = Record->field_begin(),
4333 FEnd = Record->field_end();
4334 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004335 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004336 continue;
4337
Douglas Gregor325e5932010-04-15 00:00:53 +00004338 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004339 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004340 if (!Complained) {
4341 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4342 << Record->getTagKind() << Record;
4343 Complained = true;
4344 }
4345
4346 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4347 << F->getType()->isReferenceType()
4348 << F->getDeclName();
4349 }
4350 }
4351 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004352
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004353 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004354 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004355
4356 if (Record->getIdentifier()) {
4357 // C++ [class.mem]p13:
4358 // If T is the name of a class, then each of the following shall have a
4359 // name different from T:
4360 // - every member of every anonymous union that is a member of class T.
4361 //
4362 // C++ [class.mem]p14:
4363 // In addition, if class T has a user-declared constructor (12.1), every
4364 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004365 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4366 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4367 ++I) {
4368 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004369 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4370 isa<IndirectFieldDecl>(D)) {
4371 Diag(D->getLocation(), diag::err_member_name_of_class)
4372 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004373 break;
4374 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004375 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004376 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004377
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004378 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004379 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004380 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004381 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004382 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4383 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4384 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004385
David Blaikieb6b5b972012-09-21 03:21:07 +00004386 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4387 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4388 DiagnoseAbstractType(Record);
4389 }
4390
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004391 if (!Record->isDependentType()) {
4392 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4393 MEnd = Record->method_end();
4394 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004395 // See if a method overloads virtual methods in a base
4396 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004397 if (!M->isStatic())
Eli Friedmandae92712013-09-05 23:51:03 +00004398 DiagnoseHiddenVirtualMethods(*M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004399
4400 // Check whether the explicitly-defaulted special members are valid.
4401 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4402 CheckExplicitlyDefaultedSpecialMember(*M);
4403
4404 // For an explicitly defaulted or deleted special member, we defer
4405 // determining triviality until the class is complete. That time is now!
4406 if (!M->isImplicit() && !M->isUserProvided()) {
4407 CXXSpecialMember CSM = getSpecialMember(*M);
4408 if (CSM != CXXInvalid) {
4409 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4410
4411 // Inform the class that we've finished declaring this member.
4412 Record->finishedDefaultedOrDeletedMember(*M);
4413 }
4414 }
4415 }
4416 }
4417
4418 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4419 // function that is not a constructor declares that member function to be
4420 // const. [...] The class of which that function is a member shall be
4421 // a literal type.
4422 //
4423 // If the class has virtual bases, any constexpr members will already have
4424 // been diagnosed by the checks performed on the member declaration, so
4425 // suppress this (less useful) diagnostic.
4426 //
4427 // We delay this until we know whether an explicitly-defaulted (or deleted)
4428 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004429 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004430 !Record->isLiteral() && !Record->getNumVBases()) {
4431 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4432 MEnd = Record->method_end();
4433 M != MEnd; ++M) {
4434 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4435 switch (Record->getTemplateSpecializationKind()) {
4436 case TSK_ImplicitInstantiation:
4437 case TSK_ExplicitInstantiationDeclaration:
4438 case TSK_ExplicitInstantiationDefinition:
4439 // If a template instantiates to a non-literal type, but its members
4440 // instantiate to constexpr functions, the template is technically
4441 // ill-formed, but we allow it for sanity.
4442 continue;
4443
4444 case TSK_Undeclared:
4445 case TSK_ExplicitSpecialization:
4446 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4447 diag::err_constexpr_method_non_literal);
4448 break;
4449 }
4450
4451 // Only produce one error per class.
4452 break;
4453 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004454 }
4455 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004456
Richard Smith07b0fdc2013-03-18 21:12:30 +00004457 // Declare inheriting constructors. We do this eagerly here because:
4458 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004459 // constructors from different classes.
4460 // - The lazy declaration of the other implicit constructors is so as to not
4461 // waste space and performance on classes that are not meant to be
4462 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004463 // have inheriting constructors.
4464 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004465}
4466
Richard Smith7756afa2012-06-10 05:43:50 +00004467/// Is the special member function which would be selected to perform the
4468/// specified operation on the specified class type a constexpr constructor?
4469static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4470 Sema::CXXSpecialMember CSM,
4471 bool ConstArg) {
4472 Sema::SpecialMemberOverloadResult *SMOR =
4473 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4474 false, false, false, false);
4475 if (!SMOR || !SMOR->getMethod())
4476 // A constructor we wouldn't select can't be "involved in initializing"
4477 // anything.
4478 return true;
4479 return SMOR->getMethod()->isConstexpr();
4480}
4481
4482/// Determine whether the specified special member function would be constexpr
4483/// if it were implicitly defined.
4484static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4485 Sema::CXXSpecialMember CSM,
4486 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004487 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004488 return false;
4489
4490 // C++11 [dcl.constexpr]p4:
4491 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004492 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004493 switch (CSM) {
4494 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004495 // Since default constructor lookup is essentially trivial (and cannot
4496 // involve, for instance, template instantiation), we compute whether a
4497 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4498 //
4499 // This is important for performance; we need to know whether the default
4500 // constructor is constexpr to determine whether the type is a literal type.
4501 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4502
Richard Smith7756afa2012-06-10 05:43:50 +00004503 case Sema::CXXCopyConstructor:
4504 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004505 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004506 break;
4507
4508 case Sema::CXXCopyAssignment:
4509 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004510 if (!S.getLangOpts().CPlusPlus1y)
4511 return false;
4512 // In C++1y, we need to perform overload resolution.
4513 Ctor = false;
4514 break;
4515
Richard Smith7756afa2012-06-10 05:43:50 +00004516 case Sema::CXXDestructor:
4517 case Sema::CXXInvalid:
4518 return false;
4519 }
4520
4521 // -- if the class is a non-empty union, or for each non-empty anonymous
4522 // union member of a non-union class, exactly one non-static data member
4523 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004524 //
4525 // If we squint, this is guaranteed, since exactly one non-static data member
4526 // will be initialized (if the constructor isn't deleted), we just don't know
4527 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004528 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004529 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004530
4531 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004532 if (Ctor && ClassDecl->getNumVBases())
4533 return false;
4534
4535 // C++1y [class.copy]p26:
4536 // -- [the class] is a literal type, and
4537 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004538 return false;
4539
4540 // -- every constructor involved in initializing [...] base class
4541 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004542 // -- the assignment operator selected to copy/move each direct base
4543 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004544 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4545 BEnd = ClassDecl->bases_end();
4546 B != BEnd; ++B) {
4547 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4548 if (!BaseType) continue;
4549
4550 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4551 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4552 return false;
4553 }
4554
4555 // -- every constructor involved in initializing non-static data members
4556 // [...] shall be a constexpr constructor;
4557 // -- every non-static data member and base class sub-object shall be
4558 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004559 // -- for each non-stastic data member of X that is of class type (or array
4560 // thereof), the assignment operator selected to copy/move that member is
4561 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004562 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4563 FEnd = ClassDecl->field_end();
4564 F != FEnd; ++F) {
4565 if (F->isInvalidDecl())
4566 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004567 if (const RecordType *RecordTy =
4568 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004569 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4570 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4571 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004572 }
4573 }
4574
4575 // All OK, it's constexpr!
4576 return true;
4577}
4578
Richard Smithb9d0b762012-07-27 04:22:15 +00004579static Sema::ImplicitExceptionSpecification
4580computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4581 switch (S.getSpecialMember(MD)) {
4582 case Sema::CXXDefaultConstructor:
4583 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4584 case Sema::CXXCopyConstructor:
4585 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4586 case Sema::CXXCopyAssignment:
4587 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4588 case Sema::CXXMoveConstructor:
4589 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4590 case Sema::CXXMoveAssignment:
4591 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4592 case Sema::CXXDestructor:
4593 return S.ComputeDefaultedDtorExceptionSpec(MD);
4594 case Sema::CXXInvalid:
4595 break;
4596 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004597 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4598 "only special members have implicit exception specs");
4599 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004600}
4601
Richard Smithdd25e802012-07-30 23:48:14 +00004602static void
4603updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4604 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4605 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4606 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004607 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4608 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004609}
4610
Reid Kleckneref072032013-08-27 23:08:25 +00004611static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4612 CXXMethodDecl *MD) {
4613 FunctionProtoType::ExtProtoInfo EPI;
4614
4615 // Build an exception specification pointing back at this member.
4616 EPI.ExceptionSpecType = EST_Unevaluated;
4617 EPI.ExceptionSpecDecl = MD;
4618
4619 // Set the calling convention to the default for C++ instance methods.
4620 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4621 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4622 /*IsCXXMethod=*/true));
4623 return EPI;
4624}
4625
Richard Smithb9d0b762012-07-27 04:22:15 +00004626void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4627 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4628 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4629 return;
4630
Richard Smithdd25e802012-07-30 23:48:14 +00004631 // Evaluate the exception specification.
4632 ImplicitExceptionSpecification ExceptSpec =
4633 computeImplicitExceptionSpec(*this, Loc, MD);
4634
4635 // Update the type of the special member to use it.
4636 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4637
4638 // A user-provided destructor can be defined outside the class. When that
4639 // happens, be sure to update the exception specification on both
4640 // declarations.
4641 const FunctionProtoType *CanonicalFPT =
4642 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4643 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4644 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4645 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004646}
4647
Richard Smith3003e1d2012-05-15 04:39:51 +00004648void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4649 CXXRecordDecl *RD = MD->getParent();
4650 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004651
Richard Smith3003e1d2012-05-15 04:39:51 +00004652 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4653 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004654
4655 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004656 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004657 bool First = MD == MD->getCanonicalDecl();
4658
4659 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004660
4661 // C++11 [dcl.fct.def.default]p1:
4662 // A function that is explicitly defaulted shall
4663 // -- be a special member function (checked elsewhere),
4664 // -- have the same type (except for ref-qualifiers, and except that a
4665 // copy operation can take a non-const reference) as an implicit
4666 // declaration, and
4667 // -- not have default arguments.
4668 unsigned ExpectedParams = 1;
4669 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4670 ExpectedParams = 0;
4671 if (MD->getNumParams() != ExpectedParams) {
4672 // This also checks for default arguments: a copy or move constructor with a
4673 // default argument is classified as a default constructor, and assignment
4674 // operations and destructors can't have default arguments.
4675 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4676 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004677 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004678 } else if (MD->isVariadic()) {
4679 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4680 << CSM << MD->getSourceRange();
4681 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004682 }
4683
Richard Smith3003e1d2012-05-15 04:39:51 +00004684 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004685
Richard Smith7756afa2012-06-10 05:43:50 +00004686 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004687 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004688 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004689 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004690 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004691
Richard Smith3003e1d2012-05-15 04:39:51 +00004692 QualType ReturnType = Context.VoidTy;
4693 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4694 // Check for return type matching.
4695 ReturnType = Type->getResultType();
4696 QualType ExpectedReturnType =
4697 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4698 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4699 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4700 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4701 HadError = true;
4702 }
4703
4704 // A defaulted special member cannot have cv-qualifiers.
4705 if (Type->getTypeQuals()) {
4706 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004707 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004708 HadError = true;
4709 }
4710 }
4711
4712 // Check for parameter type matching.
4713 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004714 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004715 if (ExpectedParams && ArgType->isReferenceType()) {
4716 // Argument must be reference to possibly-const T.
4717 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004718 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004719
4720 if (ReferentType.isVolatileQualified()) {
4721 Diag(MD->getLocation(),
4722 diag::err_defaulted_special_member_volatile_param) << CSM;
4723 HadError = true;
4724 }
4725
Richard Smith7756afa2012-06-10 05:43:50 +00004726 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004727 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4728 Diag(MD->getLocation(),
4729 diag::err_defaulted_special_member_copy_const_param)
4730 << (CSM == CXXCopyAssignment);
4731 // FIXME: Explain why this special member can't be const.
4732 } else {
4733 Diag(MD->getLocation(),
4734 diag::err_defaulted_special_member_move_const_param)
4735 << (CSM == CXXMoveAssignment);
4736 }
4737 HadError = true;
4738 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004739 } else if (ExpectedParams) {
4740 // A copy assignment operator can take its argument by value, but a
4741 // defaulted one cannot.
4742 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004743 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004744 HadError = true;
4745 }
Sean Huntbe631222011-05-17 20:44:43 +00004746
Richard Smith61802452011-12-22 02:22:31 +00004747 // C++11 [dcl.fct.def.default]p2:
4748 // An explicitly-defaulted function may be declared constexpr only if it
4749 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004750 // Do not apply this rule to members of class templates, since core issue 1358
4751 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004752 // functions which cannot be constexpr (for non-constructors in C++11 and for
4753 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004754 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4755 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004756 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4757 : isa<CXXConstructorDecl>(MD)) &&
4758 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004759 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4760 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004761 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004762 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004763 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004764
Richard Smith61802452011-12-22 02:22:31 +00004765 // and may have an explicit exception-specification only if it is compatible
4766 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004767 if (Type->hasExceptionSpec()) {
4768 // Delay the check if this is the first declaration of the special member,
4769 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004770 if (First) {
4771 // If the exception specification needs to be instantiated, do so now,
4772 // before we clobber it with an EST_Unevaluated specification below.
4773 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4774 InstantiateExceptionSpec(MD->getLocStart(), MD);
4775 Type = MD->getType()->getAs<FunctionProtoType>();
4776 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004777 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004778 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004779 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4780 }
Richard Smith61802452011-12-22 02:22:31 +00004781
4782 // If a function is explicitly defaulted on its first declaration,
4783 if (First) {
4784 // -- it is implicitly considered to be constexpr if the implicit
4785 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004786 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004787
Richard Smith3003e1d2012-05-15 04:39:51 +00004788 // -- it is implicitly considered to have the same exception-specification
4789 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004790 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4791 EPI.ExceptionSpecType = EST_Unevaluated;
4792 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004793 MD->setType(Context.getFunctionType(ReturnType,
4794 ArrayRef<QualType>(&ArgType,
4795 ExpectedParams),
4796 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004797 }
4798
Richard Smith3003e1d2012-05-15 04:39:51 +00004799 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004800 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004801 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004802 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004803 // C++11 [dcl.fct.def.default]p4:
4804 // [For a] user-provided explicitly-defaulted function [...] if such a
4805 // function is implicitly defined as deleted, the program is ill-formed.
4806 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4807 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004808 }
4809 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004810
Richard Smith3003e1d2012-05-15 04:39:51 +00004811 if (HadError)
4812 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004813}
4814
Richard Smith1d28caf2012-12-11 01:14:52 +00004815/// Check whether the exception specification provided for an
4816/// explicitly-defaulted special member matches the exception specification
4817/// that would have been generated for an implicit special member, per
4818/// C++11 [dcl.fct.def.default]p2.
4819void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4820 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4821 // Compute the implicit exception specification.
Reid Kleckneref072032013-08-27 23:08:25 +00004822 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4823 /*IsCXXMethod=*/true);
4824 FunctionProtoType::ExtProtoInfo EPI(CC);
Richard Smith1d28caf2012-12-11 01:14:52 +00004825 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4826 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004827 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004828
4829 // Ensure that it matches.
4830 CheckEquivalentExceptionSpec(
4831 PDiag(diag::err_incorrect_defaulted_exception_spec)
4832 << getSpecialMember(MD), PDiag(),
4833 ImplicitType, SourceLocation(),
4834 SpecifiedType, MD->getLocation());
4835}
4836
4837void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4838 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4839 I != N; ++I)
4840 CheckExplicitlyDefaultedMemberExceptionSpec(
4841 DelayedDefaultedMemberExceptionSpecs[I].first,
4842 DelayedDefaultedMemberExceptionSpecs[I].second);
4843
4844 DelayedDefaultedMemberExceptionSpecs.clear();
4845}
4846
Richard Smith7d5088a2012-02-18 02:02:13 +00004847namespace {
4848struct SpecialMemberDeletionInfo {
4849 Sema &S;
4850 CXXMethodDecl *MD;
4851 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004852 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004853
4854 // Properties of the special member, computed for convenience.
4855 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4856 SourceLocation Loc;
4857
4858 bool AllFieldsAreConst;
4859
4860 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004861 Sema::CXXSpecialMember CSM, bool Diagnose)
4862 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004863 IsConstructor(false), IsAssignment(false), IsMove(false),
4864 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4865 AllFieldsAreConst(true) {
4866 switch (CSM) {
4867 case Sema::CXXDefaultConstructor:
4868 case Sema::CXXCopyConstructor:
4869 IsConstructor = true;
4870 break;
4871 case Sema::CXXMoveConstructor:
4872 IsConstructor = true;
4873 IsMove = true;
4874 break;
4875 case Sema::CXXCopyAssignment:
4876 IsAssignment = true;
4877 break;
4878 case Sema::CXXMoveAssignment:
4879 IsAssignment = true;
4880 IsMove = true;
4881 break;
4882 case Sema::CXXDestructor:
4883 break;
4884 case Sema::CXXInvalid:
4885 llvm_unreachable("invalid special member kind");
4886 }
4887
4888 if (MD->getNumParams()) {
4889 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4890 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4891 }
4892 }
4893
4894 bool inUnion() const { return MD->getParent()->isUnion(); }
4895
4896 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004897 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4898 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004899 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004900 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4901 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4902 Quals = 0;
4903 return S.LookupSpecialMember(Class, CSM,
4904 ConstArg || (Quals & Qualifiers::Const),
4905 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004906 MD->getRefQualifier() == RQ_RValue,
4907 TQ & Qualifiers::Const,
4908 TQ & Qualifiers::Volatile);
4909 }
4910
Richard Smith6c4c36c2012-03-30 20:53:28 +00004911 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004912
Richard Smith6c4c36c2012-03-30 20:53:28 +00004913 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004914 bool shouldDeleteForField(FieldDecl *FD);
4915 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004916
Richard Smith517bb842012-07-18 03:51:16 +00004917 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4918 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004919 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4920 Sema::SpecialMemberOverloadResult *SMOR,
4921 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004922
4923 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004924};
4925}
4926
John McCall12d8d802012-04-09 20:53:23 +00004927/// Is the given special member inaccessible when used on the given
4928/// sub-object.
4929bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4930 CXXMethodDecl *target) {
4931 /// If we're operating on a base class, the object type is the
4932 /// type of this special member.
4933 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004934 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004935 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4936 objectTy = S.Context.getTypeDeclType(MD->getParent());
4937 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4938
4939 // If we're operating on a field, the object type is the type of the field.
4940 } else {
4941 objectTy = S.Context.getTypeDeclType(target->getParent());
4942 }
4943
4944 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4945}
4946
Richard Smith6c4c36c2012-03-30 20:53:28 +00004947/// Check whether we should delete a special member due to the implicit
4948/// definition containing a call to a special member of a subobject.
4949bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4950 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4951 bool IsDtorCallInCtor) {
4952 CXXMethodDecl *Decl = SMOR->getMethod();
4953 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4954
4955 int DiagKind = -1;
4956
4957 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4958 DiagKind = !Decl ? 0 : 1;
4959 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4960 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004961 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004962 DiagKind = 3;
4963 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4964 !Decl->isTrivial()) {
4965 // A member of a union must have a trivial corresponding special member.
4966 // As a weird special case, a destructor call from a union's constructor
4967 // must be accessible and non-deleted, but need not be trivial. Such a
4968 // destructor is never actually called, but is semantically checked as
4969 // if it were.
4970 DiagKind = 4;
4971 }
4972
4973 if (DiagKind == -1)
4974 return false;
4975
4976 if (Diagnose) {
4977 if (Field) {
4978 S.Diag(Field->getLocation(),
4979 diag::note_deleted_special_member_class_subobject)
4980 << CSM << MD->getParent() << /*IsField*/true
4981 << Field << DiagKind << IsDtorCallInCtor;
4982 } else {
4983 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4984 S.Diag(Base->getLocStart(),
4985 diag::note_deleted_special_member_class_subobject)
4986 << CSM << MD->getParent() << /*IsField*/false
4987 << Base->getType() << DiagKind << IsDtorCallInCtor;
4988 }
4989
4990 if (DiagKind == 1)
4991 S.NoteDeletedFunction(Decl);
4992 // FIXME: Explain inaccessibility if DiagKind == 3.
4993 }
4994
4995 return true;
4996}
4997
Richard Smith9a561d52012-02-26 09:11:52 +00004998/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004999/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00005000bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00005001 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00005002 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00005003
5004 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00005005 // -- any direct or virtual base class, or non-static data member with no
5006 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00005007 // either M has no default constructor or overload resolution as applied
5008 // to M's default constructor results in an ambiguity or in a function
5009 // that is deleted or inaccessible
5010 // C++11 [class.copy]p11, C++11 [class.copy]p23:
5011 // -- a direct or virtual base class B that cannot be copied/moved because
5012 // overload resolution, as applied to B's corresponding special member,
5013 // results in an ambiguity or a function that is deleted or inaccessible
5014 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00005015 // C++11 [class.dtor]p5:
5016 // -- any direct or virtual base class [...] has a type with a destructor
5017 // that is deleted or inaccessible
5018 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00005019 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00005020 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00005021 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005022
Richard Smith6c4c36c2012-03-30 20:53:28 +00005023 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5024 // -- any direct or virtual base class or non-static data member has a
5025 // type with a destructor that is deleted or inaccessible
5026 if (IsConstructor) {
5027 Sema::SpecialMemberOverloadResult *SMOR =
5028 S.LookupSpecialMember(Class, Sema::CXXDestructor,
5029 false, false, false, false, false);
5030 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5031 return true;
5032 }
5033
Richard Smith9a561d52012-02-26 09:11:52 +00005034 return false;
5035}
5036
5037/// Check whether we should delete a special member function due to the class
5038/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005039bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00005040 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00005041 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00005042}
5043
5044/// Check whether we should delete a special member function due to the class
5045/// having a particular non-static data member.
5046bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5047 QualType FieldType = S.Context.getBaseElementType(FD->getType());
5048 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5049
5050 if (CSM == Sema::CXXDefaultConstructor) {
5051 // For a default constructor, all references must be initialized in-class
5052 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005053 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5054 if (Diagnose)
5055 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5056 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005057 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005058 }
Richard Smith79363f52012-02-27 06:07:25 +00005059 // C++11 [class.ctor]p5: any non-variant non-static data member of
5060 // const-qualified type (or array thereof) with no
5061 // brace-or-equal-initializer does not have a user-provided default
5062 // constructor.
5063 if (!inUnion() && FieldType.isConstQualified() &&
5064 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005065 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5066 if (Diagnose)
5067 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005068 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00005069 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005070 }
5071
5072 if (inUnion() && !FieldType.isConstQualified())
5073 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005074 } else if (CSM == Sema::CXXCopyConstructor) {
5075 // For a copy constructor, data members must not be of rvalue reference
5076 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005077 if (FieldType->isRValueReferenceType()) {
5078 if (Diagnose)
5079 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5080 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00005081 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005082 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005083 } else if (IsAssignment) {
5084 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005085 if (FieldType->isReferenceType()) {
5086 if (Diagnose)
5087 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5088 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00005089 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005090 }
5091 if (!FieldRecord && FieldType.isConstQualified()) {
5092 // C++11 [class.copy]p23:
5093 // -- a non-static data member of const non-class type (or array thereof)
5094 if (Diagnose)
5095 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00005096 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005097 return true;
5098 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005099 }
5100
5101 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00005102 // Some additional restrictions exist on the variant members.
5103 if (!inUnion() && FieldRecord->isUnion() &&
5104 FieldRecord->isAnonymousStructOrUnion()) {
5105 bool AllVariantFieldsAreConst = true;
5106
Richard Smithdf8dc862012-03-29 19:00:10 +00005107 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00005108 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5109 UE = FieldRecord->field_end();
5110 UI != UE; ++UI) {
5111 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00005112
5113 if (!UnionFieldType.isConstQualified())
5114 AllVariantFieldsAreConst = false;
5115
Richard Smith9a561d52012-02-26 09:11:52 +00005116 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5117 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00005118 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5119 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00005120 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005121 }
5122
5123 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00005124 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005125 FieldRecord->field_begin() != FieldRecord->field_end()) {
5126 if (Diagnose)
5127 S.Diag(FieldRecord->getLocation(),
5128 diag::note_deleted_default_ctor_all_const)
5129 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00005130 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005131 }
Richard Smith7d5088a2012-02-18 02:02:13 +00005132
Richard Smithdf8dc862012-03-29 19:00:10 +00005133 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00005134 // This is technically non-conformant, but sanity demands it.
5135 return false;
5136 }
5137
Richard Smith517bb842012-07-18 03:51:16 +00005138 if (shouldDeleteForClassSubobject(FieldRecord, FD,
5139 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00005140 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00005141 }
5142
5143 return false;
5144}
5145
5146/// C++11 [class.ctor] p5:
5147/// A defaulted default constructor for a class X is defined as deleted if
5148/// X is a union and all of its variant members are of const-qualified type.
5149bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00005150 // This is a silly definition, because it gives an empty union a deleted
5151 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005152 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5153 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5154 if (Diagnose)
5155 S.Diag(MD->getParent()->getLocation(),
5156 diag::note_deleted_default_ctor_all_const)
5157 << MD->getParent() << /*not anonymous union*/0;
5158 return true;
5159 }
5160 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00005161}
5162
5163/// Determine whether a defaulted special member function should be defined as
5164/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5165/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00005166bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5167 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00005168 if (MD->isInvalidDecl())
5169 return false;
Sean Hunte16da072011-10-10 06:18:57 +00005170 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00005171 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00005172 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005173 return false;
5174
Richard Smith7d5088a2012-02-18 02:02:13 +00005175 // C++11 [expr.lambda.prim]p19:
5176 // The closure type associated with a lambda-expression has a
5177 // deleted (8.4.3) default constructor and a deleted copy
5178 // assignment operator.
5179 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005180 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5181 if (Diagnose)
5182 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00005183 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005184 }
5185
Richard Smith5bdaac52012-04-02 20:59:25 +00005186 // For an anonymous struct or union, the copy and assignment special members
5187 // will never be used, so skip the check. For an anonymous union declared at
5188 // namespace scope, the constructor and destructor are used.
5189 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5190 RD->isAnonymousStructOrUnion())
5191 return false;
5192
Richard Smith6c4c36c2012-03-30 20:53:28 +00005193 // C++11 [class.copy]p7, p18:
5194 // If the class definition declares a move constructor or move assignment
5195 // operator, an implicitly declared copy constructor or copy assignment
5196 // operator is defined as deleted.
5197 if (MD->isImplicit() &&
5198 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5199 CXXMethodDecl *UserDeclaredMove = 0;
5200
5201 // In Microsoft mode, a user-declared move only causes the deletion of the
5202 // corresponding copy operation, not both copy operations.
5203 if (RD->hasUserDeclaredMoveConstructor() &&
5204 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5205 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005206
5207 // Find any user-declared move constructor.
5208 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5209 E = RD->ctor_end(); I != E; ++I) {
5210 if (I->isMoveConstructor()) {
5211 UserDeclaredMove = *I;
5212 break;
5213 }
5214 }
Richard Smith1c931be2012-04-02 18:40:40 +00005215 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005216 } else if (RD->hasUserDeclaredMoveAssignment() &&
5217 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5218 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005219
5220 // Find any user-declared move assignment operator.
5221 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5222 E = RD->method_end(); I != E; ++I) {
5223 if (I->isMoveAssignmentOperator()) {
5224 UserDeclaredMove = *I;
5225 break;
5226 }
5227 }
Richard Smith1c931be2012-04-02 18:40:40 +00005228 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005229 }
5230
5231 if (UserDeclaredMove) {
5232 Diag(UserDeclaredMove->getLocation(),
5233 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005234 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005235 << UserDeclaredMove->isMoveAssignmentOperator();
5236 return true;
5237 }
5238 }
Sean Hunte16da072011-10-10 06:18:57 +00005239
Richard Smith5bdaac52012-04-02 20:59:25 +00005240 // Do access control from the special member function
5241 ContextRAII MethodContext(*this, MD);
5242
Richard Smith9a561d52012-02-26 09:11:52 +00005243 // C++11 [class.dtor]p5:
5244 // -- for a virtual destructor, lookup of the non-array deallocation function
5245 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005246 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005247 FunctionDecl *OperatorDelete = 0;
5248 DeclarationName Name =
5249 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5250 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005251 OperatorDelete, false)) {
5252 if (Diagnose)
5253 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005254 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005255 }
Richard Smith9a561d52012-02-26 09:11:52 +00005256 }
5257
Richard Smith6c4c36c2012-03-30 20:53:28 +00005258 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005259
Sean Huntcdee3fe2011-05-11 22:34:38 +00005260 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005261 BE = RD->bases_end(); BI != BE; ++BI)
5262 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005263 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005264 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005265
Richard Smithe0883602013-07-22 18:06:23 +00005266 // Per DR1611, do not consider virtual bases of constructors of abstract
5267 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005268 if (!RD->isAbstract() || !SMI.IsConstructor) {
5269 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5270 BE = RD->vbases_end();
5271 BI != BE; ++BI)
5272 if (SMI.shouldDeleteForBase(BI))
5273 return true;
5274 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005275
5276 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005277 FE = RD->field_end(); FI != FE; ++FI)
5278 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005279 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005280 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005281
Richard Smith7d5088a2012-02-18 02:02:13 +00005282 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005283 return true;
5284
5285 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005286}
5287
Richard Smithac713512012-12-08 02:53:02 +00005288/// Perform lookup for a special member of the specified kind, and determine
5289/// whether it is trivial. If the triviality can be determined without the
5290/// lookup, skip it. This is intended for use when determining whether a
5291/// special member of a containing object is trivial, and thus does not ever
5292/// perform overload resolution for default constructors.
5293///
5294/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5295/// member that was most likely to be intended to be trivial, if any.
5296static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5297 Sema::CXXSpecialMember CSM, unsigned Quals,
5298 CXXMethodDecl **Selected) {
5299 if (Selected)
5300 *Selected = 0;
5301
5302 switch (CSM) {
5303 case Sema::CXXInvalid:
5304 llvm_unreachable("not a special member");
5305
5306 case Sema::CXXDefaultConstructor:
5307 // C++11 [class.ctor]p5:
5308 // A default constructor is trivial if:
5309 // - all the [direct subobjects] have trivial default constructors
5310 //
5311 // Note, no overload resolution is performed in this case.
5312 if (RD->hasTrivialDefaultConstructor())
5313 return true;
5314
5315 if (Selected) {
5316 // If there's a default constructor which could have been trivial, dig it
5317 // out. Otherwise, if there's any user-provided default constructor, point
5318 // to that as an example of why there's not a trivial one.
5319 CXXConstructorDecl *DefCtor = 0;
5320 if (RD->needsImplicitDefaultConstructor())
5321 S.DeclareImplicitDefaultConstructor(RD);
5322 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5323 CE = RD->ctor_end(); CI != CE; ++CI) {
5324 if (!CI->isDefaultConstructor())
5325 continue;
5326 DefCtor = *CI;
5327 if (!DefCtor->isUserProvided())
5328 break;
5329 }
5330
5331 *Selected = DefCtor;
5332 }
5333
5334 return false;
5335
5336 case Sema::CXXDestructor:
5337 // C++11 [class.dtor]p5:
5338 // A destructor is trivial if:
5339 // - all the direct [subobjects] have trivial destructors
5340 if (RD->hasTrivialDestructor())
5341 return true;
5342
5343 if (Selected) {
5344 if (RD->needsImplicitDestructor())
5345 S.DeclareImplicitDestructor(RD);
5346 *Selected = RD->getDestructor();
5347 }
5348
5349 return false;
5350
5351 case Sema::CXXCopyConstructor:
5352 // C++11 [class.copy]p12:
5353 // A copy constructor is trivial if:
5354 // - the constructor selected to copy each direct [subobject] is trivial
5355 if (RD->hasTrivialCopyConstructor()) {
5356 if (Quals == Qualifiers::Const)
5357 // We must either select the trivial copy constructor or reach an
5358 // ambiguity; no need to actually perform overload resolution.
5359 return true;
5360 } else if (!Selected) {
5361 return false;
5362 }
5363 // In C++98, we are not supposed to perform overload resolution here, but we
5364 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5365 // cases like B as having a non-trivial copy constructor:
5366 // struct A { template<typename T> A(T&); };
5367 // struct B { mutable A a; };
5368 goto NeedOverloadResolution;
5369
5370 case Sema::CXXCopyAssignment:
5371 // C++11 [class.copy]p25:
5372 // A copy assignment operator is trivial if:
5373 // - the assignment operator selected to copy each direct [subobject] is
5374 // trivial
5375 if (RD->hasTrivialCopyAssignment()) {
5376 if (Quals == Qualifiers::Const)
5377 return true;
5378 } else if (!Selected) {
5379 return false;
5380 }
5381 // In C++98, we are not supposed to perform overload resolution here, but we
5382 // treat that as a language defect.
5383 goto NeedOverloadResolution;
5384
5385 case Sema::CXXMoveConstructor:
5386 case Sema::CXXMoveAssignment:
5387 NeedOverloadResolution:
5388 Sema::SpecialMemberOverloadResult *SMOR =
5389 S.LookupSpecialMember(RD, CSM,
5390 Quals & Qualifiers::Const,
5391 Quals & Qualifiers::Volatile,
5392 /*RValueThis*/false, /*ConstThis*/false,
5393 /*VolatileThis*/false);
5394
5395 // The standard doesn't describe how to behave if the lookup is ambiguous.
5396 // We treat it as not making the member non-trivial, just like the standard
5397 // mandates for the default constructor. This should rarely matter, because
5398 // the member will also be deleted.
5399 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5400 return true;
5401
5402 if (!SMOR->getMethod()) {
5403 assert(SMOR->getKind() ==
5404 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5405 return false;
5406 }
5407
5408 // We deliberately don't check if we found a deleted special member. We're
5409 // not supposed to!
5410 if (Selected)
5411 *Selected = SMOR->getMethod();
5412 return SMOR->getMethod()->isTrivial();
5413 }
5414
5415 llvm_unreachable("unknown special method kind");
5416}
5417
Benjamin Kramera574c892013-02-15 12:30:38 +00005418static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005419 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5420 CI != CE; ++CI)
5421 if (!CI->isImplicit())
5422 return *CI;
5423
5424 // Look for constructor templates.
5425 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5426 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5427 if (CXXConstructorDecl *CD =
5428 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5429 return CD;
5430 }
5431
5432 return 0;
5433}
5434
5435/// The kind of subobject we are checking for triviality. The values of this
5436/// enumeration are used in diagnostics.
5437enum TrivialSubobjectKind {
5438 /// The subobject is a base class.
5439 TSK_BaseClass,
5440 /// The subobject is a non-static data member.
5441 TSK_Field,
5442 /// The object is actually the complete object.
5443 TSK_CompleteObject
5444};
5445
5446/// Check whether the special member selected for a given type would be trivial.
5447static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5448 QualType SubType,
5449 Sema::CXXSpecialMember CSM,
5450 TrivialSubobjectKind Kind,
5451 bool Diagnose) {
5452 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5453 if (!SubRD)
5454 return true;
5455
5456 CXXMethodDecl *Selected;
5457 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5458 Diagnose ? &Selected : 0))
5459 return true;
5460
5461 if (Diagnose) {
5462 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5463 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5464 << Kind << SubType.getUnqualifiedType();
5465 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5466 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5467 } else if (!Selected)
5468 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5469 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5470 else if (Selected->isUserProvided()) {
5471 if (Kind == TSK_CompleteObject)
5472 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5473 << Kind << SubType.getUnqualifiedType() << CSM;
5474 else {
5475 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5476 << Kind << SubType.getUnqualifiedType() << CSM;
5477 S.Diag(Selected->getLocation(), diag::note_declared_at);
5478 }
5479 } else {
5480 if (Kind != TSK_CompleteObject)
5481 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5482 << Kind << SubType.getUnqualifiedType() << CSM;
5483
5484 // Explain why the defaulted or deleted special member isn't trivial.
5485 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5486 }
5487 }
5488
5489 return false;
5490}
5491
5492/// Check whether the members of a class type allow a special member to be
5493/// trivial.
5494static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5495 Sema::CXXSpecialMember CSM,
5496 bool ConstArg, bool Diagnose) {
5497 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5498 FE = RD->field_end(); FI != FE; ++FI) {
5499 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5500 continue;
5501
5502 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5503
5504 // Pretend anonymous struct or union members are members of this class.
5505 if (FI->isAnonymousStructOrUnion()) {
5506 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5507 CSM, ConstArg, Diagnose))
5508 return false;
5509 continue;
5510 }
5511
5512 // C++11 [class.ctor]p5:
5513 // A default constructor is trivial if [...]
5514 // -- no non-static data member of its class has a
5515 // brace-or-equal-initializer
5516 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5517 if (Diagnose)
5518 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5519 return false;
5520 }
5521
5522 // Objective C ARC 4.3.5:
5523 // [...] nontrivally ownership-qualified types are [...] not trivially
5524 // default constructible, copy constructible, move constructible, copy
5525 // assignable, move assignable, or destructible [...]
5526 if (S.getLangOpts().ObjCAutoRefCount &&
5527 FieldType.hasNonTrivialObjCLifetime()) {
5528 if (Diagnose)
5529 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5530 << RD << FieldType.getObjCLifetime();
5531 return false;
5532 }
5533
5534 if (ConstArg && !FI->isMutable())
5535 FieldType.addConst();
5536 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5537 TSK_Field, Diagnose))
5538 return false;
5539 }
5540
5541 return true;
5542}
5543
5544/// Diagnose why the specified class does not have a trivial special member of
5545/// the given kind.
5546void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5547 QualType Ty = Context.getRecordType(RD);
5548 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5549 Ty.addConst();
5550
5551 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5552 TSK_CompleteObject, /*Diagnose*/true);
5553}
5554
5555/// Determine whether a defaulted or deleted special member function is trivial,
5556/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5557/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5558bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5559 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005560 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5561
5562 CXXRecordDecl *RD = MD->getParent();
5563
5564 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005565
5566 // C++11 [class.copy]p12, p25:
5567 // A [special member] is trivial if its declared parameter type is the same
5568 // as if it had been implicitly declared [...]
5569 switch (CSM) {
5570 case CXXDefaultConstructor:
5571 case CXXDestructor:
5572 // Trivial default constructors and destructors cannot have parameters.
5573 break;
5574
5575 case CXXCopyConstructor:
5576 case CXXCopyAssignment: {
5577 // Trivial copy operations always have const, non-volatile parameter types.
5578 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005579 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005580 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5581 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5582 if (Diagnose)
5583 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5584 << Param0->getSourceRange() << Param0->getType()
5585 << Context.getLValueReferenceType(
5586 Context.getRecordType(RD).withConst());
5587 return false;
5588 }
5589 break;
5590 }
5591
5592 case CXXMoveConstructor:
5593 case CXXMoveAssignment: {
5594 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005595 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005596 const RValueReferenceType *RT =
5597 Param0->getType()->getAs<RValueReferenceType>();
5598 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5599 if (Diagnose)
5600 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5601 << Param0->getSourceRange() << Param0->getType()
5602 << Context.getRValueReferenceType(Context.getRecordType(RD));
5603 return false;
5604 }
5605 break;
5606 }
5607
5608 case CXXInvalid:
5609 llvm_unreachable("not a special member");
5610 }
5611
5612 // FIXME: We require that the parameter-declaration-clause is equivalent to
5613 // that of an implicit declaration, not just that the declared parameter type
5614 // matches, in order to prevent absuridities like a function simultaneously
5615 // being a trivial copy constructor and a non-trivial default constructor.
5616 // This issue has not yet been assigned a core issue number.
5617 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5618 if (Diagnose)
5619 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5620 diag::note_nontrivial_default_arg)
5621 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5622 return false;
5623 }
5624 if (MD->isVariadic()) {
5625 if (Diagnose)
5626 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5627 return false;
5628 }
5629
5630 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5631 // A copy/move [constructor or assignment operator] is trivial if
5632 // -- the [member] selected to copy/move each direct base class subobject
5633 // is trivial
5634 //
5635 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5636 // A [default constructor or destructor] is trivial if
5637 // -- all the direct base classes have trivial [default constructors or
5638 // destructors]
5639 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5640 BE = RD->bases_end(); BI != BE; ++BI)
5641 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5642 ConstArg ? BI->getType().withConst()
5643 : BI->getType(),
5644 CSM, TSK_BaseClass, Diagnose))
5645 return false;
5646
5647 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5648 // A copy/move [constructor or assignment operator] for a class X is
5649 // trivial if
5650 // -- for each non-static data member of X that is of class type (or array
5651 // thereof), the constructor selected to copy/move that member is
5652 // trivial
5653 //
5654 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5655 // A [default constructor or destructor] is trivial if
5656 // -- for all of the non-static data members of its class that are of class
5657 // type (or array thereof), each such class has a trivial [default
5658 // constructor or destructor]
5659 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5660 return false;
5661
5662 // C++11 [class.dtor]p5:
5663 // A destructor is trivial if [...]
5664 // -- the destructor is not virtual
5665 if (CSM == CXXDestructor && MD->isVirtual()) {
5666 if (Diagnose)
5667 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5668 return false;
5669 }
5670
5671 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5672 // A [special member] for class X is trivial if [...]
5673 // -- class X has no virtual functions and no virtual base classes
5674 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5675 if (!Diagnose)
5676 return false;
5677
5678 if (RD->getNumVBases()) {
5679 // Check for virtual bases. We already know that the corresponding
5680 // member in all bases is trivial, so vbases must all be direct.
5681 CXXBaseSpecifier &BS = *RD->vbases_begin();
5682 assert(BS.isVirtual());
5683 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5684 return false;
5685 }
5686
5687 // Must have a virtual method.
5688 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5689 ME = RD->method_end(); MI != ME; ++MI) {
5690 if (MI->isVirtual()) {
5691 SourceLocation MLoc = MI->getLocStart();
5692 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5693 return false;
5694 }
5695 }
5696
5697 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5698 }
5699
5700 // Looks like it's trivial!
5701 return true;
5702}
5703
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005704/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005705namespace {
5706 struct FindHiddenVirtualMethodData {
5707 Sema *S;
5708 CXXMethodDecl *Method;
5709 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005710 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005711 };
5712}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005713
David Blaikie5f750682012-10-19 00:53:08 +00005714/// \brief Check whether any most overriden method from MD in Methods
5715static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5716 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5717 if (MD->size_overridden_methods() == 0)
5718 return Methods.count(MD->getCanonicalDecl());
5719 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5720 E = MD->end_overridden_methods();
5721 I != E; ++I)
5722 if (CheckMostOverridenMethods(*I, Methods))
5723 return true;
5724 return false;
5725}
5726
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005727/// \brief Member lookup function that determines whether a given C++
5728/// method overloads virtual methods in a base class without overriding any,
5729/// to be used with CXXRecordDecl::lookupInBases().
5730static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5731 CXXBasePath &Path,
5732 void *UserData) {
5733 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5734
5735 FindHiddenVirtualMethodData &Data
5736 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5737
5738 DeclarationName Name = Data.Method->getDeclName();
5739 assert(Name.getNameKind() == DeclarationName::Identifier);
5740
5741 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005742 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005743 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005744 !Path.Decls.empty();
5745 Path.Decls = Path.Decls.slice(1)) {
5746 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005747 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005748 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005749 foundSameNameMethod = true;
5750 // Interested only in hidden virtual methods.
5751 if (!MD->isVirtual())
5752 continue;
5753 // If the method we are checking overrides a method from its base
5754 // don't warn about the other overloaded methods.
5755 if (!Data.S->IsOverload(Data.Method, MD, false))
5756 return true;
5757 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005758 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005759 overloadedMethods.push_back(MD);
5760 }
5761 }
5762
5763 if (foundSameNameMethod)
5764 Data.OverloadedMethods.append(overloadedMethods.begin(),
5765 overloadedMethods.end());
5766 return foundSameNameMethod;
5767}
5768
David Blaikie5f750682012-10-19 00:53:08 +00005769/// \brief Add the most overriden methods from MD to Methods
5770static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5771 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5772 if (MD->size_overridden_methods() == 0)
5773 Methods.insert(MD->getCanonicalDecl());
5774 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5775 E = MD->end_overridden_methods();
5776 I != E; ++I)
5777 AddMostOverridenMethods(*I, Methods);
5778}
5779
Eli Friedmandae92712013-09-05 23:51:03 +00005780/// \brief Check if a method overloads virtual methods in a base class without
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005781/// overriding any.
Eli Friedmandae92712013-09-05 23:51:03 +00005782void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5783 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
Benjamin Kramerc4704422012-05-19 16:03:58 +00005784 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005785 return;
5786
5787 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5788 /*bool RecordPaths=*/false,
5789 /*bool DetectVirtual=*/false);
5790 FindHiddenVirtualMethodData Data;
5791 Data.Method = MD;
5792 Data.S = this;
5793
5794 // Keep the base methods that were overriden or introduced in the subclass
5795 // by 'using' in a set. A base method not in this set is hidden.
Eli Friedmandae92712013-09-05 23:51:03 +00005796 CXXRecordDecl *DC = MD->getParent();
David Blaikie3bc93e32012-12-19 00:45:41 +00005797 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5798 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5799 NamedDecl *ND = *I;
5800 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005801 ND = shad->getTargetDecl();
5802 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5803 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005804 }
5805
Eli Friedmandae92712013-09-05 23:51:03 +00005806 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5807 OverloadedMethods = Data.OverloadedMethods;
5808}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005809
Eli Friedmandae92712013-09-05 23:51:03 +00005810void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5811 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5812 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5813 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5814 PartialDiagnostic PD = PDiag(
5815 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5816 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5817 Diag(overloadedMD->getLocation(), PD);
5818 }
5819}
5820
5821/// \brief Diagnose methods which overload virtual methods in a base class
5822/// without overriding any.
5823void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5824 if (MD->isInvalidDecl())
5825 return;
5826
5827 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5828 MD->getLocation()) == DiagnosticsEngine::Ignored)
5829 return;
5830
5831 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5832 FindHiddenVirtualMethods(MD, OverloadedMethods);
5833 if (!OverloadedMethods.empty()) {
5834 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5835 << MD << (OverloadedMethods.size() > 1);
5836
5837 NoteHiddenVirtualMethods(MD, OverloadedMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005838 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005839}
5840
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005841void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005842 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005843 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005844 SourceLocation RBrac,
5845 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005846 if (!TagDecl)
5847 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005848
Douglas Gregor42af25f2009-05-11 19:58:34 +00005849 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005850
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005851 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5852 if (l->getKind() != AttributeList::AT_Visibility)
5853 continue;
5854 l->setInvalid();
5855 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5856 l->getName();
5857 }
5858
David Blaikie77b6de02011-09-22 02:58:26 +00005859 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005860 // strict aliasing violation!
5861 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005862 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005863
Douglas Gregor23c94db2010-07-02 17:43:08 +00005864 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005865 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005866}
5867
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005868/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5869/// special functions, such as the default constructor, copy
5870/// constructor, or destructor, to the given C++ class (C++
5871/// [special]p1). This routine can only be executed just before the
5872/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005873void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005874 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005875 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005876
Richard Smithbc2a35d2012-12-08 08:32:28 +00005877 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005878 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005879
Richard Smithbc2a35d2012-12-08 08:32:28 +00005880 // If the properties or semantics of the copy constructor couldn't be
5881 // determined while the class was being declared, force a declaration
5882 // of it now.
5883 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5884 DeclareImplicitCopyConstructor(ClassDecl);
5885 }
5886
Richard Smith80ad52f2013-01-02 11:42:31 +00005887 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005888 ++ASTContext::NumImplicitMoveConstructors;
5889
Richard Smithbc2a35d2012-12-08 08:32:28 +00005890 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5891 DeclareImplicitMoveConstructor(ClassDecl);
5892 }
5893
Douglas Gregora376d102010-07-02 21:50:04 +00005894 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5895 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005896
5897 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005898 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005899 // it shows up in the right place in the vtable and that we diagnose
5900 // problems with the implicit exception specification.
5901 if (ClassDecl->isDynamicClass() ||
5902 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005903 DeclareImplicitCopyAssignment(ClassDecl);
5904 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005905
Richard Smith80ad52f2013-01-02 11:42:31 +00005906 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005907 ++ASTContext::NumImplicitMoveAssignmentOperators;
5908
5909 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005910 if (ClassDecl->isDynamicClass() ||
5911 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005912 DeclareImplicitMoveAssignment(ClassDecl);
5913 }
5914
Douglas Gregor4923aa22010-07-02 20:37:36 +00005915 if (!ClassDecl->hasUserDeclaredDestructor()) {
5916 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005917
5918 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005919 // have to declare the destructor immediately. This ensures that, e.g., it
5920 // shows up in the right place in the vtable and that we diagnose problems
5921 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005922 if (ClassDecl->isDynamicClass() ||
5923 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005924 DeclareImplicitDestructor(ClassDecl);
5925 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005926}
5927
Francois Pichet8387e2a2011-04-22 22:18:13 +00005928void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5929 if (!D)
5930 return;
5931
5932 int NumParamList = D->getNumTemplateParameterLists();
5933 for (int i = 0; i < NumParamList; i++) {
5934 TemplateParameterList* Params = D->getTemplateParameterList(i);
5935 for (TemplateParameterList::iterator Param = Params->begin(),
5936 ParamEnd = Params->end();
5937 Param != ParamEnd; ++Param) {
5938 NamedDecl *Named = cast<NamedDecl>(*Param);
5939 if (Named->getDeclName()) {
5940 S->AddDecl(Named);
5941 IdResolver.AddDecl(Named);
5942 }
5943 }
5944 }
5945}
5946
John McCalld226f652010-08-21 09:40:31 +00005947void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005948 if (!D)
5949 return;
5950
5951 TemplateParameterList *Params = 0;
5952 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5953 Params = Template->getTemplateParameters();
5954 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5955 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5956 Params = PartialSpec->getTemplateParameters();
5957 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005958 return;
5959
Douglas Gregor6569d682009-05-27 23:11:45 +00005960 for (TemplateParameterList::iterator Param = Params->begin(),
5961 ParamEnd = Params->end();
5962 Param != ParamEnd; ++Param) {
5963 NamedDecl *Named = cast<NamedDecl>(*Param);
5964 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005965 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005966 IdResolver.AddDecl(Named);
5967 }
5968 }
5969}
5970
John McCalld226f652010-08-21 09:40:31 +00005971void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005972 if (!RecordD) return;
5973 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005974 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005975 PushDeclContext(S, Record);
5976}
5977
John McCalld226f652010-08-21 09:40:31 +00005978void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005979 if (!RecordD) return;
5980 PopDeclContext();
5981}
5982
Douglas Gregor72b505b2008-12-16 21:30:33 +00005983/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5984/// parsing a top-level (non-nested) C++ class, and we are now
5985/// parsing those parts of the given Method declaration that could
5986/// not be parsed earlier (C++ [class.mem]p2), such as default
5987/// arguments. This action should enter the scope of the given
5988/// Method declaration as if we had just parsed the qualified method
5989/// name. However, it should not bring the parameters into scope;
5990/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005991void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005992}
5993
5994/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5995/// C++ method declaration. We're (re-)introducing the given
5996/// function parameter into scope for use in parsing later parts of
5997/// the method declaration. For example, we could see an
5998/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005999void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006000 if (!ParamD)
6001 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006002
John McCalld226f652010-08-21 09:40:31 +00006003 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00006004
6005 // If this parameter has an unparsed default argument, clear it out
6006 // to make way for the parsed default argument.
6007 if (Param->hasUnparsedDefaultArg())
6008 Param->setDefaultArg(0);
6009
John McCalld226f652010-08-21 09:40:31 +00006010 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006011 if (Param->getDeclName())
6012 IdResolver.AddDecl(Param);
6013}
6014
6015/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6016/// processing the delayed method declaration for Method. The method
6017/// declaration is now considered finished. There may be a separate
6018/// ActOnStartOfFunctionDef action later (not necessarily
6019/// immediately!) for this method, if it was also defined inside the
6020/// class body.
John McCalld226f652010-08-21 09:40:31 +00006021void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00006022 if (!MethodD)
6023 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006024
Douglas Gregorefd5bda2009-08-24 11:57:43 +00006025 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00006026
John McCalld226f652010-08-21 09:40:31 +00006027 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006028
6029 // Now that we have our default arguments, check the constructor
6030 // again. It could produce additional diagnostics or affect whether
6031 // the class has implicitly-declared destructors, among other
6032 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00006033 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6034 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00006035
6036 // Check the default arguments, which we may have added.
6037 if (!Method->isInvalidDecl())
6038 CheckCXXDefaultArguments(Method);
6039}
6040
Douglas Gregor42a552f2008-11-05 20:51:48 +00006041/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00006042/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00006043/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006044/// emit diagnostics and set the invalid bit to true. In any case, the type
6045/// will be updated to reflect a well-formed type for the constructor and
6046/// returned.
6047QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006048 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006049 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006050
6051 // C++ [class.ctor]p3:
6052 // A constructor shall not be virtual (10.3) or static (9.4). A
6053 // constructor can be invoked for a const, volatile or const
6054 // volatile object. A constructor shall not be declared const,
6055 // volatile, or const volatile (9.3.2).
6056 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00006057 if (!D.isInvalidType())
6058 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6059 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6060 << SourceRange(D.getIdentifierLoc());
6061 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006062 }
John McCalld931b082010-08-26 03:08:43 +00006063 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006064 if (!D.isInvalidType())
6065 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6066 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6067 << SourceRange(D.getIdentifierLoc());
6068 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006069 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006070 }
Mike Stump1eb44332009-09-09 15:08:12 +00006071
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006072 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006073 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00006074 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006075 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6076 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006077 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006078 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6079 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006080 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006081 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6082 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00006083 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006084 }
Mike Stump1eb44332009-09-09 15:08:12 +00006085
Douglas Gregorc938c162011-01-26 05:01:58 +00006086 // C++0x [class.ctor]p4:
6087 // A constructor shall not be declared with a ref-qualifier.
6088 if (FTI.hasRefQualifier()) {
6089 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6090 << FTI.RefQualifierIsLValueRef
6091 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6092 D.setInvalidType();
6093 }
6094
Douglas Gregor42a552f2008-11-05 20:51:48 +00006095 // Rebuild the function type "R" without any type qualifiers (in
6096 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00006097 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00006098 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006099 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6100 return R;
6101
6102 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6103 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006104 EPI.RefQualifier = RQ_None;
6105
Richard Smith07b0fdc2013-03-18 21:12:30 +00006106 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006107}
6108
Douglas Gregor72b505b2008-12-16 21:30:33 +00006109/// CheckConstructor - Checks a fully-formed constructor for
6110/// well-formedness, issuing any diagnostics required. Returns true if
6111/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00006112void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00006113 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00006114 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6115 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00006116 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006117
6118 // C++ [class.copy]p3:
6119 // A declaration of a constructor for a class X is ill-formed if
6120 // its first parameter is of type (optionally cv-qualified) X and
6121 // either there are no other parameters or else all other
6122 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00006123 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00006124 ((Constructor->getNumParams() == 1) ||
6125 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00006126 Constructor->getParamDecl(1)->hasDefaultArg())) &&
6127 Constructor->getTemplateSpecializationKind()
6128 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00006129 QualType ParamType = Constructor->getParamDecl(0)->getType();
6130 QualType ClassTy = Context.getTagDeclType(ClassDecl);
6131 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00006132 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006133 const char *ConstRef
6134 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6135 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00006136 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00006137 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00006138
6139 // FIXME: Rather that making the constructor invalid, we should endeavor
6140 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00006141 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00006142 }
6143 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00006144}
6145
John McCall15442822010-08-04 01:04:25 +00006146/// CheckDestructor - Checks a fully-formed destructor definition for
6147/// well-formedness, issuing any diagnostics required. Returns true
6148/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006149bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006150 CXXRecordDecl *RD = Destructor->getParent();
6151
Peter Collingbournef51cfb82013-05-20 14:12:25 +00006152 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00006153 SourceLocation Loc;
6154
6155 if (!Destructor->isImplicit())
6156 Loc = Destructor->getLocation();
6157 else
6158 Loc = RD->getLocation();
6159
6160 // If we have a virtual destructor, look up the deallocation function
6161 FunctionDecl *OperatorDelete = 0;
6162 DeclarationName Name =
6163 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00006164 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00006165 return true;
John McCall5efd91a2010-07-03 18:33:00 +00006166
Eli Friedman5f2987c2012-02-02 03:46:19 +00006167 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00006168
6169 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00006170 }
Anders Carlsson37909802009-11-30 21:24:50 +00006171
6172 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00006173}
6174
Mike Stump1eb44332009-09-09 15:08:12 +00006175static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006176FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6177 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6178 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00006179 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006180}
6181
Douglas Gregor42a552f2008-11-05 20:51:48 +00006182/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6183/// the well-formednes of the destructor declarator @p D with type @p
6184/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00006185/// emit diagnostics and set the declarator to invalid. Even if this happens,
6186/// will be updated to reflect a well-formed type for the destructor and
6187/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00006188QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00006189 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006190 // C++ [class.dtor]p1:
6191 // [...] A typedef-name that names a class is a class-name
6192 // (7.1.3); however, a typedef-name that names a class shall not
6193 // be used as the identifier in the declarator for a destructor
6194 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00006195 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00006196 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00006197 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00006198 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006199 else if (const TemplateSpecializationType *TST =
6200 DeclaratorType->getAs<TemplateSpecializationType>())
6201 if (TST->isTypeAlias())
6202 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6203 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006204
6205 // C++ [class.dtor]p2:
6206 // A destructor is used to destroy objects of its class type. A
6207 // destructor takes no parameters, and no return type can be
6208 // specified for it (not even void). The address of a destructor
6209 // shall not be taken. A destructor shall not be static. A
6210 // destructor can be invoked for a const, volatile or const
6211 // volatile object. A destructor shall not be declared const,
6212 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006213 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006214 if (!D.isInvalidType())
6215 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6216 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006217 << SourceRange(D.getIdentifierLoc())
6218 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6219
John McCalld931b082010-08-26 03:08:43 +00006220 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006221 }
Chris Lattner65401802009-04-25 08:28:21 +00006222 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006223 // Destructors don't have return types, but the parser will
6224 // happily parse something like:
6225 //
6226 // class X {
6227 // float ~X();
6228 // };
6229 //
6230 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006231 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6232 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6233 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006234 }
Mike Stump1eb44332009-09-09 15:08:12 +00006235
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006236 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006237 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006238 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006239 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6240 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006241 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006242 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6243 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006244 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006245 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6246 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006247 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006248 }
6249
Douglas Gregorc938c162011-01-26 05:01:58 +00006250 // C++0x [class.dtor]p2:
6251 // A destructor shall not be declared with a ref-qualifier.
6252 if (FTI.hasRefQualifier()) {
6253 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6254 << FTI.RefQualifierIsLValueRef
6255 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6256 D.setInvalidType();
6257 }
6258
Douglas Gregor42a552f2008-11-05 20:51:48 +00006259 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006260 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006261 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6262
6263 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006264 FTI.freeArgs();
6265 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006266 }
6267
Mike Stump1eb44332009-09-09 15:08:12 +00006268 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006269 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006270 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006271 D.setInvalidType();
6272 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006273
6274 // Rebuild the function type "R" without any type qualifiers or
6275 // parameters (in case any of the errors above fired) and with
6276 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006277 // types.
John McCalle23cf432010-12-14 08:05:40 +00006278 if (!D.isInvalidType())
6279 return R;
6280
Douglas Gregord92ec472010-07-01 05:10:53 +00006281 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006282 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6283 EPI.Variadic = false;
6284 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006285 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006286 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006287}
6288
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006289/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6290/// well-formednes of the conversion function declarator @p D with
6291/// type @p R. If there are any errors in the declarator, this routine
6292/// will emit diagnostics and return true. Otherwise, it will return
6293/// false. Either way, the type @p R will be updated to reflect a
6294/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006295void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006296 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006297 // C++ [class.conv.fct]p1:
6298 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006299 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006300 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006301 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006302 if (!D.isInvalidType())
6303 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006304 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6305 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006306 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006307 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006308 }
John McCalla3f81372010-04-13 00:04:31 +00006309
6310 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6311
Chris Lattner6e475012009-04-25 08:35:12 +00006312 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006313 // Conversion functions don't have return types, but the parser will
6314 // happily parse something like:
6315 //
6316 // class X {
6317 // float operator bool();
6318 // };
6319 //
6320 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006321 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6322 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6323 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006324 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006325 }
6326
John McCalla3f81372010-04-13 00:04:31 +00006327 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6328
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006329 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006330 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006331 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6332
6333 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006334 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006335 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006336 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006337 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006338 D.setInvalidType();
6339 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006340
John McCalla3f81372010-04-13 00:04:31 +00006341 // Diagnose "&operator bool()" and other such nonsense. This
6342 // is actually a gcc extension which we don't support.
6343 if (Proto->getResultType() != ConvType) {
6344 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6345 << Proto->getResultType();
6346 D.setInvalidType();
6347 ConvType = Proto->getResultType();
6348 }
6349
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006350 // C++ [class.conv.fct]p4:
6351 // The conversion-type-id shall not represent a function type nor
6352 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006353 if (ConvType->isArrayType()) {
6354 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6355 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006356 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006357 } else if (ConvType->isFunctionType()) {
6358 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6359 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006360 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006361 }
6362
6363 // Rebuild the function type "R" without any parameters (in case any
6364 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006365 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006366 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006367 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006368
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006369 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006370 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006371 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006372 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006373 diag::warn_cxx98_compat_explicit_conversion_functions :
6374 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006375 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006376}
6377
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006378/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6379/// the declaration of the given C++ conversion function. This routine
6380/// is responsible for recording the conversion function in the C++
6381/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006382Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006383 assert(Conversion && "Expected to receive a conversion function declaration");
6384
Douglas Gregor9d350972008-12-12 08:25:50 +00006385 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006386
6387 // Make sure we aren't redeclaring the conversion function.
6388 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006389
6390 // C++ [class.conv.fct]p1:
6391 // [...] A conversion function is never used to convert a
6392 // (possibly cv-qualified) object to the (possibly cv-qualified)
6393 // same object type (or a reference to it), to a (possibly
6394 // cv-qualified) base class of that type (or a reference to it),
6395 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006396 // FIXME: Suppress this warning if the conversion function ends up being a
6397 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006398 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006399 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006400 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006401 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006402 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6403 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006404 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006405 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006406 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6407 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006408 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006409 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006410 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006411 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006412 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006413 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006414 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006415 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006416 }
6417
Douglas Gregore80622f2010-09-29 04:25:11 +00006418 if (FunctionTemplateDecl *ConversionTemplate
6419 = Conversion->getDescribedFunctionTemplate())
6420 return ConversionTemplate;
6421
John McCalld226f652010-08-21 09:40:31 +00006422 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006423}
6424
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006425//===----------------------------------------------------------------------===//
6426// Namespace Handling
6427//===----------------------------------------------------------------------===//
6428
Richard Smithd1a55a62012-10-04 22:13:39 +00006429/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6430/// reopened.
6431static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6432 SourceLocation Loc,
6433 IdentifierInfo *II, bool *IsInline,
6434 NamespaceDecl *PrevNS) {
6435 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006436
Richard Smithc969e6a2012-10-05 01:46:25 +00006437 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6438 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6439 // inline namespaces, with the intention of bringing names into namespace std.
6440 //
6441 // We support this just well enough to get that case working; this is not
6442 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006443 if (*IsInline && II && II->getName().startswith("__atomic") &&
6444 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006445 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006446 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6447 NS = NS->getPreviousDecl())
6448 NS->setInline(*IsInline);
6449 // Patch up the lookup table for the containing namespace. This isn't really
6450 // correct, but it's good enough for this particular case.
6451 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6452 E = PrevNS->decls_end(); I != E; ++I)
6453 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6454 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6455 return;
6456 }
6457
6458 if (PrevNS->isInline())
6459 // The user probably just forgot the 'inline', so suggest that it
6460 // be added back.
6461 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6462 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6463 else
6464 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6465 << IsInline;
6466
6467 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6468 *IsInline = PrevNS->isInline();
6469}
John McCallea318642010-08-26 09:15:37 +00006470
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006471/// ActOnStartNamespaceDef - This is called at the start of a namespace
6472/// definition.
John McCalld226f652010-08-21 09:40:31 +00006473Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006474 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006475 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006476 SourceLocation IdentLoc,
6477 IdentifierInfo *II,
6478 SourceLocation LBrace,
6479 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006480 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6481 // For anonymous namespace, take the location of the left brace.
6482 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006483 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006484 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006485 bool IsStd = false;
6486 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006487 Scope *DeclRegionScope = NamespcScope->getParent();
6488
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006489 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006490 if (II) {
6491 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006492 // The identifier in an original-namespace-definition shall not
6493 // have been previously defined in the declarative region in
6494 // which the original-namespace-definition appears. The
6495 // identifier in an original-namespace-definition is the name of
6496 // the namespace. Subsequently in that declarative region, it is
6497 // treated as an original-namespace-name.
6498 //
6499 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006500 // look through using directives, just look for any ordinary names.
6501
6502 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006503 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6504 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006505 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006506 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6507 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6508 ++I) {
6509 if ((*I)->getIdentifierNamespace() & IDNS) {
6510 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006511 break;
6512 }
6513 }
6514
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006515 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6516
6517 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006518 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006519 if (IsInline != PrevNS->isInline())
6520 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6521 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006522 } else if (PrevDecl) {
6523 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006524 Diag(Loc, diag::err_redefinition_different_kind)
6525 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006526 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006527 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006528 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006529 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006530 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006531 // This is the first "real" definition of the namespace "std", so update
6532 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006533 PrevNS = getStdNamespace();
6534 IsStd = true;
6535 AddToKnown = !IsInline;
6536 } else {
6537 // We've seen this namespace for the first time.
6538 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006539 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006540 } else {
John McCall9aeed322009-10-01 00:25:31 +00006541 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006542
6543 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006544 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006545 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006546 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006547 } else {
6548 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006549 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006550 }
6551
Richard Smithd1a55a62012-10-04 22:13:39 +00006552 if (PrevNS && IsInline != PrevNS->isInline())
6553 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6554 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006555 }
6556
6557 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6558 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006559 if (IsInvalid)
6560 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006561
6562 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006563
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006564 // FIXME: Should we be merging attributes?
6565 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006566 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006567
6568 if (IsStd)
6569 StdNamespace = Namespc;
6570 if (AddToKnown)
6571 KnownNamespaces[Namespc] = false;
6572
6573 if (II) {
6574 PushOnScopeChains(Namespc, DeclRegionScope);
6575 } else {
6576 // Link the anonymous namespace into its parent.
6577 DeclContext *Parent = CurContext->getRedeclContext();
6578 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6579 TU->setAnonymousNamespace(Namespc);
6580 } else {
6581 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006582 }
John McCall9aeed322009-10-01 00:25:31 +00006583
Douglas Gregora4181472010-03-24 00:46:35 +00006584 CurContext->addDecl(Namespc);
6585
John McCall9aeed322009-10-01 00:25:31 +00006586 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6587 // behaves as if it were replaced by
6588 // namespace unique { /* empty body */ }
6589 // using namespace unique;
6590 // namespace unique { namespace-body }
6591 // where all occurrences of 'unique' in a translation unit are
6592 // replaced by the same identifier and this identifier differs
6593 // from all other identifiers in the entire program.
6594
6595 // We just create the namespace with an empty name and then add an
6596 // implicit using declaration, just like the standard suggests.
6597 //
6598 // CodeGen enforces the "universally unique" aspect by giving all
6599 // declarations semantically contained within an anonymous
6600 // namespace internal linkage.
6601
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006602 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006603 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006604 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006605 /* 'using' */ LBrace,
6606 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006607 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006608 /* identifier */ SourceLocation(),
6609 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006610 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006611 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006612 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006613 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006614 }
6615
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006616 ActOnDocumentableDecl(Namespc);
6617
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006618 // Although we could have an invalid decl (i.e. the namespace name is a
6619 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006620 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6621 // for the namespace has the declarations that showed up in that particular
6622 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006623 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006624 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006625}
6626
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006627/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6628/// is a namespace alias, returns the namespace it points to.
6629static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6630 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6631 return AD->getNamespace();
6632 return dyn_cast_or_null<NamespaceDecl>(D);
6633}
6634
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006635/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6636/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006637void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006638 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6639 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006640 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006641 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006642 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006643 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006644}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006645
John McCall384aff82010-08-25 07:42:41 +00006646CXXRecordDecl *Sema::getStdBadAlloc() const {
6647 return cast_or_null<CXXRecordDecl>(
6648 StdBadAlloc.get(Context.getExternalSource()));
6649}
6650
6651NamespaceDecl *Sema::getStdNamespace() const {
6652 return cast_or_null<NamespaceDecl>(
6653 StdNamespace.get(Context.getExternalSource()));
6654}
6655
Douglas Gregor66992202010-06-29 17:53:46 +00006656/// \brief Retrieve the special "std" namespace, which may require us to
6657/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006658NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006659 if (!StdNamespace) {
6660 // The "std" namespace has not yet been defined, so build one implicitly.
6661 StdNamespace = NamespaceDecl::Create(Context,
6662 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006663 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006664 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006665 &PP.getIdentifierTable().get("std"),
6666 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006667 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006668 }
6669
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006670 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006671}
6672
Sebastian Redl395e04d2012-01-17 22:49:33 +00006673bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006674 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006675 "Looking for std::initializer_list outside of C++.");
6676
6677 // We're looking for implicit instantiations of
6678 // template <typename E> class std::initializer_list.
6679
6680 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6681 return false;
6682
Sebastian Redl84760e32012-01-17 22:49:58 +00006683 ClassTemplateDecl *Template = 0;
6684 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006685
Sebastian Redl84760e32012-01-17 22:49:58 +00006686 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006687
Sebastian Redl84760e32012-01-17 22:49:58 +00006688 ClassTemplateSpecializationDecl *Specialization =
6689 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6690 if (!Specialization)
6691 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006692
Sebastian Redl84760e32012-01-17 22:49:58 +00006693 Template = Specialization->getSpecializedTemplate();
6694 Arguments = Specialization->getTemplateArgs().data();
6695 } else if (const TemplateSpecializationType *TST =
6696 Ty->getAs<TemplateSpecializationType>()) {
6697 Template = dyn_cast_or_null<ClassTemplateDecl>(
6698 TST->getTemplateName().getAsTemplateDecl());
6699 Arguments = TST->getArgs();
6700 }
6701 if (!Template)
6702 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006703
6704 if (!StdInitializerList) {
6705 // Haven't recognized std::initializer_list yet, maybe this is it.
6706 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6707 if (TemplateClass->getIdentifier() !=
6708 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006709 !getStdNamespace()->InEnclosingNamespaceSetOf(
6710 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006711 return false;
6712 // This is a template called std::initializer_list, but is it the right
6713 // template?
6714 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006715 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006716 return false;
6717 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6718 return false;
6719
6720 // It's the right template.
6721 StdInitializerList = Template;
6722 }
6723
6724 if (Template != StdInitializerList)
6725 return false;
6726
6727 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006728 if (Element)
6729 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006730 return true;
6731}
6732
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006733static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6734 NamespaceDecl *Std = S.getStdNamespace();
6735 if (!Std) {
6736 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6737 return 0;
6738 }
6739
6740 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6741 Loc, Sema::LookupOrdinaryName);
6742 if (!S.LookupQualifiedName(Result, Std)) {
6743 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6744 return 0;
6745 }
6746 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6747 if (!Template) {
6748 Result.suppressDiagnostics();
6749 // We found something weird. Complain about the first thing we found.
6750 NamedDecl *Found = *Result.begin();
6751 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6752 return 0;
6753 }
6754
6755 // We found some template called std::initializer_list. Now verify that it's
6756 // correct.
6757 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006758 if (Params->getMinRequiredArguments() != 1 ||
6759 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006760 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6761 return 0;
6762 }
6763
6764 return Template;
6765}
6766
6767QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6768 if (!StdInitializerList) {
6769 StdInitializerList = LookupStdInitializerList(*this, Loc);
6770 if (!StdInitializerList)
6771 return QualType();
6772 }
6773
6774 TemplateArgumentListInfo Args(Loc, Loc);
6775 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6776 Context.getTrivialTypeSourceInfo(Element,
6777 Loc)));
6778 return Context.getCanonicalType(
6779 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6780}
6781
Sebastian Redl98d36062012-01-17 22:50:14 +00006782bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6783 // C++ [dcl.init.list]p2:
6784 // A constructor is an initializer-list constructor if its first parameter
6785 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6786 // std::initializer_list<E> for some type E, and either there are no other
6787 // parameters or else all other parameters have default arguments.
6788 if (Ctor->getNumParams() < 1 ||
6789 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6790 return false;
6791
6792 QualType ArgType = Ctor->getParamDecl(0)->getType();
6793 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6794 ArgType = RT->getPointeeType().getUnqualifiedType();
6795
6796 return isStdInitializerList(ArgType, 0);
6797}
6798
Douglas Gregor9172aa62011-03-26 22:25:30 +00006799/// \brief Determine whether a using statement is in a context where it will be
6800/// apply in all contexts.
6801static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6802 switch (CurContext->getDeclKind()) {
6803 case Decl::TranslationUnit:
6804 return true;
6805 case Decl::LinkageSpec:
6806 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6807 default:
6808 return false;
6809 }
6810}
6811
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006812namespace {
6813
6814// Callback to only accept typo corrections that are namespaces.
6815class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006816public:
6817 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6818 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006819 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006820 return false;
6821 }
6822};
6823
6824}
6825
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006826static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6827 CXXScopeSpec &SS,
6828 SourceLocation IdentLoc,
6829 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006830 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006831 R.clear();
6832 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006833 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006834 Validator)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006835 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00006836 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6837 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006838 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00006839 S.diagnoseTypo(Corrected,
6840 S.PDiag(diag::err_using_directive_member_suggest)
6841 << Ident << DC << DroppedSpecifier << SS.getRange(),
6842 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006843 } else {
Richard Smith2d670972013-08-17 00:46:16 +00006844 S.diagnoseTypo(Corrected,
6845 S.PDiag(diag::err_using_directive_suggest) << Ident,
6846 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006847 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006848 R.addDecl(Corrected.getCorrectionDecl());
6849 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006850 }
6851 return false;
6852}
6853
John McCalld226f652010-08-21 09:40:31 +00006854Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006855 SourceLocation UsingLoc,
6856 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006857 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006858 SourceLocation IdentLoc,
6859 IdentifierInfo *NamespcName,
6860 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006861 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6862 assert(NamespcName && "Invalid NamespcName.");
6863 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006864
6865 // This can only happen along a recovery path.
6866 while (S->getFlags() & Scope::TemplateParamScope)
6867 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006868 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006869
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006870 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006871 NestedNameSpecifier *Qualifier = 0;
6872 if (SS.isSet())
6873 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6874
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006875 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006876 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6877 LookupParsedName(R, S, &SS);
6878 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006879 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006880
Douglas Gregor66992202010-06-29 17:53:46 +00006881 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006882 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006883 // Allow "using namespace std;" or "using namespace ::std;" even if
6884 // "std" hasn't been defined yet, for GCC compatibility.
6885 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6886 NamespcName->isStr("std")) {
6887 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006888 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006889 R.resolveKind();
6890 }
6891 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006892 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006893 }
6894
John McCallf36e02d2009-10-09 21:13:30 +00006895 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006896 NamedDecl *Named = R.getFoundDecl();
6897 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6898 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006899 // C++ [namespace.udir]p1:
6900 // A using-directive specifies that the names in the nominated
6901 // namespace can be used in the scope in which the
6902 // using-directive appears after the using-directive. During
6903 // unqualified name lookup (3.4.1), the names appear as if they
6904 // were declared in the nearest enclosing namespace which
6905 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006906 // namespace. [Note: in this context, "contains" means "contains
6907 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006908
6909 // Find enclosing context containing both using-directive and
6910 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006911 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006912 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6913 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6914 CommonAncestor = CommonAncestor->getParent();
6915
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006916 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006917 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006918 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006919
Douglas Gregor9172aa62011-03-26 22:25:30 +00006920 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00006921 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006922 Diag(IdentLoc, diag::warn_using_directive_in_header);
6923 }
6924
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006925 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006926 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006927 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006928 }
6929
Richard Smith6b3d3e52013-02-20 19:22:51 +00006930 if (UDir)
6931 ProcessDeclAttributeList(S, UDir, AttrList);
6932
John McCalld226f652010-08-21 09:40:31 +00006933 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006934}
6935
6936void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006937 // If the scope has an associated entity and the using directive is at
6938 // namespace or translation unit scope, add the UsingDirectiveDecl into
6939 // its lookup structure so qualified name lookup can find it.
6940 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6941 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006942 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006943 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006944 // Otherwise, it is at block sope. The using-directives will affect lookup
6945 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006946 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006947}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006948
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006949
John McCalld226f652010-08-21 09:40:31 +00006950Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006951 AccessSpecifier AS,
6952 bool HasUsingKeyword,
6953 SourceLocation UsingLoc,
6954 CXXScopeSpec &SS,
6955 UnqualifiedId &Name,
6956 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006957 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00006958 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006959 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006960
Douglas Gregor12c118a2009-11-04 16:30:06 +00006961 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006962 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006963 case UnqualifiedId::IK_Identifier:
6964 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006965 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006966 case UnqualifiedId::IK_ConversionFunctionId:
6967 break;
6968
6969 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006970 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006971 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006972 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006973 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006974 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006975 diag::err_using_decl_constructor)
6976 << SS.getRange();
6977
Richard Smith80ad52f2013-01-02 11:42:31 +00006978 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006979
John McCalld226f652010-08-21 09:40:31 +00006980 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006981
6982 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006983 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006984 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006985 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006986
6987 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006988 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006989 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006990 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006991 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006992
6993 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6994 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006995 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006996 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006997
Richard Smith07b0fdc2013-03-18 21:12:30 +00006998 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006999 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00007000 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00007001 getLangOpts().CPlusPlus11 ? diag::err_access_decl
7002 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00007003 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00007004 }
7005
Douglas Gregor56c04582010-12-16 00:46:58 +00007006 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7007 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7008 return 0;
7009
John McCall9488ea12009-11-17 05:59:44 +00007010 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007011 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007012 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007013 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00007014 if (UD)
7015 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00007016
John McCalld226f652010-08-21 09:40:31 +00007017 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00007018}
7019
Douglas Gregor09acc982010-07-07 23:08:52 +00007020/// \brief Determine whether a using declaration considers the given
7021/// declarations as "equivalent", e.g., if they are redeclarations of
7022/// the same entity or are both typedefs of the same type.
7023static bool
7024IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
7025 bool &SuppressRedeclaration) {
7026 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
7027 SuppressRedeclaration = false;
7028 return true;
7029 }
7030
Richard Smith162e1c12011-04-15 14:24:37 +00007031 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7032 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00007033 SuppressRedeclaration = true;
7034 return Context.hasSameType(TD1->getUnderlyingType(),
7035 TD2->getUnderlyingType());
7036 }
7037
7038 return false;
7039}
7040
7041
John McCall9f54ad42009-12-10 09:41:52 +00007042/// Determines whether to create a using shadow decl for a particular
7043/// decl, given the set of decls existing prior to this using lookup.
7044bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7045 const LookupResult &Previous) {
7046 // Diagnose finding a decl which is not from a base class of the
7047 // current class. We do this now because there are cases where this
7048 // function will silently decide not to build a shadow decl, which
7049 // will pre-empt further diagnostics.
7050 //
7051 // We don't need to do this in C++0x because we do the check once on
7052 // the qualifier.
7053 //
7054 // FIXME: diagnose the following if we care enough:
7055 // struct A { int foo; };
7056 // struct B : A { using A::foo; };
7057 // template <class T> struct C : A {};
7058 // template <class T> struct D : C<T> { using B::foo; } // <---
7059 // This is invalid (during instantiation) in C++03 because B::foo
7060 // resolves to the using decl in B, which is not a base class of D<T>.
7061 // We can't diagnose it immediately because C<T> is an unknown
7062 // specialization. The UsingShadowDecl in D<T> then points directly
7063 // to A::foo, which will look well-formed when we instantiate.
7064 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00007065 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00007066 DeclContext *OrigDC = Orig->getDeclContext();
7067
7068 // Handle enums and anonymous structs.
7069 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7070 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7071 while (OrigRec->isAnonymousStructOrUnion())
7072 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7073
7074 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7075 if (OrigDC == CurContext) {
7076 Diag(Using->getLocation(),
7077 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007078 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007079 Diag(Orig->getLocation(), diag::note_using_decl_target);
7080 return true;
7081 }
7082
Douglas Gregordc355712011-02-25 00:36:19 +00007083 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00007084 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00007085 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00007086 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00007087 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00007088 Diag(Orig->getLocation(), diag::note_using_decl_target);
7089 return true;
7090 }
7091 }
7092
7093 if (Previous.empty()) return false;
7094
7095 NamedDecl *Target = Orig;
7096 if (isa<UsingShadowDecl>(Target))
7097 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7098
John McCalld7533ec2009-12-11 02:33:26 +00007099 // If the target happens to be one of the previous declarations, we
7100 // don't have a conflict.
7101 //
7102 // FIXME: but we might be increasing its access, in which case we
7103 // should redeclare it.
7104 NamedDecl *NonTag = 0, *Tag = 0;
7105 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7106 I != E; ++I) {
7107 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00007108 bool Result;
7109 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
7110 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00007111
7112 (isa<TagDecl>(D) ? Tag : NonTag) = D;
7113 }
7114
John McCall9f54ad42009-12-10 09:41:52 +00007115 if (Target->isFunctionOrFunctionTemplate()) {
7116 FunctionDecl *FD;
7117 if (isa<FunctionTemplateDecl>(Target))
7118 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7119 else
7120 FD = cast<FunctionDecl>(Target);
7121
7122 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00007123 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00007124 case Ovl_Overload:
7125 return false;
7126
7127 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00007128 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007129 break;
7130
7131 // We found a decl with the exact signature.
7132 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00007133 // If we're in a record, we want to hide the target, so we
7134 // return true (without a diagnostic) to tell the caller not to
7135 // build a shadow decl.
7136 if (CurContext->isRecord())
7137 return true;
7138
7139 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00007140 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007141 break;
7142 }
7143
7144 Diag(Target->getLocation(), diag::note_using_decl_target);
7145 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7146 return true;
7147 }
7148
7149 // Target is not a function.
7150
John McCall9f54ad42009-12-10 09:41:52 +00007151 if (isa<TagDecl>(Target)) {
7152 // No conflict between a tag and a non-tag.
7153 if (!Tag) return false;
7154
John McCall41ce66f2009-12-10 19:51:03 +00007155 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007156 Diag(Target->getLocation(), diag::note_using_decl_target);
7157 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7158 return true;
7159 }
7160
7161 // No conflict between a tag and a non-tag.
7162 if (!NonTag) return false;
7163
John McCall41ce66f2009-12-10 19:51:03 +00007164 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00007165 Diag(Target->getLocation(), diag::note_using_decl_target);
7166 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7167 return true;
7168}
7169
John McCall9488ea12009-11-17 05:59:44 +00007170/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00007171UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00007172 UsingDecl *UD,
7173 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00007174
7175 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00007176 NamedDecl *Target = Orig;
7177 if (isa<UsingShadowDecl>(Target)) {
7178 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7179 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00007180 }
7181
7182 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00007183 = UsingShadowDecl::Create(Context, CurContext,
7184 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00007185 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00007186
7187 Shadow->setAccess(UD->getAccess());
7188 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7189 Shadow->setInvalidDecl();
7190
John McCall9488ea12009-11-17 05:59:44 +00007191 if (S)
John McCall604e7f12009-12-08 07:46:18 +00007192 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00007193 else
John McCall604e7f12009-12-08 07:46:18 +00007194 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00007195
John McCall604e7f12009-12-08 07:46:18 +00007196
John McCall9f54ad42009-12-10 09:41:52 +00007197 return Shadow;
7198}
John McCall604e7f12009-12-08 07:46:18 +00007199
John McCall9f54ad42009-12-10 09:41:52 +00007200/// Hides a using shadow declaration. This is required by the current
7201/// using-decl implementation when a resolvable using declaration in a
7202/// class is followed by a declaration which would hide or override
7203/// one or more of the using decl's targets; for example:
7204///
7205/// struct Base { void foo(int); };
7206/// struct Derived : Base {
7207/// using Base::foo;
7208/// void foo(int);
7209/// };
7210///
7211/// The governing language is C++03 [namespace.udecl]p12:
7212///
7213/// When a using-declaration brings names from a base class into a
7214/// derived class scope, member functions in the derived class
7215/// override and/or hide member functions with the same name and
7216/// parameter types in a base class (rather than conflicting).
7217///
7218/// There are two ways to implement this:
7219/// (1) optimistically create shadow decls when they're not hidden
7220/// by existing declarations, or
7221/// (2) don't create any shadow decls (or at least don't make them
7222/// visible) until we've fully parsed/instantiated the class.
7223/// The problem with (1) is that we might have to retroactively remove
7224/// a shadow decl, which requires several O(n) operations because the
7225/// decl structures are (very reasonably) not designed for removal.
7226/// (2) avoids this but is very fiddly and phase-dependent.
7227void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007228 if (Shadow->getDeclName().getNameKind() ==
7229 DeclarationName::CXXConversionFunctionName)
7230 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7231
John McCall9f54ad42009-12-10 09:41:52 +00007232 // Remove it from the DeclContext...
7233 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007234
John McCall9f54ad42009-12-10 09:41:52 +00007235 // ...and the scope, if applicable...
7236 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007237 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007238 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007239 }
7240
John McCall9f54ad42009-12-10 09:41:52 +00007241 // ...and the using decl.
7242 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7243
7244 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007245 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007246}
7247
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007248namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007249class UsingValidatorCCC : public CorrectionCandidateCallback {
7250public:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007251 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation)
7252 : HasTypenameKeyword(HasTypenameKeyword),
7253 IsInstantiation(IsInstantiation) {}
7254
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007255 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7256 NamedDecl *ND = Candidate.getCorrectionDecl();
7257
7258 // Keywords are not valid here.
7259 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007260 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007261
7262 // Completely unqualified names are invalid for a 'using' declaration.
7263 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7264 return false;
7265
7266 if (isa<TypeDecl>(ND))
7267 return HasTypenameKeyword || !IsInstantiation;
7268
7269 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007270 }
7271
7272private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007273 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007274 bool IsInstantiation;
7275};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007276} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007277
John McCall7ba107a2009-11-18 02:36:19 +00007278/// Builds a using declaration.
7279///
7280/// \param IsInstantiation - Whether this call arises from an
7281/// instantiation of an unresolved using declaration. We treat
7282/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007283NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7284 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007285 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007286 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007287 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007288 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007289 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007290 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007291 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007292 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007293 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007294
Anders Carlsson550b14b2009-08-28 05:49:21 +00007295 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007296
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007297 if (SS.isEmpty()) {
7298 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007299 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007300 }
Mike Stump1eb44332009-09-09 15:08:12 +00007301
John McCall9f54ad42009-12-10 09:41:52 +00007302 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007303 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007304 ForRedeclaration);
7305 Previous.setHideTags(false);
7306 if (S) {
7307 LookupName(Previous, S);
7308
7309 // It is really dumb that we have to do this.
7310 LookupResult::Filter F = Previous.makeFilter();
7311 while (F.hasNext()) {
7312 NamedDecl *D = F.next();
7313 if (!isDeclInScope(D, CurContext, S))
7314 F.erase();
7315 }
7316 F.done();
7317 } else {
7318 assert(IsInstantiation && "no scope in non-instantiation");
7319 assert(CurContext->isRecord() && "scope not record in instantiation");
7320 LookupQualifiedName(Previous, CurContext);
7321 }
7322
John McCall9f54ad42009-12-10 09:41:52 +00007323 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007324 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7325 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007326 return 0;
7327
7328 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007329 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7330 return 0;
7331
John McCallaf8e6ed2009-11-12 03:15:40 +00007332 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007333 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007334 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007335 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007336 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007337 // FIXME: not all declaration name kinds are legal here
7338 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7339 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007340 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007341 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007342 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007343 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7344 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007345 }
John McCalled976492009-12-04 22:46:56 +00007346 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007347 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007348 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007349 }
John McCalled976492009-12-04 22:46:56 +00007350 D->setAccess(AS);
7351 CurContext->addDecl(D);
7352
7353 if (!LookupContext) return D;
7354 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007355
John McCall77bb1aa2010-05-01 00:40:08 +00007356 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007357 UD->setInvalidDecl();
7358 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007359 }
7360
Richard Smithc5a89a12012-04-02 01:30:27 +00007361 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007362 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007363 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007364 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007365 return UD;
7366 }
7367
7368 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007369
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007370 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007371
John McCall604e7f12009-12-08 07:46:18 +00007372 // Unlike most lookups, we don't always want to hide tag
7373 // declarations: tag names are visible through the using declaration
7374 // even if hidden by ordinary names, *except* in a dependent context
7375 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007376 if (!IsInstantiation)
7377 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007378
John McCallb9abd8722012-04-07 03:04:20 +00007379 // For the purposes of this lookup, we have a base object type
7380 // equal to that of the current context.
7381 if (CurContext->isRecord()) {
7382 R.setBaseObjectType(
7383 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7384 }
7385
John McCalla24dc2e2009-11-17 02:14:36 +00007386 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007387
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007388 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007389 if (R.empty()) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007390 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation);
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007391 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7392 R.getLookupKind(), S, &SS, CCC)){
7393 // We reject any correction for which ND would be NULL.
7394 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007395 R.setLookupName(Corrected.getCorrection());
7396 R.addDecl(ND);
Richard Smith2d670972013-08-17 00:46:16 +00007397 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007398 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007399 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7400 << NameInfo.getName() << LookupContext << 0
7401 << SS.getRange());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007402 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007403 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007404 << NameInfo.getName() << LookupContext << SS.getRange();
7405 UD->setInvalidDecl();
7406 return UD;
7407 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007408 }
7409
John McCalled976492009-12-04 22:46:56 +00007410 if (R.isAmbiguous()) {
7411 UD->setInvalidDecl();
7412 return UD;
7413 }
Mike Stump1eb44332009-09-09 15:08:12 +00007414
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007415 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007416 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007417 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007418 Diag(IdentLoc, diag::err_using_typename_non_type);
7419 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7420 Diag((*I)->getUnderlyingDecl()->getLocation(),
7421 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007422 UD->setInvalidDecl();
7423 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007424 }
7425 } else {
7426 // If we asked for a non-typename and we got a type, error out,
7427 // but only if this is an instantiation of an unresolved using
7428 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007429 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007430 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7431 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007432 UD->setInvalidDecl();
7433 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007434 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007435 }
7436
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007437 // C++0x N2914 [namespace.udecl]p6:
7438 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007439 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007440 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7441 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007442 UD->setInvalidDecl();
7443 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007444 }
Mike Stump1eb44332009-09-09 15:08:12 +00007445
John McCall9f54ad42009-12-10 09:41:52 +00007446 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7447 if (!CheckUsingShadowDecl(UD, *I, Previous))
7448 BuildUsingShadowDecl(S, UD, *I);
7449 }
John McCall9488ea12009-11-17 05:59:44 +00007450
7451 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007452}
7453
Sebastian Redlf677ea32011-02-05 19:23:19 +00007454/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007455bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007456 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007457
Douglas Gregordc355712011-02-25 00:36:19 +00007458 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007459 assert(SourceType &&
7460 "Using decl naming constructor doesn't have type in scope spec.");
7461 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7462
7463 // Check whether the named type is a direct base class.
7464 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7465 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7466 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7467 BaseIt != BaseE; ++BaseIt) {
7468 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7469 if (CanonicalSourceType == BaseType)
7470 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007471 if (BaseIt->getType()->isDependentType())
7472 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007473 }
7474
7475 if (BaseIt == BaseE) {
7476 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007477 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007478 diag::err_using_decl_constructor_not_in_direct_base)
7479 << UD->getNameInfo().getSourceRange()
7480 << QualType(SourceType, 0) << TargetClass;
7481 return true;
7482 }
7483
Richard Smithc5a89a12012-04-02 01:30:27 +00007484 if (!CurContext->isDependentContext())
7485 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007486
7487 return false;
7488}
7489
John McCall9f54ad42009-12-10 09:41:52 +00007490/// Checks that the given using declaration is not an invalid
7491/// redeclaration. Note that this is checking only for the using decl
7492/// itself, not for any ill-formedness among the UsingShadowDecls.
7493bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007494 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007495 const CXXScopeSpec &SS,
7496 SourceLocation NameLoc,
7497 const LookupResult &Prev) {
7498 // C++03 [namespace.udecl]p8:
7499 // C++0x [namespace.udecl]p10:
7500 // A using-declaration is a declaration and can therefore be used
7501 // repeatedly where (and only where) multiple declarations are
7502 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007503 //
John McCall8a726212010-11-29 18:01:58 +00007504 // That's in non-member contexts.
7505 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007506 return false;
7507
7508 NestedNameSpecifier *Qual
7509 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7510
7511 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7512 NamedDecl *D = *I;
7513
7514 bool DTypename;
7515 NestedNameSpecifier *DQual;
7516 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007517 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007518 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007519 } else if (UnresolvedUsingValueDecl *UD
7520 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7521 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007522 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007523 } else if (UnresolvedUsingTypenameDecl *UD
7524 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7525 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007526 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007527 } else continue;
7528
7529 // using decls differ if one says 'typename' and the other doesn't.
7530 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007531 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007532
7533 // using decls differ if they name different scopes (but note that
7534 // template instantiation can cause this check to trigger when it
7535 // didn't before instantiation).
7536 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7537 Context.getCanonicalNestedNameSpecifier(DQual))
7538 continue;
7539
7540 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007541 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007542 return true;
7543 }
7544
7545 return false;
7546}
7547
John McCall604e7f12009-12-08 07:46:18 +00007548
John McCalled976492009-12-04 22:46:56 +00007549/// Checks that the given nested-name qualifier used in a using decl
7550/// in the current context is appropriately related to the current
7551/// scope. If an error is found, diagnoses it and returns true.
7552bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7553 const CXXScopeSpec &SS,
7554 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007555 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007556
John McCall604e7f12009-12-08 07:46:18 +00007557 if (!CurContext->isRecord()) {
7558 // C++03 [namespace.udecl]p3:
7559 // C++0x [namespace.udecl]p8:
7560 // A using-declaration for a class member shall be a member-declaration.
7561
7562 // If we weren't able to compute a valid scope, it must be a
7563 // dependent class scope.
7564 if (!NamedContext || NamedContext->isRecord()) {
7565 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7566 << SS.getRange();
7567 return true;
7568 }
7569
7570 // Otherwise, everything is known to be fine.
7571 return false;
7572 }
7573
7574 // The current scope is a record.
7575
7576 // If the named context is dependent, we can't decide much.
7577 if (!NamedContext) {
7578 // FIXME: in C++0x, we can diagnose if we can prove that the
7579 // nested-name-specifier does not refer to a base class, which is
7580 // still possible in some cases.
7581
7582 // Otherwise we have to conservatively report that things might be
7583 // okay.
7584 return false;
7585 }
7586
7587 if (!NamedContext->isRecord()) {
7588 // Ideally this would point at the last name in the specifier,
7589 // but we don't have that level of source info.
7590 Diag(SS.getRange().getBegin(),
7591 diag::err_using_decl_nested_name_specifier_is_not_class)
7592 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7593 return true;
7594 }
7595
Douglas Gregor6fb07292010-12-21 07:41:49 +00007596 if (!NamedContext->isDependentContext() &&
7597 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7598 return true;
7599
Richard Smith80ad52f2013-01-02 11:42:31 +00007600 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007601 // C++0x [namespace.udecl]p3:
7602 // In a using-declaration used as a member-declaration, the
7603 // nested-name-specifier shall name a base class of the class
7604 // being defined.
7605
7606 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7607 cast<CXXRecordDecl>(NamedContext))) {
7608 if (CurContext == NamedContext) {
7609 Diag(NameLoc,
7610 diag::err_using_decl_nested_name_specifier_is_current_class)
7611 << SS.getRange();
7612 return true;
7613 }
7614
7615 Diag(SS.getRange().getBegin(),
7616 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7617 << (NestedNameSpecifier*) SS.getScopeRep()
7618 << cast<CXXRecordDecl>(CurContext)
7619 << SS.getRange();
7620 return true;
7621 }
7622
7623 return false;
7624 }
7625
7626 // C++03 [namespace.udecl]p4:
7627 // A using-declaration used as a member-declaration shall refer
7628 // to a member of a base class of the class being defined [etc.].
7629
7630 // Salient point: SS doesn't have to name a base class as long as
7631 // lookup only finds members from base classes. Therefore we can
7632 // diagnose here only if we can prove that that can't happen,
7633 // i.e. if the class hierarchies provably don't intersect.
7634
7635 // TODO: it would be nice if "definitely valid" results were cached
7636 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7637 // need to be repeated.
7638
7639 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007640 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007641
7642 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7643 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7644 Data->Bases.insert(Base);
7645 return true;
7646 }
7647
7648 bool hasDependentBases(const CXXRecordDecl *Class) {
7649 return !Class->forallBases(collect, this);
7650 }
7651
7652 /// Returns true if the base is dependent or is one of the
7653 /// accumulated base classes.
7654 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7655 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7656 return !Data->Bases.count(Base);
7657 }
7658
7659 bool mightShareBases(const CXXRecordDecl *Class) {
7660 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7661 }
7662 };
7663
7664 UserData Data;
7665
7666 // Returns false if we find a dependent base.
7667 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7668 return false;
7669
7670 // Returns false if the class has a dependent base or if it or one
7671 // of its bases is present in the base set of the current context.
7672 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7673 return false;
7674
7675 Diag(SS.getRange().getBegin(),
7676 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7677 << (NestedNameSpecifier*) SS.getScopeRep()
7678 << cast<CXXRecordDecl>(CurContext)
7679 << SS.getRange();
7680
7681 return true;
John McCalled976492009-12-04 22:46:56 +00007682}
7683
Richard Smith162e1c12011-04-15 14:24:37 +00007684Decl *Sema::ActOnAliasDeclaration(Scope *S,
7685 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007686 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007687 SourceLocation UsingLoc,
7688 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007689 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007690 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007691 // Skip up to the relevant declaration scope.
7692 while (S->getFlags() & Scope::TemplateParamScope)
7693 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007694 assert((S->getFlags() & Scope::DeclScope) &&
7695 "got alias-declaration outside of declaration scope");
7696
7697 if (Type.isInvalid())
7698 return 0;
7699
7700 bool Invalid = false;
7701 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7702 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007703 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007704
7705 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7706 return 0;
7707
7708 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007709 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007710 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007711 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7712 TInfo->getTypeLoc().getBeginLoc());
7713 }
Richard Smith162e1c12011-04-15 14:24:37 +00007714
7715 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7716 LookupName(Previous, S);
7717
7718 // Warn about shadowing the name of a template parameter.
7719 if (Previous.isSingleResult() &&
7720 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007721 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007722 Previous.clear();
7723 }
7724
7725 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7726 "name in alias declaration must be an identifier");
7727 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7728 Name.StartLocation,
7729 Name.Identifier, TInfo);
7730
7731 NewTD->setAccess(AS);
7732
7733 if (Invalid)
7734 NewTD->setInvalidDecl();
7735
Richard Smith6b3d3e52013-02-20 19:22:51 +00007736 ProcessDeclAttributeList(S, NewTD, AttrList);
7737
Richard Smith3e4c6c42011-05-05 21:57:07 +00007738 CheckTypedefForVariablyModifiedType(S, NewTD);
7739 Invalid |= NewTD->isInvalidDecl();
7740
Richard Smith162e1c12011-04-15 14:24:37 +00007741 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007742
7743 NamedDecl *NewND;
7744 if (TemplateParamLists.size()) {
7745 TypeAliasTemplateDecl *OldDecl = 0;
7746 TemplateParameterList *OldTemplateParams = 0;
7747
7748 if (TemplateParamLists.size() != 1) {
7749 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007750 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7751 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007752 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007753 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007754
7755 // Only consider previous declarations in the same scope.
7756 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7757 /*ExplicitInstantiationOrSpecialization*/false);
7758 if (!Previous.empty()) {
7759 Redeclaration = true;
7760
7761 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7762 if (!OldDecl && !Invalid) {
7763 Diag(UsingLoc, diag::err_redefinition_different_kind)
7764 << Name.Identifier;
7765
7766 NamedDecl *OldD = Previous.getRepresentativeDecl();
7767 if (OldD->getLocation().isValid())
7768 Diag(OldD->getLocation(), diag::note_previous_definition);
7769
7770 Invalid = true;
7771 }
7772
7773 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7774 if (TemplateParameterListsAreEqual(TemplateParams,
7775 OldDecl->getTemplateParameters(),
7776 /*Complain=*/true,
7777 TPL_TemplateMatch))
7778 OldTemplateParams = OldDecl->getTemplateParameters();
7779 else
7780 Invalid = true;
7781
7782 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7783 if (!Invalid &&
7784 !Context.hasSameType(OldTD->getUnderlyingType(),
7785 NewTD->getUnderlyingType())) {
7786 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7787 // but we can't reasonably accept it.
7788 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7789 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7790 if (OldTD->getLocation().isValid())
7791 Diag(OldTD->getLocation(), diag::note_previous_definition);
7792 Invalid = true;
7793 }
7794 }
7795 }
7796
7797 // Merge any previous default template arguments into our parameters,
7798 // and check the parameter list.
7799 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7800 TPC_TypeAliasTemplate))
7801 return 0;
7802
7803 TypeAliasTemplateDecl *NewDecl =
7804 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7805 Name.Identifier, TemplateParams,
7806 NewTD);
7807
7808 NewDecl->setAccess(AS);
7809
7810 if (Invalid)
7811 NewDecl->setInvalidDecl();
7812 else if (OldDecl)
7813 NewDecl->setPreviousDeclaration(OldDecl);
7814
7815 NewND = NewDecl;
7816 } else {
7817 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7818 NewND = NewTD;
7819 }
Richard Smith162e1c12011-04-15 14:24:37 +00007820
7821 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007822 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007823
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007824 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007825 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007826}
7827
John McCalld226f652010-08-21 09:40:31 +00007828Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007829 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007830 SourceLocation AliasLoc,
7831 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007832 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007833 SourceLocation IdentLoc,
7834 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007835
Anders Carlsson81c85c42009-03-28 23:53:49 +00007836 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007837 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7838 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007839
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007840 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007841 NamedDecl *PrevDecl
7842 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7843 ForRedeclaration);
7844 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7845 PrevDecl = 0;
7846
7847 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007848 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007849 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007850 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007851 // FIXME: At some point, we'll want to create the (redundant)
7852 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007853 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007854 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007855 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007856 }
Mike Stump1eb44332009-09-09 15:08:12 +00007857
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007858 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7859 diag::err_redefinition_different_kind;
7860 Diag(AliasLoc, DiagID) << Alias;
7861 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007862 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007863 }
7864
John McCalla24dc2e2009-11-17 02:14:36 +00007865 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007866 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007867
John McCallf36e02d2009-10-09 21:13:30 +00007868 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007869 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007870 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007871 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007872 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007873 }
Mike Stump1eb44332009-09-09 15:08:12 +00007874
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007875 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007876 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007877 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007878 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007879
John McCall3dbd3d52010-02-16 06:53:13 +00007880 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007881 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007882}
7883
Sean Hunt001cad92011-05-10 00:49:42 +00007884Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007885Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7886 CXXMethodDecl *MD) {
7887 CXXRecordDecl *ClassDecl = MD->getParent();
7888
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007889 // C++ [except.spec]p14:
7890 // An implicitly declared special member function (Clause 12) shall have an
7891 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007892 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007893 if (ClassDecl->isInvalidDecl())
7894 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007895
Sebastian Redl60618fa2011-03-12 11:50:43 +00007896 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007897 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7898 BEnd = ClassDecl->bases_end();
7899 B != BEnd; ++B) {
7900 if (B->isVirtual()) // Handled below.
7901 continue;
7902
Douglas Gregor18274032010-07-03 00:47:00 +00007903 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7904 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007905 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7906 // If this is a deleted function, add it anyway. This might be conformant
7907 // with the standard. This might not. I'm not sure. It might not matter.
7908 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007909 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007910 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007911 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007912
7913 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007914 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7915 BEnd = ClassDecl->vbases_end();
7916 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007917 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7918 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007919 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7920 // If this is a deleted function, add it anyway. This might be conformant
7921 // with the standard. This might not. I'm not sure. It might not matter.
7922 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007923 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007924 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007925 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007926
7927 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007928 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7929 FEnd = ClassDecl->field_end();
7930 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007931 if (F->hasInClassInitializer()) {
7932 if (Expr *E = F->getInClassInitializer())
7933 ExceptSpec.CalledExpr(E);
7934 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007935 // DR1351:
7936 // If the brace-or-equal-initializer of a non-static data member
7937 // invokes a defaulted default constructor of its class or of an
7938 // enclosing class in a potentially evaluated subexpression, the
7939 // program is ill-formed.
7940 //
7941 // This resolution is unworkable: the exception specification of the
7942 // default constructor can be needed in an unevaluated context, in
7943 // particular, in the operand of a noexcept-expression, and we can be
7944 // unable to compute an exception specification for an enclosed class.
7945 //
7946 // We do not allow an in-class initializer to require the evaluation
7947 // of the exception specification for any in-class initializer whose
7948 // definition is not lexically complete.
7949 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007950 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007951 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007952 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7953 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7954 // If this is a deleted function, add it anyway. This might be conformant
7955 // with the standard. This might not. I'm not sure. It might not matter.
7956 // In particular, the problem is that this function never gets called. It
7957 // might just be ill-formed because this function attempts to refer to
7958 // a deleted function here.
7959 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007960 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007961 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007962 }
John McCalle23cf432010-12-14 08:05:40 +00007963
Sean Hunt001cad92011-05-10 00:49:42 +00007964 return ExceptSpec;
7965}
7966
Richard Smith07b0fdc2013-03-18 21:12:30 +00007967Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007968Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7969 CXXRecordDecl *ClassDecl = CD->getParent();
7970
7971 // C++ [except.spec]p14:
7972 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007973 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007974 if (ClassDecl->isInvalidDecl())
7975 return ExceptSpec;
7976
7977 // Inherited constructor.
7978 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7979 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7980 // FIXME: Copying or moving the parameters could add extra exceptions to the
7981 // set, as could the default arguments for the inherited constructor. This
7982 // will be addressed when we implement the resolution of core issue 1351.
7983 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7984
7985 // Direct base-class constructors.
7986 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7987 BEnd = ClassDecl->bases_end();
7988 B != BEnd; ++B) {
7989 if (B->isVirtual()) // Handled below.
7990 continue;
7991
7992 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7993 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7994 if (BaseClassDecl == InheritedDecl)
7995 continue;
7996 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7997 if (Constructor)
7998 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7999 }
8000 }
8001
8002 // Virtual base-class constructors.
8003 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8004 BEnd = ClassDecl->vbases_end();
8005 B != BEnd; ++B) {
8006 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8007 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8008 if (BaseClassDecl == InheritedDecl)
8009 continue;
8010 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8011 if (Constructor)
8012 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8013 }
8014 }
8015
8016 // Field constructors.
8017 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8018 FEnd = ClassDecl->field_end();
8019 F != FEnd; ++F) {
8020 if (F->hasInClassInitializer()) {
8021 if (Expr *E = F->getInClassInitializer())
8022 ExceptSpec.CalledExpr(E);
8023 else if (!F->isInvalidDecl())
8024 Diag(CD->getLocation(),
8025 diag::err_in_class_initializer_references_def_ctor) << CD;
8026 } else if (const RecordType *RecordTy
8027 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8028 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8029 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8030 if (Constructor)
8031 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8032 }
8033 }
8034
Richard Smith07b0fdc2013-03-18 21:12:30 +00008035 return ExceptSpec;
8036}
8037
Richard Smithafb49182012-11-29 01:34:07 +00008038namespace {
8039/// RAII object to register a special member as being currently declared.
8040struct DeclaringSpecialMember {
8041 Sema &S;
8042 Sema::SpecialMemberDecl D;
8043 bool WasAlreadyBeingDeclared;
8044
8045 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8046 : S(S), D(RD, CSM) {
8047 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8048 if (WasAlreadyBeingDeclared)
8049 // This almost never happens, but if it does, ensure that our cache
8050 // doesn't contain a stale result.
8051 S.SpecialMemberCache.clear();
8052
8053 // FIXME: Register a note to be produced if we encounter an error while
8054 // declaring the special member.
8055 }
8056 ~DeclaringSpecialMember() {
8057 if (!WasAlreadyBeingDeclared)
8058 S.SpecialMembersBeingDeclared.erase(D);
8059 }
8060
8061 /// \brief Are we already trying to declare this special member?
8062 bool isAlreadyBeingDeclared() const {
8063 return WasAlreadyBeingDeclared;
8064 }
8065};
8066}
8067
Sean Hunt001cad92011-05-10 00:49:42 +00008068CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8069 CXXRecordDecl *ClassDecl) {
8070 // C++ [class.ctor]p5:
8071 // A default constructor for a class X is a constructor of class X
8072 // that can be called without an argument. If there is no
8073 // user-declared constructor for class X, a default constructor is
8074 // implicitly declared. An implicitly-declared default constructor
8075 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00008076 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00008077 "Should not build implicit default constructor!");
8078
Richard Smithafb49182012-11-29 01:34:07 +00008079 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8080 if (DSM.isAlreadyBeingDeclared())
8081 return 0;
8082
Richard Smith7756afa2012-06-10 05:43:50 +00008083 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8084 CXXDefaultConstructor,
8085 false);
8086
Douglas Gregoreb8c6702010-07-01 22:31:05 +00008087 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00008088 CanQualType ClassType
8089 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008090 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008091 DeclarationName Name
8092 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008093 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00008094 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008095 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008096 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008097 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00008098 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00008099 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00008100 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008101
8102 // Build an exception specification pointing back at this constructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008103 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008104 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008105
Richard Smithbc2a35d2012-12-08 08:32:28 +00008106 // We don't need to use SpecialMemberIsTrivial here; triviality for default
8107 // constructors is easy to compute.
8108 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8109
8110 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008111 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008112
Douglas Gregor18274032010-07-03 00:47:00 +00008113 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00008114 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00008115
Douglas Gregor23c94db2010-07-02 17:43:08 +00008116 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00008117 PushOnScopeChains(DefaultCon, S, false);
8118 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00008119
Douglas Gregor32df23e2010-07-01 22:02:46 +00008120 return DefaultCon;
8121}
8122
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008123void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8124 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00008125 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008126 !Constructor->doesThisDeclarationHaveABody() &&
8127 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00008128 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008129
Anders Carlssonf6513ed2010-04-23 16:04:08 +00008130 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00008131 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00008132
Eli Friedman9a14db32012-10-18 20:14:08 +00008133 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008134 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00008135 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008136 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008137 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00008138 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00008139 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008140 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00008141 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008142
8143 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008144 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008145
Eli Friedman86164e82013-09-05 00:02:25 +00008146 Constructor->markUsed(Context);
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008147 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008148
8149 if (ASTMutationListener *L = getASTMutationListener()) {
8150 L->CompletedImplicitDefinition(Constructor);
8151 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00008152}
8153
Richard Smith7a614d82011-06-11 17:19:42 +00008154void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00008155 // Check that any explicitly-defaulted methods have exception specifications
8156 // compatible with their implicit exception specifications.
8157 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Trieuef8f90c2013-09-20 03:03:06 +00008158
8159 // Once all the member initializers are processed, perform checks to see if
8160 // any unintialized use is happeneing.
8161 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
8162 D->getLocation())
8163 == DiagnosticsEngine::Ignored)
8164 return;
8165
8166 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D);
8167 if (!RD) return;
8168
8169 // Holds fields that are uninitialized.
8170 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
8171
8172 // In the beginning, every field is uninitialized.
8173 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
8174 I != E; ++I) {
8175 if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
8176 UninitializedFields.insert(FD);
8177 } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
8178 UninitializedFields.insert(IFD->getAnonField());
8179 }
8180 }
8181
8182 for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
8183 I != E; ++I) {
8184 FieldDecl *FD = dyn_cast<FieldDecl>(*I);
8185 if (!FD)
8186 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I))
8187 FD = IFD->getAnonField();
8188
8189 if (!FD)
8190 continue;
8191
8192 Expr *InitExpr = FD->getInClassInitializer();
8193 if (!InitExpr) {
8194 // Uninitialized reference types will give an error.
8195 // Record types with an initializer are default initialized.
8196 QualType FieldType = FD->getType();
8197 if (FieldType->isReferenceType() || FieldType->isRecordType())
8198 UninitializedFields.erase(FD);
8199 continue;
8200 }
8201
8202 CheckInitExprContainsUninitializedFields(
8203 *this, InitExpr, FD, UninitializedFields,
8204 UninitializedFields.count(FD)/*WarnOnSelfReference*/);
8205
8206 UninitializedFields.erase(FD);
8207 }
Richard Smith7a614d82011-06-11 17:19:42 +00008208}
8209
Richard Smith4841ca52013-04-10 05:48:59 +00008210namespace {
8211/// Information on inheriting constructors to declare.
8212class InheritingConstructorInfo {
8213public:
8214 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8215 : SemaRef(SemaRef), Derived(Derived) {
8216 // Mark the constructors that we already have in the derived class.
8217 //
8218 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8219 // unless there is a user-declared constructor with the same signature in
8220 // the class where the using-declaration appears.
8221 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8222 }
8223
8224 void inheritAll(CXXRecordDecl *RD) {
8225 visitAll(RD, &InheritingConstructorInfo::inherit);
8226 }
8227
8228private:
8229 /// Information about an inheriting constructor.
8230 struct InheritingConstructor {
8231 InheritingConstructor()
8232 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8233
8234 /// If \c true, a constructor with this signature is already declared
8235 /// in the derived class.
8236 bool DeclaredInDerived;
8237
8238 /// The constructor which is inherited.
8239 const CXXConstructorDecl *BaseCtor;
8240
8241 /// The derived constructor we declared.
8242 CXXConstructorDecl *DerivedCtor;
8243 };
8244
8245 /// Inheriting constructors with a given canonical type. There can be at
8246 /// most one such non-template constructor, and any number of templated
8247 /// constructors.
8248 struct InheritingConstructorsForType {
8249 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00008250 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8251 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00008252
8253 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8254 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8255 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8256 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8257 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8258 false, S.TPL_TemplateMatch))
8259 return Templates[I].second;
8260 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8261 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008262 }
Richard Smith4841ca52013-04-10 05:48:59 +00008263
8264 return NonTemplate;
8265 }
8266 };
8267
8268 /// Get or create the inheriting constructor record for a constructor.
8269 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8270 QualType CtorType) {
8271 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8272 .getEntry(SemaRef, Ctor);
8273 }
8274
8275 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8276
8277 /// Process all constructors for a class.
8278 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8279 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8280 CtorE = RD->ctor_end();
8281 CtorIt != CtorE; ++CtorIt)
8282 (this->*Callback)(*CtorIt);
8283 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8284 I(RD->decls_begin()), E(RD->decls_end());
8285 I != E; ++I) {
8286 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8287 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8288 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008289 }
8290 }
Richard Smith4841ca52013-04-10 05:48:59 +00008291
8292 /// Note that a constructor (or constructor template) was declared in Derived.
8293 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8294 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8295 }
8296
8297 /// Inherit a single constructor.
8298 void inherit(const CXXConstructorDecl *Ctor) {
8299 const FunctionProtoType *CtorType =
8300 Ctor->getType()->castAs<FunctionProtoType>();
8301 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8302 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8303
8304 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8305
8306 // Core issue (no number yet): the ellipsis is always discarded.
8307 if (EPI.Variadic) {
8308 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8309 SemaRef.Diag(Ctor->getLocation(),
8310 diag::note_using_decl_constructor_ellipsis);
8311 EPI.Variadic = false;
8312 }
8313
8314 // Declare a constructor for each number of parameters.
8315 //
8316 // C++11 [class.inhctor]p1:
8317 // The candidate set of inherited constructors from the class X named in
8318 // the using-declaration consists of [... modulo defects ...] for each
8319 // constructor or constructor template of X, the set of constructors or
8320 // constructor templates that results from omitting any ellipsis parameter
8321 // specification and successively omitting parameters with a default
8322 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008323 unsigned MinParams = minParamsToInherit(Ctor);
8324 unsigned Params = Ctor->getNumParams();
8325 if (Params >= MinParams) {
8326 do
8327 declareCtor(UsingLoc, Ctor,
8328 SemaRef.Context.getFunctionType(
8329 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8330 while (Params > MinParams &&
8331 Ctor->getParamDecl(--Params)->hasDefaultArg());
8332 }
Richard Smith4841ca52013-04-10 05:48:59 +00008333 }
8334
8335 /// Find the using-declaration which specified that we should inherit the
8336 /// constructors of \p Base.
8337 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8338 // No fancy lookup required; just look for the base constructor name
8339 // directly within the derived class.
8340 ASTContext &Context = SemaRef.Context;
8341 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8342 Context.getCanonicalType(Context.getRecordType(Base)));
8343 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8344 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8345 }
8346
8347 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8348 // C++11 [class.inhctor]p3:
8349 // [F]or each constructor template in the candidate set of inherited
8350 // constructors, a constructor template is implicitly declared
8351 if (Ctor->getDescribedFunctionTemplate())
8352 return 0;
8353
8354 // For each non-template constructor in the candidate set of inherited
8355 // constructors other than a constructor having no parameters or a
8356 // copy/move constructor having a single parameter, a constructor is
8357 // implicitly declared [...]
8358 if (Ctor->getNumParams() == 0)
8359 return 1;
8360 if (Ctor->isCopyOrMoveConstructor())
8361 return 2;
8362
8363 // Per discussion on core reflector, never inherit a constructor which
8364 // would become a default, copy, or move constructor of Derived either.
8365 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8366 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8367 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8368 }
8369
8370 /// Declare a single inheriting constructor, inheriting the specified
8371 /// constructor, with the given type.
8372 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8373 QualType DerivedType) {
8374 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8375
8376 // C++11 [class.inhctor]p3:
8377 // ... a constructor is implicitly declared with the same constructor
8378 // characteristics unless there is a user-declared constructor with
8379 // the same signature in the class where the using-declaration appears
8380 if (Entry.DeclaredInDerived)
8381 return;
8382
8383 // C++11 [class.inhctor]p7:
8384 // If two using-declarations declare inheriting constructors with the
8385 // same signature, the program is ill-formed
8386 if (Entry.DerivedCtor) {
8387 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8388 // Only diagnose this once per constructor.
8389 if (Entry.DerivedCtor->isInvalidDecl())
8390 return;
8391 Entry.DerivedCtor->setInvalidDecl();
8392
8393 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8394 SemaRef.Diag(BaseCtor->getLocation(),
8395 diag::note_using_decl_constructor_conflict_current_ctor);
8396 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8397 diag::note_using_decl_constructor_conflict_previous_ctor);
8398 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8399 diag::note_using_decl_constructor_conflict_previous_using);
8400 } else {
8401 // Core issue (no number): if the same inheriting constructor is
8402 // produced by multiple base class constructors from the same base
8403 // class, the inheriting constructor is defined as deleted.
8404 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8405 }
8406
8407 return;
8408 }
8409
8410 ASTContext &Context = SemaRef.Context;
8411 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8412 Context.getCanonicalType(Context.getRecordType(Derived)));
8413 DeclarationNameInfo NameInfo(Name, UsingLoc);
8414
8415 TemplateParameterList *TemplateParams = 0;
8416 if (const FunctionTemplateDecl *FTD =
8417 BaseCtor->getDescribedFunctionTemplate()) {
8418 TemplateParams = FTD->getTemplateParameters();
8419 // We're reusing template parameters from a different DeclContext. This
8420 // is questionable at best, but works out because the template depth in
8421 // both places is guaranteed to be 0.
8422 // FIXME: Rebuild the template parameters in the new context, and
8423 // transform the function type to refer to them.
8424 }
8425
8426 // Build type source info pointing at the using-declaration. This is
8427 // required by template instantiation.
8428 TypeSourceInfo *TInfo =
8429 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8430 FunctionProtoTypeLoc ProtoLoc =
8431 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8432
8433 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8434 Context, Derived, UsingLoc, NameInfo, DerivedType,
8435 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8436 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8437
8438 // Build an unevaluated exception specification for this constructor.
8439 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8440 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8441 EPI.ExceptionSpecType = EST_Unevaluated;
8442 EPI.ExceptionSpecDecl = DerivedCtor;
8443 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8444 FPT->getArgTypes(), EPI));
8445
8446 // Build the parameter declarations.
8447 SmallVector<ParmVarDecl *, 16> ParamDecls;
8448 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8449 TypeSourceInfo *TInfo =
8450 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8451 ParmVarDecl *PD = ParmVarDecl::Create(
8452 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8453 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8454 PD->setScopeInfo(0, I);
8455 PD->setImplicit();
8456 ParamDecls.push_back(PD);
8457 ProtoLoc.setArg(I, PD);
8458 }
8459
8460 // Set up the new constructor.
8461 DerivedCtor->setAccess(BaseCtor->getAccess());
8462 DerivedCtor->setParams(ParamDecls);
8463 DerivedCtor->setInheritedConstructor(BaseCtor);
8464 if (BaseCtor->isDeleted())
8465 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8466
8467 // If this is a constructor template, build the template declaration.
8468 if (TemplateParams) {
8469 FunctionTemplateDecl *DerivedTemplate =
8470 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8471 TemplateParams, DerivedCtor);
8472 DerivedTemplate->setAccess(BaseCtor->getAccess());
8473 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8474 Derived->addDecl(DerivedTemplate);
8475 } else {
8476 Derived->addDecl(DerivedCtor);
8477 }
8478
8479 Entry.BaseCtor = BaseCtor;
8480 Entry.DerivedCtor = DerivedCtor;
8481 }
8482
8483 Sema &SemaRef;
8484 CXXRecordDecl *Derived;
8485 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8486 MapType Map;
8487};
8488}
8489
8490void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8491 // Defer declaring the inheriting constructors until the class is
8492 // instantiated.
8493 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008494 return;
8495
Richard Smith4841ca52013-04-10 05:48:59 +00008496 // Find base classes from which we might inherit constructors.
8497 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8498 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8499 BaseE = ClassDecl->bases_end();
8500 BaseIt != BaseE; ++BaseIt)
8501 if (BaseIt->getInheritConstructors())
8502 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008503
Richard Smith4841ca52013-04-10 05:48:59 +00008504 // Go no further if we're not inheriting any constructors.
8505 if (InheritedBases.empty())
8506 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008507
Richard Smith4841ca52013-04-10 05:48:59 +00008508 // Declare the inherited constructors.
8509 InheritingConstructorInfo ICI(*this, ClassDecl);
8510 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8511 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008512}
8513
Richard Smith07b0fdc2013-03-18 21:12:30 +00008514void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8515 CXXConstructorDecl *Constructor) {
8516 CXXRecordDecl *ClassDecl = Constructor->getParent();
8517 assert(Constructor->getInheritedConstructor() &&
8518 !Constructor->doesThisDeclarationHaveABody() &&
8519 !Constructor->isDeleted());
8520
8521 SynthesizedFunctionScope Scope(*this, Constructor);
8522 DiagnosticErrorTrap Trap(Diags);
8523 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8524 Trap.hasErrorOccurred()) {
8525 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8526 << Context.getTagDeclType(ClassDecl);
8527 Constructor->setInvalidDecl();
8528 return;
8529 }
8530
8531 SourceLocation Loc = Constructor->getLocation();
8532 Constructor->setBody(new (Context) CompoundStmt(Loc));
8533
Eli Friedman86164e82013-09-05 00:02:25 +00008534 Constructor->markUsed(Context);
Richard Smith07b0fdc2013-03-18 21:12:30 +00008535 MarkVTableUsed(CurrentLocation, ClassDecl);
8536
8537 if (ASTMutationListener *L = getASTMutationListener()) {
8538 L->CompletedImplicitDefinition(Constructor);
8539 }
8540}
8541
8542
Sean Huntcb45a0f2011-05-12 22:46:25 +00008543Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008544Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8545 CXXRecordDecl *ClassDecl = MD->getParent();
8546
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008547 // C++ [except.spec]p14:
8548 // An implicitly declared special member function (Clause 12) shall have
8549 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008550 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008551 if (ClassDecl->isInvalidDecl())
8552 return ExceptSpec;
8553
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008554 // Direct base-class destructors.
8555 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8556 BEnd = ClassDecl->bases_end();
8557 B != BEnd; ++B) {
8558 if (B->isVirtual()) // Handled below.
8559 continue;
8560
8561 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008562 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008563 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008564 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008565
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008566 // Virtual base-class destructors.
8567 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8568 BEnd = ClassDecl->vbases_end();
8569 B != BEnd; ++B) {
8570 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008571 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008572 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008573 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008574
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008575 // Field destructors.
8576 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8577 FEnd = ClassDecl->field_end();
8578 F != FEnd; ++F) {
8579 if (const RecordType *RecordTy
8580 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008581 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008582 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008583 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008584
Sean Huntcb45a0f2011-05-12 22:46:25 +00008585 return ExceptSpec;
8586}
8587
8588CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8589 // C++ [class.dtor]p2:
8590 // If a class has no user-declared destructor, a destructor is
8591 // declared implicitly. An implicitly-declared destructor is an
8592 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008593 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008594
Richard Smithafb49182012-11-29 01:34:07 +00008595 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8596 if (DSM.isAlreadyBeingDeclared())
8597 return 0;
8598
Douglas Gregor4923aa22010-07-02 20:37:36 +00008599 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008600 CanQualType ClassType
8601 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008602 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008603 DeclarationName Name
8604 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008605 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008606 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008607 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8608 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008609 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008610 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008611 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008612 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008613
8614 // Build an exception specification pointing back at this destructor.
Reid Kleckneref072032013-08-27 23:08:25 +00008615 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
Dmitri Gribenko55431692013-05-05 00:41:58 +00008616 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008617
Richard Smithbc2a35d2012-12-08 08:32:28 +00008618 AddOverriddenMethods(ClassDecl, Destructor);
8619
8620 // We don't need to use SpecialMemberIsTrivial here; triviality for
8621 // destructors is easy to compute.
8622 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8623
8624 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008625 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008626
Douglas Gregor4923aa22010-07-02 20:37:36 +00008627 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008628 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008629
Douglas Gregor4923aa22010-07-02 20:37:36 +00008630 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008631 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008632 PushOnScopeChains(Destructor, S, false);
8633 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008634
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008635 return Destructor;
8636}
8637
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008638void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008639 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008640 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008641 !Destructor->doesThisDeclarationHaveABody() &&
8642 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008643 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008644 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008645 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008646
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008647 if (Destructor->isInvalidDecl())
8648 return;
8649
Eli Friedman9a14db32012-10-18 20:14:08 +00008650 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008651
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008652 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008653 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8654 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008655
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008656 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008657 Diag(CurrentLocation, diag::note_member_synthesized_at)
8658 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8659
8660 Destructor->setInvalidDecl();
8661 return;
8662 }
8663
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008664 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008665 Destructor->setBody(new (Context) CompoundStmt(Loc));
Eli Friedman86164e82013-09-05 00:02:25 +00008666 Destructor->markUsed(Context);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008667 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008668
8669 if (ASTMutationListener *L = getASTMutationListener()) {
8670 L->CompletedImplicitDefinition(Destructor);
8671 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008672}
8673
Richard Smitha4156b82012-04-21 18:42:51 +00008674/// \brief Perform any semantic analysis which needs to be delayed until all
8675/// pending class member declarations have been parsed.
8676void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008677 // If the context is an invalid C++ class, just suppress these checks.
8678 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8679 if (Record->isInvalidDecl()) {
8680 DelayedDestructorExceptionSpecChecks.clear();
8681 return;
8682 }
8683 }
8684
Richard Smitha4156b82012-04-21 18:42:51 +00008685 // Perform any deferred checking of exception specifications for virtual
8686 // destructors.
8687 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8688 i != e; ++i) {
8689 const CXXDestructorDecl *Dtor =
8690 DelayedDestructorExceptionSpecChecks[i].first;
8691 assert(!Dtor->getParent()->isDependentType() &&
8692 "Should not ever add destructors of templates into the list.");
8693 CheckOverridingFunctionExceptionSpec(Dtor,
8694 DelayedDestructorExceptionSpecChecks[i].second);
8695 }
8696 DelayedDestructorExceptionSpecChecks.clear();
8697}
8698
Richard Smithb9d0b762012-07-27 04:22:15 +00008699void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8700 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008701 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008702 "adjusting dtor exception specs was introduced in c++11");
8703
Sebastian Redl0ee33912011-05-19 05:13:44 +00008704 // C++11 [class.dtor]p3:
8705 // A declaration of a destructor that does not have an exception-
8706 // specification is implicitly considered to have the same exception-
8707 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008708 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008709 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008710 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008711 return;
8712
Chandler Carruth3f224b22011-09-20 04:55:26 +00008713 // Replace the destructor's type, building off the existing one. Fortunately,
8714 // the only thing of interest in the destructor type is its extended info.
8715 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008716 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8717 EPI.ExceptionSpecType = EST_Unevaluated;
8718 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008719 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008720
Sebastian Redl0ee33912011-05-19 05:13:44 +00008721 // FIXME: If the destructor has a body that could throw, and the newly created
8722 // spec doesn't allow exceptions, we should emit a warning, because this
8723 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008724 // However, we don't have a body or an exception specification yet, so it
8725 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008726}
8727
Pavel Labath66ea35d2013-08-30 08:52:28 +00008728namespace {
8729/// \brief An abstract base class for all helper classes used in building the
8730// copy/move operators. These classes serve as factory functions and help us
8731// avoid using the same Expr* in the AST twice.
8732class ExprBuilder {
8733 ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8734 ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8735
8736protected:
8737 static Expr *assertNotNull(Expr *E) {
8738 assert(E && "Expression construction must not fail.");
8739 return E;
8740 }
8741
8742public:
8743 ExprBuilder() {}
8744 virtual ~ExprBuilder() {}
8745
8746 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8747};
8748
8749class RefBuilder: public ExprBuilder {
8750 VarDecl *Var;
8751 QualType VarType;
8752
8753public:
8754 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8755 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8756 }
8757
8758 RefBuilder(VarDecl *Var, QualType VarType)
8759 : Var(Var), VarType(VarType) {}
8760};
8761
8762class ThisBuilder: public ExprBuilder {
8763public:
8764 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8765 return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8766 }
8767};
8768
8769class CastBuilder: public ExprBuilder {
8770 const ExprBuilder &Builder;
8771 QualType Type;
8772 ExprValueKind Kind;
8773 const CXXCastPath &Path;
8774
8775public:
8776 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8777 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8778 CK_UncheckedDerivedToBase, Kind,
8779 &Path).take());
8780 }
8781
8782 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8783 const CXXCastPath &Path)
8784 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8785};
8786
8787class DerefBuilder: public ExprBuilder {
8788 const ExprBuilder &Builder;
8789
8790public:
8791 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8792 return assertNotNull(
8793 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8794 }
8795
8796 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8797};
8798
8799class MemberBuilder: public ExprBuilder {
8800 const ExprBuilder &Builder;
8801 QualType Type;
8802 CXXScopeSpec SS;
8803 bool IsArrow;
8804 LookupResult &MemberLookup;
8805
8806public:
8807 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8808 return assertNotNull(S.BuildMemberReferenceExpr(
8809 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8810 MemberLookup, 0).take());
8811 }
8812
8813 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8814 LookupResult &MemberLookup)
8815 : Builder(Builder), Type(Type), IsArrow(IsArrow),
8816 MemberLookup(MemberLookup) {}
8817};
8818
8819class MoveCastBuilder: public ExprBuilder {
8820 const ExprBuilder &Builder;
8821
8822public:
8823 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8824 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8825 }
8826
8827 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8828};
8829
8830class LvalueConvBuilder: public ExprBuilder {
8831 const ExprBuilder &Builder;
8832
8833public:
8834 virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8835 return assertNotNull(
8836 S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8837 }
8838
8839 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8840};
8841
8842class SubscriptBuilder: public ExprBuilder {
8843 const ExprBuilder &Base;
8844 const ExprBuilder &Index;
8845
8846public:
8847 virtual Expr *build(Sema &S, SourceLocation Loc) const
8848 LLVM_OVERRIDE {
8849 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8850 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8851 }
8852
8853 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8854 : Base(Base), Index(Index) {}
8855};
8856
8857} // end anonymous namespace
8858
Richard Smith8c889532012-11-14 00:50:40 +00008859/// When generating a defaulted copy or move assignment operator, if a field
8860/// should be copied with __builtin_memcpy rather than via explicit assignments,
8861/// do so. This optimization only applies for arrays of scalars, and for arrays
8862/// of class type where the selected copy/move-assignment operator is trivial.
8863static StmtResult
8864buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008865 const ExprBuilder &ToB, const ExprBuilder &FromB) {
Richard Smith8c889532012-11-14 00:50:40 +00008866 // Compute the size of the memory buffer to be copied.
8867 QualType SizeType = S.Context.getSizeType();
8868 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8869 S.Context.getTypeSizeInChars(T).getQuantity());
8870
8871 // Take the address of the field references for "from" and "to". We
8872 // directly construct UnaryOperators here because semantic analysis
8873 // does not permit us to take the address of an xvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00008874 Expr *From = FromB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008875 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8876 S.Context.getPointerType(From->getType()),
8877 VK_RValue, OK_Ordinary, Loc);
Pavel Labath66ea35d2013-08-30 08:52:28 +00008878 Expr *To = ToB.build(S, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008879 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8880 S.Context.getPointerType(To->getType()),
8881 VK_RValue, OK_Ordinary, Loc);
8882
8883 const Type *E = T->getBaseElementTypeUnsafe();
8884 bool NeedsCollectableMemCpy =
8885 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8886
8887 // Create a reference to the __builtin_objc_memmove_collectable function
8888 StringRef MemCpyName = NeedsCollectableMemCpy ?
8889 "__builtin_objc_memmove_collectable" :
8890 "__builtin_memcpy";
8891 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8892 Sema::LookupOrdinaryName);
8893 S.LookupName(R, S.TUScope, true);
8894
8895 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8896 if (!MemCpy)
8897 // Something went horribly wrong earlier, and we will have complained
8898 // about it.
8899 return StmtError();
8900
8901 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8902 VK_RValue, Loc, 0);
8903 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8904
8905 Expr *CallArgs[] = {
8906 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8907 };
8908 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8909 Loc, CallArgs, Loc);
8910
8911 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8912 return S.Owned(Call.takeAs<Stmt>());
8913}
8914
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008915/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008916/// \c To.
8917///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008918/// This routine is used to copy/move the members of a class with an
8919/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008920/// copied are arrays, this routine builds for loops to copy them.
8921///
8922/// \param S The Sema object used for type-checking.
8923///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008924/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008925///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008926/// \param T The type of the expressions being copied/moved. Both expressions
8927/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008928///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008929/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008930///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008931/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008932///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008933/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008934/// Otherwise, it's a non-static member subobject.
8935///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008936/// \param Copying Whether we're copying or moving.
8937///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008938/// \param Depth Internal parameter recording the depth of the recursion.
8939///
Richard Smith8c889532012-11-14 00:50:40 +00008940/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8941/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008942static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008943buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00008944 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00008945 bool CopyingBaseSubobject, bool Copying,
8946 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008947 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008948 // Each subobject is assigned in the manner appropriate to its type:
8949 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008950 // - if the subobject is of class type, as if by a call to operator= with
8951 // the subobject as the object expression and the corresponding
8952 // subobject of x as a single function argument (as if by explicit
8953 // qualification; that is, ignoring any possible virtual overriding
8954 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008955 //
8956 // C++03 [class.copy]p13:
8957 // - if the subobject is of class type, the copy assignment operator for
8958 // the class is used (as if by explicit qualification; that is,
8959 // ignoring any possible virtual overriding functions in more derived
8960 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008961 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8962 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008963
Douglas Gregor06a9f362010-05-01 20:49:11 +00008964 // Look for operator=.
8965 DeclarationName Name
8966 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8967 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8968 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008969
Richard Smith044c8aa2012-11-13 00:54:12 +00008970 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8971 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008972 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008973 LookupResult::Filter F = OpLookup.makeFilter();
8974 while (F.hasNext()) {
8975 NamedDecl *D = F.next();
8976 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8977 if (Method->isCopyAssignmentOperator() ||
8978 (!Copying && Method->isMoveAssignmentOperator()))
8979 continue;
8980
8981 F.erase();
8982 }
8983 F.done();
John McCallb0207482010-03-16 06:11:48 +00008984 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008985
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008986 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008987 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008988 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008989 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008990 // ambiguities), we need to cast "this" to that subobject type; to
8991 // ensure that we don't go through the virtual call mechanism, we need
8992 // to qualify the operator= name with the base class (see below). However,
8993 // this means that if the base class has a protected copy assignment
8994 // operator, the protected member access check will fail. So, we
8995 // rewrite "protected" access to "public" access in this case, since we
8996 // know by construction that we're calling from a derived class.
8997 if (CopyingBaseSubobject) {
8998 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8999 L != LEnd; ++L) {
9000 if (L.getAccess() == AS_protected)
9001 L.setAccess(AS_public);
9002 }
9003 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009004
Douglas Gregor06a9f362010-05-01 20:49:11 +00009005 // Create the nested-name-specifier that will be used to qualify the
9006 // reference to operator=; this is required to suppress the virtual
9007 // call mechanism.
9008 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009009 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00009010 SS.MakeTrivial(S.Context,
9011 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00009012 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00009013 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00009014
Douglas Gregor06a9f362010-05-01 20:49:11 +00009015 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00009016 ExprResult OpEqualRef
Pavel Labath66ea35d2013-08-30 08:52:28 +00009017 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
9018 SS, /*TemplateKWLoc=*/SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009019 /*FirstQualifierInScope=*/0,
9020 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009021 /*TemplateArgs=*/0,
9022 /*SuppressQualifierCheck=*/true);
9023 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009024 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009025
Douglas Gregor06a9f362010-05-01 20:49:11 +00009026 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00009027
Pavel Labath66ea35d2013-08-30 08:52:28 +00009028 Expr *FromInst = From.build(S, Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00009029 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00009030 OpEqualRef.takeAs<Expr>(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009031 Loc, FromInst, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009032 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009033 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00009034
Richard Smith8c889532012-11-14 00:50:40 +00009035 // If we built a call to a trivial 'operator=' while copying an array,
9036 // bail out. We'll replace the whole shebang with a memcpy.
9037 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
9038 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
9039 return StmtResult((Stmt*)0);
9040
Richard Smith044c8aa2012-11-13 00:54:12 +00009041 // Convert to an expression-statement, and clean up any produced
9042 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00009043 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009044 }
John McCallb0207482010-03-16 06:11:48 +00009045
Richard Smith044c8aa2012-11-13 00:54:12 +00009046 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00009047 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00009048 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009049 if (!ArrayTy) {
Pavel Labath66ea35d2013-08-30 08:52:28 +00009050 ExprResult Assignment = S.CreateBuiltinBinOp(
9051 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009052 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009053 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00009054 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009055 }
Richard Smith044c8aa2012-11-13 00:54:12 +00009056
9057 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00009058 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00009059
Douglas Gregor06a9f362010-05-01 20:49:11 +00009060 // Construct a loop over the array bounds, e.g.,
9061 //
9062 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9063 //
9064 // that will copy each of the array elements.
9065 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00009066
Douglas Gregor06a9f362010-05-01 20:49:11 +00009067 // Create the iteration variable.
9068 IdentifierInfo *IterationVarName = 0;
9069 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00009070 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009071 llvm::raw_svector_ostream OS(Str);
9072 OS << "__i" << Depth;
9073 IterationVarName = &S.Context.Idents.get(OS.str());
9074 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009075 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009076 IterationVarName, SizeType,
9077 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00009078 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00009079
Douglas Gregor06a9f362010-05-01 20:49:11 +00009080 // Initialize the iteration variable to zero.
9081 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009082 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009083
Pavel Labath66ea35d2013-08-30 08:52:28 +00009084 // Creates a reference to the iteration variable.
9085 RefBuilder IterationVarRef(IterationVar, SizeType);
9086 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
Eli Friedman8c382062012-01-23 02:35:22 +00009087
Douglas Gregor06a9f362010-05-01 20:49:11 +00009088 // Create the DeclStmt that holds the iteration variable.
9089 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009090
Douglas Gregor06a9f362010-05-01 20:49:11 +00009091 // Subscript the "from" and "to" expressions with the iteration variable.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009092 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9093 MoveCastBuilder FromIndexMove(FromIndexCopy);
9094 const ExprBuilder *FromIndex;
9095 if (Copying)
9096 FromIndex = &FromIndexCopy;
9097 else
9098 FromIndex = &FromIndexMove;
9099
9100 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009101
9102 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00009103 StmtResult Copy =
9104 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
Pavel Labath66ea35d2013-08-30 08:52:28 +00009105 ToIndex, *FromIndex, CopyingBaseSubobject,
Richard Smith8c889532012-11-14 00:50:40 +00009106 Copying, Depth + 1);
9107 // Bail out if copying fails or if we determined that we should use memcpy.
9108 if (Copy.isInvalid() || !Copy.get())
9109 return Copy;
9110
9111 // Create the comparison against the array bound.
9112 llvm::APInt Upper
9113 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9114 Expr *Comparison
Pavel Labath66ea35d2013-08-30 08:52:28 +00009115 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
Richard Smith8c889532012-11-14 00:50:40 +00009116 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9117 BO_NE, S.Context.BoolTy,
9118 VK_RValue, OK_Ordinary, Loc, false);
9119
9120 // Create the pre-increment of the iteration variable.
9121 Expr *Increment
Pavel Labath66ea35d2013-08-30 08:52:28 +00009122 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9123 SizeType, VK_LValue, OK_Ordinary, Loc);
Richard Smith8c889532012-11-14 00:50:40 +00009124
Douglas Gregor06a9f362010-05-01 20:49:11 +00009125 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00009126 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00009127 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00009128 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00009129 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009130}
9131
Richard Smith8c889532012-11-14 00:50:40 +00009132static StmtResult
9133buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009134 const ExprBuilder &To, const ExprBuilder &From,
Richard Smith8c889532012-11-14 00:50:40 +00009135 bool CopyingBaseSubobject, bool Copying) {
9136 // Maybe we should use a memcpy?
9137 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9138 T.isTriviallyCopyableType(S.Context))
9139 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9140
9141 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9142 CopyingBaseSubobject,
9143 Copying, 0));
9144
9145 // If we ended up picking a trivial assignment operator for an array of a
9146 // non-trivially-copyable class type, just emit a memcpy.
9147 if (!Result.isInvalid() && !Result.get())
9148 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9149
9150 return Result;
9151}
9152
Richard Smithb9d0b762012-07-27 04:22:15 +00009153Sema::ImplicitExceptionSpecification
9154Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9155 CXXRecordDecl *ClassDecl = MD->getParent();
9156
9157 ImplicitExceptionSpecification ExceptSpec(*this);
9158 if (ClassDecl->isInvalidDecl())
9159 return ExceptSpec;
9160
9161 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9162 assert(T->getNumArgs() == 1 && "not a copy assignment op");
9163 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9164
Douglas Gregorb87786f2010-07-01 17:48:08 +00009165 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00009166 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00009167 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00009168
9169 // It is unspecified whether or not an implicit copy assignment operator
9170 // attempts to deduplicate calls to assignment operators of virtual bases are
9171 // made. As such, this exception specification is effectively unspecified.
9172 // Based on a similar decision made for constness in C++0x, we're erring on
9173 // the side of assuming such calls to be made regardless of whether they
9174 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00009175 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9176 BaseEnd = ClassDecl->bases_end();
9177 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00009178 if (Base->isVirtual())
9179 continue;
9180
Douglas Gregora376d102010-07-02 21:50:04 +00009181 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00009182 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00009183 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9184 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009185 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00009186 }
Sean Hunt661c67a2011-06-21 23:42:56 +00009187
9188 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9189 BaseEnd = ClassDecl->vbases_end();
9190 Base != BaseEnd; ++Base) {
9191 CXXRecordDecl *BaseClassDecl
9192 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9193 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9194 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009195 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00009196 }
9197
Douglas Gregorb87786f2010-07-01 17:48:08 +00009198 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9199 FieldEnd = ClassDecl->field_end();
9200 Field != FieldEnd;
9201 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009202 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00009203 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9204 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009205 LookupCopyingAssignment(FieldClassDecl,
9206 ArgQuals | FieldType.getCVRQualifiers(),
9207 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009208 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00009209 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00009210 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009211
Richard Smithb9d0b762012-07-27 04:22:15 +00009212 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00009213}
9214
9215CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9216 // Note: The following rules are largely analoguous to the copy
9217 // constructor rules. Note that virtual bases are not taken into account
9218 // for determining the argument type of the operator. Note also that
9219 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00009220 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00009221
Richard Smithafb49182012-11-29 01:34:07 +00009222 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9223 if (DSM.isAlreadyBeingDeclared())
9224 return 0;
9225
Sean Hunt30de05c2011-05-14 05:23:20 +00009226 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9227 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00009228 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9229 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00009230 ArgType = ArgType.withConst();
9231 ArgType = Context.getLValueReferenceType(ArgType);
9232
Richard Smitha8942d72013-05-07 03:19:20 +00009233 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9234 CXXCopyAssignment,
9235 Const);
9236
Douglas Gregord3c35902010-07-01 16:36:15 +00009237 // An implicitly-declared copy assignment operator is an inline public
9238 // member of its class.
9239 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009240 SourceLocation ClassLoc = ClassDecl->getLocation();
9241 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009242 CXXMethodDecl *CopyAssignment =
9243 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9244 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9245 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00009246 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00009247 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00009248 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00009249
9250 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009251 FunctionProtoType::ExtProtoInfo EPI =
9252 getImplicitMethodEPI(*this, CopyAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009253 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009254
Douglas Gregord3c35902010-07-01 16:36:15 +00009255 // Add the parameter to the operator.
9256 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009257 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00009258 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009259 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009260 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00009261
Richard Smithbc2a35d2012-12-08 08:32:28 +00009262 AddOverriddenMethods(ClassDecl, CopyAssignment);
9263
9264 CopyAssignment->setTrivial(
9265 ClassDecl->needsOverloadResolutionForCopyAssignment()
9266 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9267 : ClassDecl->hasTrivialCopyAssignment());
9268
Richard Smitha8942d72013-05-07 03:19:20 +00009269 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00009270 // .... If the class definition does not explicitly declare a copy
9271 // assignment operator, there is no user-declared move constructor, and
9272 // there is no user-declared move assignment operator, a copy assignment
9273 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009274 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009275 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009276
Richard Smithbc2a35d2012-12-08 08:32:28 +00009277 // Note that we have added this copy-assignment operator.
9278 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9279
9280 if (Scope *S = getScopeForContext(ClassDecl))
9281 PushOnScopeChains(CopyAssignment, S, false);
9282 ClassDecl->addDecl(CopyAssignment);
9283
Douglas Gregord3c35902010-07-01 16:36:15 +00009284 return CopyAssignment;
9285}
9286
Richard Smith36155c12013-06-13 03:23:42 +00009287/// Diagnose an implicit copy operation for a class which is odr-used, but
9288/// which is deprecated because the class has a user-declared copy constructor,
9289/// copy assignment operator, or destructor.
9290static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9291 SourceLocation UseLoc) {
9292 assert(CopyOp->isImplicit());
9293
9294 CXXRecordDecl *RD = CopyOp->getParent();
9295 CXXMethodDecl *UserDeclaredOperation = 0;
9296
9297 // In Microsoft mode, assignment operations don't affect constructors and
9298 // vice versa.
9299 if (RD->hasUserDeclaredDestructor()) {
9300 UserDeclaredOperation = RD->getDestructor();
9301 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9302 RD->hasUserDeclaredCopyConstructor() &&
9303 !S.getLangOpts().MicrosoftMode) {
9304 // Find any user-declared copy constructor.
9305 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9306 E = RD->ctor_end(); I != E; ++I) {
9307 if (I->isCopyConstructor()) {
9308 UserDeclaredOperation = *I;
9309 break;
9310 }
9311 }
9312 assert(UserDeclaredOperation);
9313 } else if (isa<CXXConstructorDecl>(CopyOp) &&
9314 RD->hasUserDeclaredCopyAssignment() &&
9315 !S.getLangOpts().MicrosoftMode) {
9316 // Find any user-declared move assignment operator.
9317 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9318 E = RD->method_end(); I != E; ++I) {
9319 if (I->isCopyAssignmentOperator()) {
9320 UserDeclaredOperation = *I;
9321 break;
9322 }
9323 }
9324 assert(UserDeclaredOperation);
9325 }
9326
9327 if (UserDeclaredOperation) {
9328 S.Diag(UserDeclaredOperation->getLocation(),
9329 diag::warn_deprecated_copy_operation)
9330 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9331 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9332 S.Diag(UseLoc, diag::note_member_synthesized_at)
9333 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9334 : Sema::CXXCopyAssignment)
9335 << RD;
9336 }
9337}
9338
Douglas Gregor06a9f362010-05-01 20:49:11 +00009339void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9340 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00009341 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009342 CopyAssignOperator->isOverloadedOperator() &&
9343 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009344 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9345 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00009346 "DefineImplicitCopyAssignment called for wrong function");
9347
9348 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9349
9350 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9351 CopyAssignOperator->setInvalidDecl();
9352 return;
9353 }
Richard Smith36155c12013-06-13 03:23:42 +00009354
9355 // C++11 [class.copy]p18:
9356 // The [definition of an implicitly declared copy assignment operator] is
9357 // deprecated if the class has a user-declared copy constructor or a
9358 // user-declared destructor.
9359 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9360 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9361
Eli Friedman86164e82013-09-05 00:02:25 +00009362 CopyAssignOperator->markUsed(Context);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009363
Eli Friedman9a14db32012-10-18 20:14:08 +00009364 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009365 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009366
9367 // C++0x [class.copy]p30:
9368 // The implicitly-defined or explicitly-defaulted copy assignment operator
9369 // for a non-union class X performs memberwise copy assignment of its
9370 // subobjects. The direct base classes of X are assigned first, in the
9371 // order of their declaration in the base-specifier-list, and then the
9372 // immediate non-static data members of X are assigned, in the order in
9373 // which they were declared in the class definition.
9374
9375 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009376 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009377
9378 // The parameter for the "other" object, which we are copying from.
9379 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9380 Qualifiers OtherQuals = Other->getType().getQualifiers();
9381 QualType OtherRefType = Other->getType();
9382 if (const LValueReferenceType *OtherRef
9383 = OtherRefType->getAs<LValueReferenceType>()) {
9384 OtherRefType = OtherRef->getPointeeType();
9385 OtherQuals = OtherRefType.getQualifiers();
9386 }
9387
9388 // Our location for everything implicitly-generated.
9389 SourceLocation Loc = CopyAssignOperator->getLocation();
9390
Pavel Labath66ea35d2013-08-30 08:52:28 +00009391 // Builds a DeclRefExpr for the "other" object.
9392 RefBuilder OtherRef(Other, OtherRefType);
9393
9394 // Builds the "this" pointer.
9395 ThisBuilder This;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009396
9397 // Assign base classes.
9398 bool Invalid = false;
9399 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9400 E = ClassDecl->bases_end(); Base != E; ++Base) {
9401 // Form the assignment:
9402 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9403 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009404 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009405 Invalid = true;
9406 continue;
9407 }
9408
John McCallf871d0c2010-08-07 06:22:56 +00009409 CXXCastPath BasePath;
9410 BasePath.push_back(Base);
9411
Douglas Gregor06a9f362010-05-01 20:49:11 +00009412 // Construct the "from" expression, which is an implicit cast to the
9413 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009414 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9415 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009416
9417 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009418 DerefBuilder DerefThis(This);
9419 CastBuilder To(DerefThis,
9420 Context.getCVRQualifiedType(
9421 BaseType, CopyAssignOperator->getTypeQualifiers()),
9422 VK_LValue, BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009423
9424 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009425 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009426 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009427 /*CopyingBaseSubobject=*/true,
9428 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009429 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009430 Diag(CurrentLocation, diag::note_member_synthesized_at)
9431 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9432 CopyAssignOperator->setInvalidDecl();
9433 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009434 }
9435
9436 // Success! Record the copy.
9437 Statements.push_back(Copy.takeAs<Expr>());
9438 }
9439
Douglas Gregor06a9f362010-05-01 20:49:11 +00009440 // Assign non-static members.
9441 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9442 FieldEnd = ClassDecl->field_end();
9443 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009444 if (Field->isUnnamedBitfield())
9445 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009446
9447 if (Field->isInvalidDecl()) {
9448 Invalid = true;
9449 continue;
9450 }
9451
Douglas Gregor06a9f362010-05-01 20:49:11 +00009452 // Check for members of reference type; we can't copy those.
9453 if (Field->getType()->isReferenceType()) {
9454 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9455 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9456 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009457 Diag(CurrentLocation, diag::note_member_synthesized_at)
9458 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009459 Invalid = true;
9460 continue;
9461 }
9462
9463 // Check for members of const-qualified, non-class type.
9464 QualType BaseType = Context.getBaseElementType(Field->getType());
9465 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9466 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9467 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9468 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009469 Diag(CurrentLocation, diag::note_member_synthesized_at)
9470 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009471 Invalid = true;
9472 continue;
9473 }
John McCallb77115d2011-06-17 00:18:42 +00009474
9475 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009476 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9477 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009478
9479 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009480 if (FieldType->isIncompleteArrayType()) {
9481 assert(ClassDecl->hasFlexibleArrayMember() &&
9482 "Incomplete array type is not valid");
9483 continue;
9484 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009485
9486 // Build references to the field in the object we're copying from and to.
9487 CXXScopeSpec SS; // Intentionally empty
9488 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9489 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009490 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009491 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009492
9493 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9494
9495 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009496
Douglas Gregor06a9f362010-05-01 20:49:11 +00009497 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009498 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009499 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009500 /*CopyingBaseSubobject=*/false,
9501 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009502 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009503 Diag(CurrentLocation, diag::note_member_synthesized_at)
9504 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9505 CopyAssignOperator->setInvalidDecl();
9506 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009507 }
9508
9509 // Success! Record the copy.
9510 Statements.push_back(Copy.takeAs<Stmt>());
9511 }
9512
9513 if (!Invalid) {
9514 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009515 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00009516
John McCall60d7b3a2010-08-24 06:29:42 +00009517 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009518 if (Return.isInvalid())
9519 Invalid = true;
9520 else {
9521 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009522
9523 if (Trap.hasErrorOccurred()) {
9524 Diag(CurrentLocation, diag::note_member_synthesized_at)
9525 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9526 Invalid = true;
9527 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009528 }
9529 }
9530
9531 if (Invalid) {
9532 CopyAssignOperator->setInvalidDecl();
9533 return;
9534 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009535
9536 StmtResult Body;
9537 {
9538 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009539 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009540 /*isStmtExpr=*/false);
9541 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9542 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009543 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009544
9545 if (ASTMutationListener *L = getASTMutationListener()) {
9546 L->CompletedImplicitDefinition(CopyAssignOperator);
9547 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009548}
9549
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009550Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009551Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9552 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009553
Richard Smithb9d0b762012-07-27 04:22:15 +00009554 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009555 if (ClassDecl->isInvalidDecl())
9556 return ExceptSpec;
9557
9558 // C++0x [except.spec]p14:
9559 // An implicitly declared special member function (Clause 12) shall have an
9560 // exception-specification. [...]
9561
9562 // It is unspecified whether or not an implicit move assignment operator
9563 // attempts to deduplicate calls to assignment operators of virtual bases are
9564 // made. As such, this exception specification is effectively unspecified.
9565 // Based on a similar decision made for constness in C++0x, we're erring on
9566 // the side of assuming such calls to be made regardless of whether they
9567 // actually happen.
9568 // Note that a move constructor is not implicitly declared when there are
9569 // virtual bases, but it can still be user-declared and explicitly defaulted.
9570 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9571 BaseEnd = ClassDecl->bases_end();
9572 Base != BaseEnd; ++Base) {
9573 if (Base->isVirtual())
9574 continue;
9575
9576 CXXRecordDecl *BaseClassDecl
9577 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9578 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009579 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009580 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009581 }
9582
9583 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9584 BaseEnd = ClassDecl->vbases_end();
9585 Base != BaseEnd; ++Base) {
9586 CXXRecordDecl *BaseClassDecl
9587 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9588 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009589 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009590 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009591 }
9592
9593 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9594 FieldEnd = ClassDecl->field_end();
9595 Field != FieldEnd;
9596 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009597 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009598 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009599 if (CXXMethodDecl *MoveAssign =
9600 LookupMovingAssignment(FieldClassDecl,
9601 FieldType.getCVRQualifiers(),
9602 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009603 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009604 }
9605 }
9606
9607 return ExceptSpec;
9608}
9609
Richard Smith1c931be2012-04-02 18:40:40 +00009610/// Determine whether the class type has any direct or indirect virtual base
9611/// classes which have a non-trivial move assignment operator.
9612static bool
9613hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9614 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9615 BaseEnd = ClassDecl->vbases_end();
9616 Base != BaseEnd; ++Base) {
9617 CXXRecordDecl *BaseClass =
9618 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9619
9620 // Try to declare the move assignment. If it would be deleted, then the
9621 // class does not have a non-trivial move assignment.
9622 if (BaseClass->needsImplicitMoveAssignment())
9623 S.DeclareImplicitMoveAssignment(BaseClass);
9624
Richard Smith426391c2012-11-16 00:53:38 +00009625 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009626 return true;
9627 }
9628
9629 return false;
9630}
9631
9632/// Determine whether the given type either has a move constructor or is
9633/// trivially copyable.
9634static bool
9635hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9636 Type = S.Context.getBaseElementType(Type);
9637
9638 // FIXME: Technically, non-trivially-copyable non-class types, such as
9639 // reference types, are supposed to return false here, but that appears
9640 // to be a standard defect.
9641 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009642 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009643 return true;
9644
9645 if (Type.isTriviallyCopyableType(S.Context))
9646 return true;
9647
9648 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009649 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9650 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009651 if (ClassDecl->needsImplicitMoveConstructor())
9652 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009653 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009654 }
9655
Richard Smithe5411b72012-12-01 02:35:44 +00009656 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9657 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009658 if (ClassDecl->needsImplicitMoveAssignment())
9659 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009660 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009661}
9662
9663/// Determine whether all non-static data members and direct or virtual bases
9664/// of class \p ClassDecl have either a move operation, or are trivially
9665/// copyable.
9666static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9667 bool IsConstructor) {
9668 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9669 BaseEnd = ClassDecl->bases_end();
9670 Base != BaseEnd; ++Base) {
9671 if (Base->isVirtual())
9672 continue;
9673
9674 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9675 return false;
9676 }
9677
9678 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9679 BaseEnd = ClassDecl->vbases_end();
9680 Base != BaseEnd; ++Base) {
9681 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9682 return false;
9683 }
9684
9685 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9686 FieldEnd = ClassDecl->field_end();
9687 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009688 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009689 return false;
9690 }
9691
9692 return true;
9693}
9694
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009695CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009696 // C++11 [class.copy]p20:
9697 // If the definition of a class X does not explicitly declare a move
9698 // assignment operator, one will be implicitly declared as defaulted
9699 // if and only if:
9700 //
9701 // - [first 4 bullets]
9702 assert(ClassDecl->needsImplicitMoveAssignment());
9703
Richard Smithafb49182012-11-29 01:34:07 +00009704 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9705 if (DSM.isAlreadyBeingDeclared())
9706 return 0;
9707
Richard Smith1c931be2012-04-02 18:40:40 +00009708 // [Checked after we build the declaration]
9709 // - the move assignment operator would not be implicitly defined as
9710 // deleted,
9711
9712 // [DR1402]:
9713 // - X has no direct or indirect virtual base class with a non-trivial
9714 // move assignment operator, and
9715 // - each of X's non-static data members and direct or virtual base classes
9716 // has a type that either has a move assignment operator or is trivially
9717 // copyable.
9718 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9719 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9720 ClassDecl->setFailedImplicitMoveAssignment();
9721 return 0;
9722 }
9723
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009724 // Note: The following rules are largely analoguous to the move
9725 // constructor rules.
9726
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009727 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9728 QualType RetType = Context.getLValueReferenceType(ArgType);
9729 ArgType = Context.getRValueReferenceType(ArgType);
9730
Richard Smitha8942d72013-05-07 03:19:20 +00009731 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9732 CXXMoveAssignment,
9733 false);
9734
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009735 // An implicitly-declared move assignment operator is an inline public
9736 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009737 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9738 SourceLocation ClassLoc = ClassDecl->getLocation();
9739 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009740 CXXMethodDecl *MoveAssignment =
9741 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9742 /*TInfo=*/0, /*StorageClass=*/SC_None,
9743 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009744 MoveAssignment->setAccess(AS_public);
9745 MoveAssignment->setDefaulted();
9746 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009747
Richard Smithb9d0b762012-07-27 04:22:15 +00009748 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +00009749 FunctionProtoType::ExtProtoInfo EPI =
9750 getImplicitMethodEPI(*this, MoveAssignment);
Jordan Rosebea522f2013-03-08 21:51:21 +00009751 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009752
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009753 // Add the parameter to the operator.
9754 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9755 ClassLoc, ClassLoc, /*Id=*/0,
9756 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009757 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009758 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009759
Richard Smithbc2a35d2012-12-08 08:32:28 +00009760 AddOverriddenMethods(ClassDecl, MoveAssignment);
9761
9762 MoveAssignment->setTrivial(
9763 ClassDecl->needsOverloadResolutionForMoveAssignment()
9764 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9765 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009766
9767 // C++0x [class.copy]p9:
9768 // If the definition of a class X does not explicitly declare a move
9769 // assignment operator, one will be implicitly declared as defaulted if and
9770 // only if:
9771 // [...]
9772 // - the move assignment operator would not be implicitly defined as
9773 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009774 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009775 // Cache this result so that we don't try to generate this over and over
9776 // on every lookup, leaking memory and wasting time.
9777 ClassDecl->setFailedImplicitMoveAssignment();
9778 return 0;
9779 }
9780
Richard Smithbc2a35d2012-12-08 08:32:28 +00009781 // Note that we have added this copy-assignment operator.
9782 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9783
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009784 if (Scope *S = getScopeForContext(ClassDecl))
9785 PushOnScopeChains(MoveAssignment, S, false);
9786 ClassDecl->addDecl(MoveAssignment);
9787
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009788 return MoveAssignment;
9789}
9790
9791void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9792 CXXMethodDecl *MoveAssignOperator) {
9793 assert((MoveAssignOperator->isDefaulted() &&
9794 MoveAssignOperator->isOverloadedOperator() &&
9795 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009796 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9797 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009798 "DefineImplicitMoveAssignment called for wrong function");
9799
9800 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9801
9802 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9803 MoveAssignOperator->setInvalidDecl();
9804 return;
9805 }
9806
Eli Friedman86164e82013-09-05 00:02:25 +00009807 MoveAssignOperator->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009808
Eli Friedman9a14db32012-10-18 20:14:08 +00009809 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009810 DiagnosticErrorTrap Trap(Diags);
9811
9812 // C++0x [class.copy]p28:
9813 // The implicitly-defined or move assignment operator for a non-union class
9814 // X performs memberwise move assignment of its subobjects. The direct base
9815 // classes of X are assigned first, in the order of their declaration in the
9816 // base-specifier-list, and then the immediate non-static data members of X
9817 // are assigned, in the order in which they were declared in the class
9818 // definition.
9819
9820 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009821 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009822
9823 // The parameter for the "other" object, which we are move from.
9824 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9825 QualType OtherRefType = Other->getType()->
9826 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009827 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009828 "Bad argument type of defaulted move assignment");
9829
9830 // Our location for everything implicitly-generated.
9831 SourceLocation Loc = MoveAssignOperator->getLocation();
9832
Pavel Labath66ea35d2013-08-30 08:52:28 +00009833 // Builds a reference to the "other" object.
9834 RefBuilder OtherRef(Other, OtherRefType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009835 // Cast to rvalue.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009836 MoveCastBuilder MoveOther(OtherRef);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009837
Pavel Labath66ea35d2013-08-30 08:52:28 +00009838 // Builds the "this" pointer.
9839 ThisBuilder This;
Richard Smith1c931be2012-04-02 18:40:40 +00009840
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009841 // Assign base classes.
9842 bool Invalid = false;
9843 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9844 E = ClassDecl->bases_end(); Base != E; ++Base) {
9845 // Form the assignment:
9846 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9847 QualType BaseType = Base->getType().getUnqualifiedType();
9848 if (!BaseType->isRecordType()) {
9849 Invalid = true;
9850 continue;
9851 }
9852
9853 CXXCastPath BasePath;
9854 BasePath.push_back(Base);
9855
9856 // Construct the "from" expression, which is an implicit cast to the
9857 // appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009858 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009859
9860 // Dereference "this".
Pavel Labath66ea35d2013-08-30 08:52:28 +00009861 DerefBuilder DerefThis(This);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009862
9863 // Implicitly cast "this" to the appropriately-qualified base type.
Pavel Labath66ea35d2013-08-30 08:52:28 +00009864 CastBuilder To(DerefThis,
9865 Context.getCVRQualifiedType(
9866 BaseType, MoveAssignOperator->getTypeQualifiers()),
9867 VK_LValue, BasePath);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009868
9869 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009870 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009871 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009872 /*CopyingBaseSubobject=*/true,
9873 /*Copying=*/false);
9874 if (Move.isInvalid()) {
9875 Diag(CurrentLocation, diag::note_member_synthesized_at)
9876 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9877 MoveAssignOperator->setInvalidDecl();
9878 return;
9879 }
9880
9881 // Success! Record the move.
9882 Statements.push_back(Move.takeAs<Expr>());
9883 }
9884
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009885 // Assign non-static members.
9886 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9887 FieldEnd = ClassDecl->field_end();
9888 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009889 if (Field->isUnnamedBitfield())
9890 continue;
9891
Eli Friedman8150da32013-06-07 01:48:56 +00009892 if (Field->isInvalidDecl()) {
9893 Invalid = true;
9894 continue;
9895 }
9896
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009897 // Check for members of reference type; we can't move those.
9898 if (Field->getType()->isReferenceType()) {
9899 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9900 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9901 Diag(Field->getLocation(), diag::note_declared_at);
9902 Diag(CurrentLocation, diag::note_member_synthesized_at)
9903 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9904 Invalid = true;
9905 continue;
9906 }
9907
9908 // Check for members of const-qualified, non-class type.
9909 QualType BaseType = Context.getBaseElementType(Field->getType());
9910 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9911 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9912 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9913 Diag(Field->getLocation(), diag::note_declared_at);
9914 Diag(CurrentLocation, diag::note_member_synthesized_at)
9915 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9916 Invalid = true;
9917 continue;
9918 }
9919
9920 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009921 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9922 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009923
9924 QualType FieldType = Field->getType().getNonReferenceType();
9925 if (FieldType->isIncompleteArrayType()) {
9926 assert(ClassDecl->hasFlexibleArrayMember() &&
9927 "Incomplete array type is not valid");
9928 continue;
9929 }
9930
9931 // Build references to the field in the object we're copying from and to.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009932 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9933 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009934 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009935 MemberLookup.resolveKind();
Pavel Labath66ea35d2013-08-30 08:52:28 +00009936 MemberBuilder From(MoveOther, OtherRefType,
9937 /*IsArrow=*/false, MemberLookup);
9938 MemberBuilder To(This, getCurrentThisType(),
9939 /*IsArrow=*/true, MemberLookup);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009940
Pavel Labath66ea35d2013-08-30 08:52:28 +00009941 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009942 "Member reference with rvalue base must be rvalue except for reference "
9943 "members, which aren't allowed for move assignment.");
9944
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009945 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009946 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Pavel Labath66ea35d2013-08-30 08:52:28 +00009947 To, From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009948 /*CopyingBaseSubobject=*/false,
9949 /*Copying=*/false);
9950 if (Move.isInvalid()) {
9951 Diag(CurrentLocation, diag::note_member_synthesized_at)
9952 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9953 MoveAssignOperator->setInvalidDecl();
9954 return;
9955 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009956
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009957 // Success! Record the copy.
9958 Statements.push_back(Move.takeAs<Stmt>());
9959 }
9960
9961 if (!Invalid) {
9962 // Add a "return *this;"
Pavel Labath66ea35d2013-08-30 08:52:28 +00009963 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009964
9965 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9966 if (Return.isInvalid())
9967 Invalid = true;
9968 else {
9969 Statements.push_back(Return.takeAs<Stmt>());
9970
9971 if (Trap.hasErrorOccurred()) {
9972 Diag(CurrentLocation, diag::note_member_synthesized_at)
9973 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9974 Invalid = true;
9975 }
9976 }
9977 }
9978
9979 if (Invalid) {
9980 MoveAssignOperator->setInvalidDecl();
9981 return;
9982 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009983
9984 StmtResult Body;
9985 {
9986 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009987 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009988 /*isStmtExpr=*/false);
9989 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9990 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009991 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9992
9993 if (ASTMutationListener *L = getASTMutationListener()) {
9994 L->CompletedImplicitDefinition(MoveAssignOperator);
9995 }
9996}
9997
Richard Smithb9d0b762012-07-27 04:22:15 +00009998Sema::ImplicitExceptionSpecification
9999Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
10000 CXXRecordDecl *ClassDecl = MD->getParent();
10001
10002 ImplicitExceptionSpecification ExceptSpec(*this);
10003 if (ClassDecl->isInvalidDecl())
10004 return ExceptSpec;
10005
10006 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
10007 assert(T->getNumArgs() >= 1 && "not a copy ctor");
10008 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
10009
Douglas Gregor0d405db2010-07-01 20:59:04 +000010010 // C++ [except.spec]p14:
10011 // An implicitly declared special member function (Clause 12) shall have an
10012 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +000010013 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
10014 BaseEnd = ClassDecl->bases_end();
10015 Base != BaseEnd;
10016 ++Base) {
10017 // Virtual bases are handled below.
10018 if (Base->isVirtual())
10019 continue;
10020
Douglas Gregor22584312010-07-02 23:41:54 +000010021 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +000010022 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010023 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010024 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +000010025 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010026 }
10027 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
10028 BaseEnd = ClassDecl->vbases_end();
10029 Base != BaseEnd;
10030 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +000010031 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +000010032 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +000010033 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +000010034 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +000010035 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010036 }
10037 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
10038 FieldEnd = ClassDecl->field_end();
10039 Field != FieldEnd;
10040 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +000010041 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +000010042 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
10043 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +000010044 LookupCopyingConstructor(FieldClassDecl,
10045 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +000010046 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +000010047 }
10048 }
Sebastian Redl60618fa2011-03-12 11:50:43 +000010049
Richard Smithb9d0b762012-07-27 04:22:15 +000010050 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +000010051}
10052
10053CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10054 CXXRecordDecl *ClassDecl) {
10055 // C++ [class.copy]p4:
10056 // If the class definition does not explicitly declare a copy
10057 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +000010058 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +000010059
Richard Smithafb49182012-11-29 01:34:07 +000010060 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10061 if (DSM.isAlreadyBeingDeclared())
10062 return 0;
10063
Sean Hunt49634cf2011-05-13 06:10:58 +000010064 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10065 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +000010066 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +000010067 if (Const)
10068 ArgType = ArgType.withConst();
10069 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +000010070
Richard Smith7756afa2012-06-10 05:43:50 +000010071 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10072 CXXCopyConstructor,
10073 Const);
10074
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010075 DeclarationName Name
10076 = Context.DeclarationNames.getCXXConstructorName(
10077 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010078 SourceLocation ClassLoc = ClassDecl->getLocation();
10079 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +000010080
10081 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010082 // member of its class.
10083 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010084 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010085 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010086 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010087 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +000010088 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010089
Richard Smithb9d0b762012-07-27 04:22:15 +000010090 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010091 FunctionProtoType::ExtProtoInfo EPI =
10092 getImplicitMethodEPI(*this, CopyConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010093 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010094 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010095
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010096 // Add the parameter to the constructor.
10097 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010098 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010099 /*IdentifierInfo=*/0,
10100 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +000010101 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010102 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +000010103
Richard Smithbc2a35d2012-12-08 08:32:28 +000010104 CopyConstructor->setTrivial(
10105 ClassDecl->needsOverloadResolutionForCopyConstructor()
10106 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10107 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +000010108
Nico Weberafcc96a2012-01-23 03:19:29 +000010109 // C++11 [class.copy]p8:
10110 // ... If the class definition does not explicitly declare a copy
10111 // constructor, there is no user-declared move constructor, and there is no
10112 // user-declared move assignment operator, a copy constructor is implicitly
10113 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +000010114 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +000010115 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +000010116
Richard Smithbc2a35d2012-12-08 08:32:28 +000010117 // Note that we have declared this constructor.
10118 ++ASTContext::NumImplicitCopyConstructorsDeclared;
10119
10120 if (Scope *S = getScopeForContext(ClassDecl))
10121 PushOnScopeChains(CopyConstructor, S, false);
10122 ClassDecl->addDecl(CopyConstructor);
10123
Douglas Gregor4a0c26f2010-07-01 17:57:27 +000010124 return CopyConstructor;
10125}
10126
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010127void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +000010128 CXXConstructorDecl *CopyConstructor) {
10129 assert((CopyConstructor->isDefaulted() &&
10130 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010131 !CopyConstructor->doesThisDeclarationHaveABody() &&
10132 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010133 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +000010134
Anders Carlsson63010a72010-04-23 16:24:12 +000010135 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010136 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010137
Richard Smith36155c12013-06-13 03:23:42 +000010138 // C++11 [class.copy]p7:
Benjamin Kramere5753592013-09-09 14:48:42 +000010139 // The [definition of an implicitly declared copy constructor] is
Richard Smith36155c12013-06-13 03:23:42 +000010140 // deprecated if the class has a user-declared copy assignment operator
10141 // or a user-declared destructor.
10142 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10143 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10144
Eli Friedman9a14db32012-10-18 20:14:08 +000010145 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +000010146 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010147
David Blaikie93c86172013-01-17 05:26:25 +000010148 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +000010149 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +000010150 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010151 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +000010152 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +000010153 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010154 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010155 CopyConstructor->setBody(ActOnCompoundStmt(
10156 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10157 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +000010158 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010159
Eli Friedman86164e82013-09-05 00:02:25 +000010160 CopyConstructor->markUsed(Context);
Sebastian Redl58a2cd82011-04-24 16:28:06 +000010161 if (ASTMutationListener *L = getASTMutationListener()) {
10162 L->CompletedImplicitDefinition(CopyConstructor);
10163 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +000010164}
10165
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010166Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +000010167Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10168 CXXRecordDecl *ClassDecl = MD->getParent();
10169
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010170 // C++ [except.spec]p14:
10171 // An implicitly declared special member function (Clause 12) shall have an
10172 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +000010173 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010174 if (ClassDecl->isInvalidDecl())
10175 return ExceptSpec;
10176
10177 // Direct base-class constructors.
10178 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10179 BEnd = ClassDecl->bases_end();
10180 B != BEnd; ++B) {
10181 if (B->isVirtual()) // Handled below.
10182 continue;
10183
10184 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10185 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010186 CXXConstructorDecl *Constructor =
10187 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010188 // If this is a deleted function, add it anyway. This might be conformant
10189 // with the standard. This might not. I'm not sure. It might not matter.
10190 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010191 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010192 }
10193 }
10194
10195 // Virtual base-class constructors.
10196 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10197 BEnd = ClassDecl->vbases_end();
10198 B != BEnd; ++B) {
10199 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10200 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +000010201 CXXConstructorDecl *Constructor =
10202 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010203 // If this is a deleted function, add it anyway. This might be conformant
10204 // with the standard. This might not. I'm not sure. It might not matter.
10205 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010206 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010207 }
10208 }
10209
10210 // Field constructors.
10211 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10212 FEnd = ClassDecl->field_end();
10213 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +000010214 QualType FieldType = Context.getBaseElementType(F->getType());
10215 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10216 CXXConstructorDecl *Constructor =
10217 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
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 // In particular, the problem is that this function never gets called. It
10221 // might just be ill-formed because this function attempts to refer to
10222 // a deleted function here.
10223 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +000010224 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010225 }
10226 }
10227
10228 return ExceptSpec;
10229}
10230
10231CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10232 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +000010233 // C++11 [class.copy]p9:
10234 // If the definition of a class X does not explicitly declare a move
10235 // constructor, one will be implicitly declared as defaulted if and only if:
10236 //
10237 // - [first 4 bullets]
10238 assert(ClassDecl->needsImplicitMoveConstructor());
10239
Richard Smithafb49182012-11-29 01:34:07 +000010240 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10241 if (DSM.isAlreadyBeingDeclared())
10242 return 0;
10243
Richard Smith1c931be2012-04-02 18:40:40 +000010244 // [Checked after we build the declaration]
10245 // - the move assignment operator would not be implicitly defined as
10246 // deleted,
10247
10248 // [DR1402]:
10249 // - each of X's non-static data members and direct or virtual base classes
10250 // has a type that either has a move constructor or is trivially copyable.
10251 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
10252 ClassDecl->setFailedImplicitMoveConstructor();
10253 return 0;
10254 }
10255
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010256 QualType ClassType = Context.getTypeDeclType(ClassDecl);
10257 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010258
Richard Smith7756afa2012-06-10 05:43:50 +000010259 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10260 CXXMoveConstructor,
10261 false);
10262
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010263 DeclarationName Name
10264 = Context.DeclarationNames.getCXXConstructorName(
10265 Context.getCanonicalType(ClassType));
10266 SourceLocation ClassLoc = ClassDecl->getLocation();
10267 DeclarationNameInfo NameInfo(Name, ClassLoc);
10268
Richard Smitha8942d72013-05-07 03:19:20 +000010269 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010270 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +000010271 // member of its class.
10272 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +000010273 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +000010274 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +000010275 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010276 MoveConstructor->setAccess(AS_public);
10277 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +000010278
Richard Smithb9d0b762012-07-27 04:22:15 +000010279 // Build an exception specification pointing back at this member.
Reid Kleckneref072032013-08-27 23:08:25 +000010280 FunctionProtoType::ExtProtoInfo EPI =
10281 getImplicitMethodEPI(*this, MoveConstructor);
Richard Smithb9d0b762012-07-27 04:22:15 +000010282 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +000010283 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +000010284
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010285 // Add the parameter to the constructor.
10286 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10287 ClassLoc, ClassLoc,
10288 /*IdentifierInfo=*/0,
10289 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010290 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +000010291 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010292
Richard Smithbc2a35d2012-12-08 08:32:28 +000010293 MoveConstructor->setTrivial(
10294 ClassDecl->needsOverloadResolutionForMoveConstructor()
10295 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10296 : ClassDecl->hasTrivialMoveConstructor());
10297
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010298 // C++0x [class.copy]p9:
10299 // If the definition of a class X does not explicitly declare a move
10300 // constructor, one will be implicitly declared as defaulted if and only if:
10301 // [...]
10302 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +000010303 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010304 // Cache this result so that we don't try to generate this over and over
10305 // on every lookup, leaking memory and wasting time.
10306 ClassDecl->setFailedImplicitMoveConstructor();
10307 return 0;
10308 }
10309
10310 // Note that we have declared this constructor.
10311 ++ASTContext::NumImplicitMoveConstructorsDeclared;
10312
10313 if (Scope *S = getScopeForContext(ClassDecl))
10314 PushOnScopeChains(MoveConstructor, S, false);
10315 ClassDecl->addDecl(MoveConstructor);
10316
10317 return MoveConstructor;
10318}
10319
10320void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10321 CXXConstructorDecl *MoveConstructor) {
10322 assert((MoveConstructor->isDefaulted() &&
10323 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +000010324 !MoveConstructor->doesThisDeclarationHaveABody() &&
10325 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010326 "DefineImplicitMoveConstructor - call it for implicit move ctor");
10327
10328 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10329 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10330
Eli Friedman9a14db32012-10-18 20:14:08 +000010331 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010332 DiagnosticErrorTrap Trap(Diags);
10333
David Blaikie93c86172013-01-17 05:26:25 +000010334 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010335 Trap.hasErrorOccurred()) {
10336 Diag(CurrentLocation, diag::note_member_synthesized_at)
10337 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10338 MoveConstructor->setInvalidDecl();
10339 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +000010340 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +000010341 MoveConstructor->setBody(ActOnCompoundStmt(
10342 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10343 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010344 }
10345
Eli Friedman86164e82013-09-05 00:02:25 +000010346 MoveConstructor->markUsed(Context);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010347
10348 if (ASTMutationListener *L = getASTMutationListener()) {
10349 L->CompletedImplicitDefinition(MoveConstructor);
10350 }
10351}
10352
Douglas Gregore4e68d42012-02-15 19:33:52 +000010353bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010354 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010355}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010356
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010357/// \brief Mark the call operator of the given lambda closure type as "used".
10358static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
10359 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +000010360 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +000010361 Lambda->lookup(
10362 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010363 CallOperator->setReferenced();
Eli Friedman86164e82013-09-05 00:02:25 +000010364 CallOperator->markUsed(S.Context);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010365}
10366
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010367void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10368 SourceLocation CurrentLocation,
10369 CXXConversionDecl *Conv)
10370{
Manuel Klimek152b4e42013-08-22 12:12:24 +000010371 CXXRecordDecl *Lambda = Conv->getParent();
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010372
10373 // Make sure that the lambda call operator is marked used.
Manuel Klimek152b4e42013-08-22 12:12:24 +000010374 markLambdaCallOperatorUsed(*this, Lambda);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010375
Eli Friedman86164e82013-09-05 00:02:25 +000010376 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010377
Eli Friedman9a14db32012-10-18 20:14:08 +000010378 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010379 DiagnosticErrorTrap Trap(Diags);
10380
Manuel Klimek152b4e42013-08-22 12:12:24 +000010381 // Return the address of the __invoke function.
10382 DeclarationName InvokeName = &Context.Idents.get("__invoke");
10383 CXXMethodDecl *Invoke
10384 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010385 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
10386 VK_LValue, Conv->getLocation()).take();
Manuel Klimek152b4e42013-08-22 12:12:24 +000010387 assert(FunctionRef && "Can't refer to __invoke function?");
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010388 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +000010389 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010390 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010391 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010392
Manuel Klimek152b4e42013-08-22 12:12:24 +000010393 // Fill in the __invoke function with a dummy implementation. IR generation
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010394 // will fill in the actual details.
Eli Friedman86164e82013-09-05 00:02:25 +000010395 Invoke->markUsed(Context);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010396 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +000010397 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010398
10399 if (ASTMutationListener *L = getASTMutationListener()) {
10400 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010401 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010402 }
10403}
10404
10405void Sema::DefineImplicitLambdaToBlockPointerConversion(
10406 SourceLocation CurrentLocation,
10407 CXXConversionDecl *Conv)
10408{
Eli Friedman86164e82013-09-05 00:02:25 +000010409 Conv->markUsed(Context);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010410
Eli Friedman9a14db32012-10-18 20:14:08 +000010411 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010412 DiagnosticErrorTrap Trap(Diags);
10413
Douglas Gregorac1303e2012-02-22 05:02:47 +000010414 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010415 Expr *This = ActOnCXXThis(CurrentLocation).take();
10416 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010417
Eli Friedman23f02672012-03-01 04:01:32 +000010418 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10419 Conv->getLocation(),
10420 Conv, DerefThis);
10421
10422 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10423 // behavior. Note that only the general conversion function does this
10424 // (since it's unusable otherwise); in the case where we inline the
10425 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010426 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010427 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10428 CK_CopyAndAutoreleaseBlockObject,
10429 BuildBlock.get(), 0, VK_RValue);
10430
10431 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010432 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010433 Conv->setInvalidDecl();
10434 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010435 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010436
Douglas Gregorac1303e2012-02-22 05:02:47 +000010437 // Create the return statement that returns the block from the conversion
10438 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010439 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010440 if (Return.isInvalid()) {
10441 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10442 Conv->setInvalidDecl();
10443 return;
10444 }
10445
10446 // Set the body of the conversion function.
10447 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010448 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010449 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010450 Conv->getLocation()));
10451
Douglas Gregorac1303e2012-02-22 05:02:47 +000010452 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010453 if (ASTMutationListener *L = getASTMutationListener()) {
10454 L->CompletedImplicitDefinition(Conv);
10455 }
10456}
10457
Douglas Gregorf52757d2012-03-10 06:53:13 +000010458/// \brief Determine whether the given list arguments contains exactly one
10459/// "real" (non-default) argument.
10460static bool hasOneRealArgument(MultiExprArg Args) {
10461 switch (Args.size()) {
10462 case 0:
10463 return false;
10464
10465 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010466 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010467 return false;
10468
10469 // fall through
10470 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010471 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010472 }
10473
10474 return false;
10475}
10476
John McCall60d7b3a2010-08-24 06:29:42 +000010477ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010478Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010479 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010480 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010481 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010482 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010483 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010484 unsigned ConstructKind,
10485 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010486 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010487
Douglas Gregor2f599792010-04-02 18:24:57 +000010488 // C++0x [class.copy]p34:
10489 // When certain criteria are met, an implementation is allowed to
10490 // omit the copy/move construction of a class object, even if the
10491 // copy/move constructor and/or destructor for the object have
10492 // side effects. [...]
10493 // - when a temporary class object that has not been bound to a
10494 // reference (12.2) would be copied/moved to a class object
10495 // with the same cv-unqualified type, the copy/move operation
10496 // can be omitted by constructing the temporary object
10497 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010498 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010499 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010500 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010501 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010502 }
Mike Stump1eb44332009-09-09 15:08:12 +000010503
10504 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010505 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010506 IsListInitialization, RequiresZeroInit,
10507 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010508}
10509
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010510/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10511/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010512ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010513Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10514 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010515 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010516 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010517 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010518 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010519 unsigned ConstructKind,
10520 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010521 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010522 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010523 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010524 HadMultipleCandidates,
10525 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010526 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10527 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010528}
10529
John McCall68c6c9a2010-02-02 09:10:11 +000010530void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010531 if (VD->isInvalidDecl()) return;
10532
John McCall68c6c9a2010-02-02 09:10:11 +000010533 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010534 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010535 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010536 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010537
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010538 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010539 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010540 CheckDestructorAccess(VD->getLocation(), Destructor,
10541 PDiag(diag::err_access_dtor_var)
10542 << VD->getDeclName()
10543 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010544 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010545
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010546 if (!VD->hasGlobalStorage()) return;
10547
10548 // Emit warning for non-trivial dtor in global scope (a real global,
10549 // class-static, function-static).
10550 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10551
10552 // TODO: this should be re-enabled for static locals by !CXAAtExit
10553 if (!VD->isStaticLocal())
10554 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010555}
10556
Douglas Gregor39da0b82009-09-09 23:08:42 +000010557/// \brief Given a constructor and the set of arguments provided for the
10558/// constructor, convert the arguments and add any required default arguments
10559/// to form a proper call to this constructor.
10560///
10561/// \returns true if an error occurred, false otherwise.
10562bool
10563Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10564 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010565 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010566 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010567 bool AllowExplicit,
10568 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010569 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10570 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010571 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010572
10573 const FunctionProtoType *Proto
10574 = Constructor->getType()->getAs<FunctionProtoType>();
10575 assert(Proto && "Constructor without a prototype?");
10576 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010577
10578 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010579 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010580 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010581 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010582 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010583
10584 VariadicCallType CallType =
10585 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010586 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010587 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010588 Proto, 0,
10589 llvm::makeArrayRef(Args, NumArgs),
10590 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010591 CallType, AllowExplicit,
10592 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010593 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010594
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010595 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010596
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010597 CheckConstructorCall(Constructor,
10598 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10599 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010600 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010601
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010602 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010603}
10604
Anders Carlsson20d45d22009-12-12 00:32:00 +000010605static inline bool
10606CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10607 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010608 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010609 if (isa<NamespaceDecl>(DC)) {
10610 return SemaRef.Diag(FnDecl->getLocation(),
10611 diag::err_operator_new_delete_declared_in_namespace)
10612 << FnDecl->getDeclName();
10613 }
10614
10615 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010616 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010617 return SemaRef.Diag(FnDecl->getLocation(),
10618 diag::err_operator_new_delete_declared_static)
10619 << FnDecl->getDeclName();
10620 }
10621
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010622 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010623}
10624
Anders Carlsson156c78e2009-12-13 17:53:43 +000010625static inline bool
10626CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10627 CanQualType ExpectedResultType,
10628 CanQualType ExpectedFirstParamType,
10629 unsigned DependentParamTypeDiag,
10630 unsigned InvalidParamTypeDiag) {
10631 QualType ResultType =
10632 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10633
10634 // Check that the result type is not dependent.
10635 if (ResultType->isDependentType())
10636 return SemaRef.Diag(FnDecl->getLocation(),
10637 diag::err_operator_new_delete_dependent_result_type)
10638 << FnDecl->getDeclName() << ExpectedResultType;
10639
10640 // Check that the result type is what we expect.
10641 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10642 return SemaRef.Diag(FnDecl->getLocation(),
10643 diag::err_operator_new_delete_invalid_result_type)
10644 << FnDecl->getDeclName() << ExpectedResultType;
10645
10646 // A function template must have at least 2 parameters.
10647 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10648 return SemaRef.Diag(FnDecl->getLocation(),
10649 diag::err_operator_new_delete_template_too_few_parameters)
10650 << FnDecl->getDeclName();
10651
10652 // The function decl must have at least 1 parameter.
10653 if (FnDecl->getNumParams() == 0)
10654 return SemaRef.Diag(FnDecl->getLocation(),
10655 diag::err_operator_new_delete_too_few_parameters)
10656 << FnDecl->getDeclName();
10657
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010658 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010659 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10660 if (FirstParamType->isDependentType())
10661 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10662 << FnDecl->getDeclName() << ExpectedFirstParamType;
10663
10664 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010665 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010666 ExpectedFirstParamType)
10667 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10668 << FnDecl->getDeclName() << ExpectedFirstParamType;
10669
10670 return false;
10671}
10672
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010673static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010674CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010675 // C++ [basic.stc.dynamic.allocation]p1:
10676 // A program is ill-formed if an allocation function is declared in a
10677 // namespace scope other than global scope or declared static in global
10678 // scope.
10679 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10680 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010681
10682 CanQualType SizeTy =
10683 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10684
10685 // C++ [basic.stc.dynamic.allocation]p1:
10686 // The return type shall be void*. The first parameter shall have type
10687 // std::size_t.
10688 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10689 SizeTy,
10690 diag::err_operator_new_dependent_param_type,
10691 diag::err_operator_new_param_type))
10692 return true;
10693
10694 // C++ [basic.stc.dynamic.allocation]p1:
10695 // The first parameter shall not have an associated default argument.
10696 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010697 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010698 diag::err_operator_new_default_arg)
10699 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10700
10701 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010702}
10703
10704static bool
Richard Smith444d3842012-10-20 08:26:51 +000010705CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010706 // C++ [basic.stc.dynamic.deallocation]p1:
10707 // A program is ill-formed if deallocation functions are declared in a
10708 // namespace scope other than global scope or declared static in global
10709 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010710 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10711 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010712
10713 // C++ [basic.stc.dynamic.deallocation]p2:
10714 // Each deallocation function shall return void and its first parameter
10715 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010716 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10717 SemaRef.Context.VoidPtrTy,
10718 diag::err_operator_delete_dependent_param_type,
10719 diag::err_operator_delete_param_type))
10720 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010721
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010722 return false;
10723}
10724
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010725/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10726/// of this overloaded operator is well-formed. If so, returns false;
10727/// otherwise, emits appropriate diagnostics and returns true.
10728bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010729 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010730 "Expected an overloaded operator declaration");
10731
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010732 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10733
Mike Stump1eb44332009-09-09 15:08:12 +000010734 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010735 // The allocation and deallocation functions, operator new,
10736 // operator new[], operator delete and operator delete[], are
10737 // described completely in 3.7.3. The attributes and restrictions
10738 // found in the rest of this subclause do not apply to them unless
10739 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010740 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010741 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010742
Anders Carlssona3ccda52009-12-12 00:26:23 +000010743 if (Op == OO_New || Op == OO_Array_New)
10744 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010745
10746 // C++ [over.oper]p6:
10747 // An operator function shall either be a non-static member
10748 // function or be a non-member function and have at least one
10749 // parameter whose type is a class, a reference to a class, an
10750 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010751 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10752 if (MethodDecl->isStatic())
10753 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010754 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010755 } else {
10756 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010757 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10758 ParamEnd = FnDecl->param_end();
10759 Param != ParamEnd; ++Param) {
10760 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010761 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10762 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010763 ClassOrEnumParam = true;
10764 break;
10765 }
10766 }
10767
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010768 if (!ClassOrEnumParam)
10769 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010770 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010771 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010772 }
10773
10774 // C++ [over.oper]p8:
10775 // An operator function cannot have default arguments (8.3.6),
10776 // except where explicitly stated below.
10777 //
Mike Stump1eb44332009-09-09 15:08:12 +000010778 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010779 // (C++ [over.call]p1).
10780 if (Op != OO_Call) {
10781 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10782 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010783 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010784 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010785 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010786 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010787 }
10788 }
10789
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010790 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10791 { false, false, false }
10792#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10793 , { Unary, Binary, MemberOnly }
10794#include "clang/Basic/OperatorKinds.def"
10795 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010796
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010797 bool CanBeUnaryOperator = OperatorUses[Op][0];
10798 bool CanBeBinaryOperator = OperatorUses[Op][1];
10799 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010800
10801 // C++ [over.oper]p8:
10802 // [...] Operator functions cannot have more or fewer parameters
10803 // than the number required for the corresponding operator, as
10804 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010805 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010806 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010807 if (Op != OO_Call &&
10808 ((NumParams == 1 && !CanBeUnaryOperator) ||
10809 (NumParams == 2 && !CanBeBinaryOperator) ||
10810 (NumParams < 1) || (NumParams > 2))) {
10811 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010812 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010813 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010814 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010815 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010816 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010817 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010818 assert(CanBeBinaryOperator &&
10819 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010820 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010821 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010822
Chris Lattner416e46f2008-11-21 07:57:12 +000010823 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010824 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010825 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010826
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010827 // Overloaded operators other than operator() cannot be variadic.
10828 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010829 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010830 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010831 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010832 }
10833
10834 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010835 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10836 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010837 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010838 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010839 }
10840
10841 // C++ [over.inc]p1:
10842 // The user-defined function called operator++ implements the
10843 // prefix and postfix ++ operator. If this function is a member
10844 // function with no parameters, or a non-member function with one
10845 // parameter of class or enumeration type, it defines the prefix
10846 // increment operator ++ for objects of that type. If the function
10847 // is a member function with one parameter (which shall be of type
10848 // int) or a non-member function with two parameters (the second
10849 // of which shall be of type int), it defines the postfix
10850 // increment operator ++ for objects of that type.
10851 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10852 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10853 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010854 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010855 ParamIsInt = BT->getKind() == BuiltinType::Int;
10856
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010857 if (!ParamIsInt)
10858 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010859 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010860 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010861 }
10862
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010863 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010864}
Chris Lattner5a003a42008-12-17 07:09:26 +000010865
Sean Hunta6c058d2010-01-13 09:01:02 +000010866/// CheckLiteralOperatorDeclaration - Check whether the declaration
10867/// of this literal operator function is well-formed. If so, returns
10868/// false; otherwise, emits appropriate diagnostics and returns true.
10869bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010870 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010871 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10872 << FnDecl->getDeclName();
10873 return true;
10874 }
10875
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010876 if (FnDecl->isExternC()) {
10877 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10878 return true;
10879 }
10880
Sean Hunta6c058d2010-01-13 09:01:02 +000010881 bool Valid = false;
10882
Richard Smith36f5cfe2012-03-09 08:00:36 +000010883 // This might be the definition of a literal operator template.
10884 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10885 // This might be a specialization of a literal operator template.
10886 if (!TpDecl)
10887 TpDecl = FnDecl->getPrimaryTemplate();
10888
Sean Hunt216c2782010-04-07 23:11:06 +000010889 // template <char...> type operator "" name() is the only valid template
10890 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010891 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010892 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010893 // Must have only one template parameter
10894 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10895 if (Params->size() == 1) {
10896 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010897 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010898
Sean Hunt216c2782010-04-07 23:11:06 +000010899 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010900 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10901 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10902 Valid = true;
10903 }
10904 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010905 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010906 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010907 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10908
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010909 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010910
Sean Hunt30019c02010-04-07 22:57:35 +000010911 // unsigned long long int, long double, and any character type are allowed
10912 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010913 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10914 Context.hasSameType(T, Context.LongDoubleTy) ||
10915 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010916 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010917 Context.hasSameType(T, Context.Char16Ty) ||
10918 Context.hasSameType(T, Context.Char32Ty)) {
10919 if (++Param == FnDecl->param_end())
10920 Valid = true;
10921 goto FinishedParams;
10922 }
10923
Sean Hunt30019c02010-04-07 22:57:35 +000010924 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010925 const PointerType *PT = T->getAs<PointerType>();
10926 if (!PT)
10927 goto FinishedParams;
10928 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010929 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010930 goto FinishedParams;
10931 T = T.getUnqualifiedType();
10932
10933 // Move on to the second parameter;
10934 ++Param;
10935
10936 // If there is no second parameter, the first must be a const char *
10937 if (Param == FnDecl->param_end()) {
10938 if (Context.hasSameType(T, Context.CharTy))
10939 Valid = true;
10940 goto FinishedParams;
10941 }
10942
10943 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10944 // are allowed as the first parameter to a two-parameter function
10945 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010946 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010947 Context.hasSameType(T, Context.Char16Ty) ||
10948 Context.hasSameType(T, Context.Char32Ty)))
10949 goto FinishedParams;
10950
10951 // The second and final parameter must be an std::size_t
10952 T = (*Param)->getType().getUnqualifiedType();
10953 if (Context.hasSameType(T, Context.getSizeType()) &&
10954 ++Param == FnDecl->param_end())
10955 Valid = true;
10956 }
10957
10958 // FIXME: This diagnostic is absolutely terrible.
10959FinishedParams:
10960 if (!Valid) {
10961 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10962 << FnDecl->getDeclName();
10963 return true;
10964 }
10965
Richard Smitha9e88b22012-03-09 08:16:22 +000010966 // A parameter-declaration-clause containing a default argument is not
10967 // equivalent to any of the permitted forms.
10968 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10969 ParamEnd = FnDecl->param_end();
10970 Param != ParamEnd; ++Param) {
10971 if ((*Param)->hasDefaultArg()) {
10972 Diag((*Param)->getDefaultArgRange().getBegin(),
10973 diag::err_literal_operator_default_argument)
10974 << (*Param)->getDefaultArgRange();
10975 break;
10976 }
10977 }
10978
Richard Smith2fb4ae32012-03-08 02:39:21 +000010979 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010980 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10981 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010982 // C++11 [usrlit.suffix]p1:
10983 // Literal suffix identifiers that do not start with an underscore
10984 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000010985 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10986 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000010987 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010988
Sean Hunta6c058d2010-01-13 09:01:02 +000010989 return false;
10990}
10991
Douglas Gregor074149e2009-01-05 19:45:36 +000010992/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10993/// linkage specification, including the language and (if present)
10994/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10995/// the location of the language string literal, which is provided
10996/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10997/// the '{' brace. Otherwise, this linkage specification does not
10998/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010999Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11000 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000011001 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000011002 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000011003 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000011004 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011005 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000011006 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000011007 Language = LinkageSpecDecl::lang_cxx;
11008 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000011009 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000011010 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011011 }
Mike Stump1eb44332009-09-09 15:08:12 +000011012
Chris Lattnercc98eac2008-12-17 07:13:27 +000011013 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000011014
Douglas Gregor074149e2009-01-05 19:45:36 +000011015 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000011016 ExternLoc, LangLoc, Language,
11017 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011018 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000011019 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000011020 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000011021}
11022
Abramo Bagnara35f9a192010-07-30 16:47:02 +000011023/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000011024/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11025/// valid, it's the position of the closing '}' brace in a linkage
11026/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000011027Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011028 Decl *LinkageSpec,
11029 SourceLocation RBraceLoc) {
11030 if (LinkageSpec) {
11031 if (RBraceLoc.isValid()) {
11032 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11033 LSDecl->setRBraceLoc(RBraceLoc);
11034 }
Douglas Gregor074149e2009-01-05 19:45:36 +000011035 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000011036 }
Douglas Gregor074149e2009-01-05 19:45:36 +000011037 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000011038}
11039
Michael Han684aa732013-02-22 17:15:32 +000011040Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11041 AttributeList *AttrList,
11042 SourceLocation SemiLoc) {
11043 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11044 // Attribute declarations appertain to empty declaration so we handle
11045 // them here.
11046 if (AttrList)
11047 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000011048
Michael Han684aa732013-02-22 17:15:32 +000011049 CurContext->addDecl(ED);
11050 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000011051}
11052
Douglas Gregord308e622009-05-18 20:51:54 +000011053/// \brief Perform semantic analysis for the variable declaration that
11054/// occurs within a C++ catch clause, returning the newly-created
11055/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011056VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000011057 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011058 SourceLocation StartLoc,
11059 SourceLocation Loc,
11060 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000011061 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000011062 QualType ExDeclType = TInfo->getType();
11063
Sebastian Redl4b07b292008-12-22 19:15:10 +000011064 // Arrays and functions decay.
11065 if (ExDeclType->isArrayType())
11066 ExDeclType = Context.getArrayDecayedType(ExDeclType);
11067 else if (ExDeclType->isFunctionType())
11068 ExDeclType = Context.getPointerType(ExDeclType);
11069
11070 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11071 // The exception-declaration shall not denote a pointer or reference to an
11072 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011073 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000011074 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000011075 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011076 Invalid = true;
11077 }
Douglas Gregord308e622009-05-18 20:51:54 +000011078
Sebastian Redl4b07b292008-12-22 19:15:10 +000011079 QualType BaseType = ExDeclType;
11080 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000011081 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000011082 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011083 BaseType = Ptr->getPointeeType();
11084 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011085 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000011086 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011087 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011088 BaseType = Ref->getPointeeType();
11089 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000011090 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011091 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000011092 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000011093 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000011094 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011095
Mike Stump1eb44332009-09-09 15:08:12 +000011096 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000011097 RequireNonAbstractType(Loc, ExDeclType,
11098 diag::err_abstract_type_in_decl,
11099 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000011100 Invalid = true;
11101
John McCall5a180392010-07-24 00:37:23 +000011102 // Only the non-fragile NeXT runtime currently supports C++ catches
11103 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000011104 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000011105 QualType T = ExDeclType;
11106 if (const ReferenceType *RT = T->getAs<ReferenceType>())
11107 T = RT->getPointeeType();
11108
11109 if (T->isObjCObjectType()) {
11110 Diag(Loc, diag::err_objc_object_catch);
11111 Invalid = true;
11112 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000011113 // FIXME: should this be a test for macosx-fragile specifically?
11114 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000011115 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000011116 }
11117 }
11118
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011119 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000011120 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000011121 ExDecl->setExceptionVariable(true);
11122
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011123 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000011124 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000011125 Invalid = true;
11126
Douglas Gregorc41b8782011-07-06 18:14:43 +000011127 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000011128 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000011129 // Insulate this from anything else we might currently be parsing.
11130 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11131
Douglas Gregor6d182892010-03-05 23:38:39 +000011132 // C++ [except.handle]p16:
11133 // The object declared in an exception-declaration or, if the
11134 // exception-declaration does not specify a name, a temporary (12.2) is
11135 // copy-initialized (8.5) from the exception object. [...]
11136 // The object is destroyed when the handler exits, after the destruction
11137 // of any automatic objects initialized within the handler.
11138 //
11139 // We just pretend to initialize the object with itself, then make sure
11140 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000011141 QualType initType = ExDeclType;
11142
11143 InitializedEntity entity =
11144 InitializedEntity::InitializeVariable(ExDecl);
11145 InitializationKind initKind =
11146 InitializationKind::CreateCopy(Loc, SourceLocation());
11147
11148 Expr *opaqueValue =
11149 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000011150 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11151 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000011152 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000011153 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000011154 else {
11155 // If the constructor used was non-trivial, set this as the
11156 // "initializer".
11157 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
11158 if (!construct->getConstructor()->isTrivial()) {
11159 Expr *init = MaybeCreateExprWithCleanups(construct);
11160 ExDecl->setInit(init);
11161 }
11162
11163 // And make sure it's destructable.
11164 FinalizeVarWithDestructor(ExDecl, recordType);
11165 }
Douglas Gregor6d182892010-03-05 23:38:39 +000011166 }
11167 }
11168
Douglas Gregord308e622009-05-18 20:51:54 +000011169 if (Invalid)
11170 ExDecl->setInvalidDecl();
11171
11172 return ExDecl;
11173}
11174
11175/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11176/// handler.
John McCalld226f652010-08-21 09:40:31 +000011177Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000011178 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000011179 bool Invalid = D.isInvalidType();
11180
11181 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000011182 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11183 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000011184 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11185 D.getIdentifierLoc());
11186 Invalid = true;
11187 }
11188
Sebastian Redl4b07b292008-12-22 19:15:10 +000011189 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000011190 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000011191 LookupOrdinaryName,
11192 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011193 // The scope should be freshly made just for us. There is just no way
11194 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000011195 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000011196 if (PrevDecl->isTemplateParameter()) {
11197 // Maybe we will complain about the shadowed template parameter.
11198 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000011199 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011200 }
11201 }
11202
Chris Lattnereaaebc72009-04-25 08:06:05 +000011203 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000011204 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11205 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000011206 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011207 }
11208
Douglas Gregor83cb9422010-09-09 17:09:21 +000011209 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000011210 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000011211 D.getIdentifierLoc(),
11212 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000011213 if (Invalid)
11214 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000011215
Sebastian Redl4b07b292008-12-22 19:15:10 +000011216 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000011217 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000011218 PushOnScopeChains(ExDecl, S);
11219 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011220 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000011221
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000011222 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000011223 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000011224}
Anders Carlssonfb311762009-03-14 00:25:26 +000011225
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011226Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000011227 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000011228 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011229 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000011230 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000011231
Richard Smithe3f470a2012-07-11 22:37:56 +000011232 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11233 return 0;
11234
11235 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11236 AssertMessage, RParenLoc, false);
11237}
11238
11239Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11240 Expr *AssertExpr,
11241 StringLiteral *AssertMessage,
11242 SourceLocation RParenLoc,
11243 bool Failed) {
11244 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11245 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000011246 // In a static_assert-declaration, the constant-expression shall be a
11247 // constant expression that can be contextually converted to bool.
11248 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11249 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011250 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000011251
Richard Smithdaaefc52011-12-14 23:32:26 +000011252 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000011253 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011254 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000011255 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000011256 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000011257
Richard Smithe3f470a2012-07-11 22:37:56 +000011258 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000011259 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000011260 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000011261 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011262 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000011263 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000011264 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000011265 }
Anders Carlssonc3082412009-03-14 00:33:21 +000011266 }
Mike Stump1eb44332009-09-09 15:08:12 +000011267
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000011268 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000011269 AssertExpr, AssertMessage, RParenLoc,
11270 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000011271
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000011272 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000011273 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000011274}
Sebastian Redl50de12f2009-03-24 22:27:57 +000011275
Douglas Gregor1d869352010-04-07 16:53:43 +000011276/// \brief Perform semantic analysis of the given friend type declaration.
11277///
11278/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000011279FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000011280 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011281 TypeSourceInfo *TSInfo) {
11282 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11283
11284 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000011285 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000011286
Richard Smith6b130222011-10-18 21:39:00 +000011287 // C++03 [class.friend]p2:
11288 // An elaborated-type-specifier shall be used in a friend declaration
11289 // for a class.*
11290 //
11291 // * The class-key of the elaborated-type-specifier is required.
11292 if (!ActiveTemplateInstantiations.empty()) {
11293 // Do not complain about the form of friend template types during
11294 // template instantiation; we will already have complained when the
11295 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011296 } else {
11297 if (!T->isElaboratedTypeSpecifier()) {
11298 // If we evaluated the type to a record type, suggest putting
11299 // a tag in front.
11300 if (const RecordType *RT = T->getAs<RecordType>()) {
11301 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000011302
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011303 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000011304
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011305 Diag(TypeRange.getBegin(),
11306 getLangOpts().CPlusPlus11 ?
11307 diag::warn_cxx98_compat_unelaborated_friend_type :
11308 diag::ext_unelaborated_friend_type)
11309 << (unsigned) RD->getTagKind()
11310 << T
11311 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11312 InsertionText);
11313 } else {
11314 Diag(FriendLoc,
11315 getLangOpts().CPlusPlus11 ?
11316 diag::warn_cxx98_compat_nonclass_type_friend :
11317 diag::ext_nonclass_type_friend)
11318 << T
11319 << TypeRange;
11320 }
11321 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000011322 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000011323 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011324 diag::warn_cxx98_compat_enum_friend :
11325 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000011326 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000011327 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000011328 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011329
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000011330 // C++11 [class.friend]p3:
11331 // A friend declaration that does not declare a function shall have one
11332 // of the following forms:
11333 // friend elaborated-type-specifier ;
11334 // friend simple-type-specifier ;
11335 // friend typename-specifier ;
11336 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11337 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11338 }
Richard Smithd6f80da2012-09-20 01:31:00 +000011339
Douglas Gregor06245bf2010-04-07 17:57:12 +000011340 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000011341 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000011342 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000011343 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000011344}
11345
John McCall9a34edb2010-10-19 01:40:49 +000011346/// Handle a friend tag declaration where the scope specifier was
11347/// templated.
11348Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11349 unsigned TagSpec, SourceLocation TagLoc,
11350 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011351 IdentifierInfo *Name,
11352 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011353 AttributeList *Attr,
11354 MultiTemplateParamsArg TempParamLists) {
11355 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11356
11357 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011358 bool Invalid = false;
11359
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011360 if (TemplateParameterList *TemplateParams =
11361 MatchTemplateParametersToScopeSpecifier(
11362 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11363 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011364 if (TemplateParams->size() > 0) {
11365 // This is a declaration of a class template.
11366 if (Invalid)
11367 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011368
Eric Christopher4110e132011-07-21 05:34:24 +000011369 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11370 SS, Name, NameLoc, Attr,
11371 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011372 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011373 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011374 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011375 } else {
11376 // The "template<>" header is extraneous.
11377 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11378 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11379 isExplicitSpecialization = true;
11380 }
11381 }
11382
11383 if (Invalid) return 0;
11384
John McCall9a34edb2010-10-19 01:40:49 +000011385 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011386 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011387 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011388 isAllExplicitSpecializations = false;
11389 break;
11390 }
11391 }
11392
11393 // FIXME: don't ignore attributes.
11394
11395 // If it's explicit specializations all the way down, just forget
11396 // about the template header and build an appropriate non-templated
11397 // friend. TODO: for source fidelity, remember the headers.
11398 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011399 if (SS.isEmpty()) {
11400 bool Owned = false;
11401 bool IsDependent = false;
11402 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11403 Attr, AS_public,
11404 /*ModulePrivateLoc=*/SourceLocation(),
11405 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011406 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011407 /*ScopedEnumUsesClassTag=*/false,
11408 /*UnderlyingType=*/TypeResult());
11409 }
11410
Douglas Gregor2494dd02011-03-01 01:34:45 +000011411 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011412 ElaboratedTypeKeyword Keyword
11413 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011414 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011415 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011416 if (T.isNull())
11417 return 0;
11418
11419 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11420 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011421 DependentNameTypeLoc TL =
11422 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011423 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011424 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011425 TL.setNameLoc(NameLoc);
11426 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011427 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011428 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011429 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011430 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011431 }
11432
11433 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011434 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011435 Friend->setAccess(AS_public);
11436 CurContext->addDecl(Friend);
11437 return Friend;
11438 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011439
11440 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11441
11442
John McCall9a34edb2010-10-19 01:40:49 +000011443
11444 // Handle the case of a templated-scope friend class. e.g.
11445 // template <class T> class A<T>::B;
11446 // FIXME: we don't support these right now.
11447 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11448 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11449 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011450 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011451 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011452 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011453 TL.setNameLoc(NameLoc);
11454
11455 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011456 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011457 Friend->setAccess(AS_public);
11458 Friend->setUnsupportedFriend(true);
11459 CurContext->addDecl(Friend);
11460 return Friend;
11461}
11462
11463
John McCalldd4a3b02009-09-16 22:47:08 +000011464/// Handle a friend type declaration. This works in tandem with
11465/// ActOnTag.
11466///
11467/// Notes on friend class templates:
11468///
11469/// We generally treat friend class declarations as if they were
11470/// declaring a class. So, for example, the elaborated type specifier
11471/// in a friend declaration is required to obey the restrictions of a
11472/// class-head (i.e. no typedefs in the scope chain), template
11473/// parameters are required to match up with simple template-ids, &c.
11474/// However, unlike when declaring a template specialization, it's
11475/// okay to refer to a template specialization without an empty
11476/// template parameter declaration, e.g.
11477/// friend class A<T>::B<unsigned>;
11478/// We permit this as a special case; if there are any template
11479/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011480/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011481Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011482 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011483 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011484
11485 assert(DS.isFriendSpecified());
11486 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11487
John McCalldd4a3b02009-09-16 22:47:08 +000011488 // Try to convert the decl specifier to a type. This works for
11489 // friend templates because ActOnTag never produces a ClassTemplateDecl
11490 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011491 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011492 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11493 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011494 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011495 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011496
Douglas Gregor6ccab972010-12-16 01:14:37 +000011497 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11498 return 0;
11499
John McCalldd4a3b02009-09-16 22:47:08 +000011500 // This is definitely an error in C++98. It's probably meant to
11501 // be forbidden in C++0x, too, but the specification is just
11502 // poorly written.
11503 //
11504 // The problem is with declarations like the following:
11505 // template <T> friend A<T>::foo;
11506 // where deciding whether a class C is a friend or not now hinges
11507 // on whether there exists an instantiation of A that causes
11508 // 'foo' to equal C. There are restrictions on class-heads
11509 // (which we declare (by fiat) elaborated friend declarations to
11510 // be) that makes this tractable.
11511 //
11512 // FIXME: handle "template <> friend class A<T>;", which
11513 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011514 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011515 Diag(Loc, diag::err_tagless_friend_type_template)
11516 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011517 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011518 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011519
John McCall02cace72009-08-28 07:59:38 +000011520 // C++98 [class.friend]p1: A friend of a class is a function
11521 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011522 // This is fixed in DR77, which just barely didn't make the C++03
11523 // deadline. It's also a very silly restriction that seriously
11524 // affects inner classes and which nobody else seems to implement;
11525 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011526 //
11527 // But note that we could warn about it: it's always useless to
11528 // friend one of your own members (it's not, however, worthless to
11529 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011530
John McCalldd4a3b02009-09-16 22:47:08 +000011531 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011532 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011533 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011534 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011535 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011536 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011537 DS.getFriendSpecLoc());
11538 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011539 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011540
11541 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011542 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011543
John McCalldd4a3b02009-09-16 22:47:08 +000011544 D->setAccess(AS_public);
11545 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011546
John McCalld226f652010-08-21 09:40:31 +000011547 return D;
John McCall02cace72009-08-28 07:59:38 +000011548}
11549
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011550NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11551 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011552 const DeclSpec &DS = D.getDeclSpec();
11553
11554 assert(DS.isFriendSpecified());
11555 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11556
11557 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011558 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011559
11560 // C++ [class.friend]p1
11561 // A friend of a class is a function or class....
11562 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011563 // It *doesn't* see through dependent types, which is correct
11564 // according to [temp.arg.type]p3:
11565 // If a declaration acquires a function type through a
11566 // type dependent on a template-parameter and this causes
11567 // a declaration that does not use the syntactic form of a
11568 // function declarator to have a function type, the program
11569 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011570 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011571 Diag(Loc, diag::err_unexpected_friend);
11572
11573 // It might be worthwhile to try to recover by creating an
11574 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011575 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011576 }
11577
11578 // C++ [namespace.memdef]p3
11579 // - If a friend declaration in a non-local class first declares a
11580 // class or function, the friend class or function is a member
11581 // of the innermost enclosing namespace.
11582 // - The name of the friend is not found by simple name lookup
11583 // until a matching declaration is provided in that namespace
11584 // scope (either before or after the class declaration granting
11585 // friendship).
11586 // - If a friend function is called, its name may be found by the
11587 // name lookup that considers functions from namespaces and
11588 // classes associated with the types of the function arguments.
11589 // - When looking for a prior declaration of a class or a function
11590 // declared as a friend, scopes outside the innermost enclosing
11591 // namespace scope are not considered.
11592
John McCall337ec3d2010-10-12 23:13:28 +000011593 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011594 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11595 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011596 assert(Name);
11597
Douglas Gregor6ccab972010-12-16 01:14:37 +000011598 // Check for unexpanded parameter packs.
11599 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11600 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11601 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11602 return 0;
11603
John McCall67d1a672009-08-06 02:15:43 +000011604 // The context we found the declaration in, or in which we should
11605 // create the declaration.
11606 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011607 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011608 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011609 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011610
Richard Smith4e9686b2013-08-09 04:35:01 +000011611 // There are five cases here.
11612 // - There's no scope specifier and we're in a local class. Only look
11613 // for functions declared in the immediately-enclosing block scope.
11614 // We recover from invalid scope qualifiers as if they just weren't there.
11615 FunctionDecl *FunctionContainingLocalClass = 0;
11616 if ((SS.isInvalid() || !SS.isSet()) &&
11617 (FunctionContainingLocalClass =
11618 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11619 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000011620 // If a friend declaration appears in a local class and the name
11621 // specified is an unqualified name, a prior declaration is
11622 // looked up without considering scopes that are outside the
11623 // innermost enclosing non-class scope. For a friend function
11624 // declaration, if there is no prior declaration, the program is
11625 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000011626
11627 // Find the innermost enclosing non-class scope. This is the block
11628 // scope containing the local class definition (or for a nested class,
11629 // the outer local class).
11630 DCScope = S->getFnParent();
11631
11632 // Look up the function name in the scope.
11633 Previous.clear(LookupLocalFriendName);
11634 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11635
11636 if (!Previous.empty()) {
11637 // All possible previous declarations must have the same context:
11638 // either they were declared at block scope or they are members of
11639 // one of the enclosing local classes.
11640 DC = Previous.getRepresentativeDecl()->getDeclContext();
11641 } else {
11642 // This is ill-formed, but provide the context that we would have
11643 // declared the function in, if we were permitted to, for error recovery.
11644 DC = FunctionContainingLocalClass;
11645 }
Richard Smitha41c97a2013-09-20 01:15:31 +000011646 adjustContextForLocalExternDecl(DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011647
11648 // C++ [class.friend]p6:
11649 // A function can be defined in a friend declaration of a class if and
11650 // only if the class is a non-local class (9.8), the function name is
11651 // unqualified, and the function has namespace scope.
11652 if (D.isFunctionDefinition()) {
11653 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11654 }
11655
11656 // - There's no scope specifier, in which case we just go to the
11657 // appropriate scope and look for a function or function template
11658 // there as appropriate.
11659 } else if (SS.isInvalid() || !SS.isSet()) {
11660 // C++11 [namespace.memdef]p3:
11661 // If the name in a friend declaration is neither qualified nor
11662 // a template-id and the declaration is a function or an
11663 // elaborated-type-specifier, the lookup to determine whether
11664 // the entity has been previously declared shall not consider
11665 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000011666 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011667
John McCall29ae6e52010-10-13 05:45:15 +000011668 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011669 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011670
Rafael Espindola11dc6342013-04-25 20:12:36 +000011671 // Skip class contexts. If someone can cite chapter and verse
11672 // for this behavior, that would be nice --- it's what GCC and
11673 // EDG do, and it seems like a reasonable intent, but the spec
11674 // really only says that checks for unqualified existing
11675 // declarations should stop at the nearest enclosing namespace,
11676 // not that they should only consider the nearest enclosing
11677 // namespace.
11678 while (DC->isRecord())
11679 DC = DC->getParent();
11680
11681 DeclContext *LookupDC = DC;
11682 while (LookupDC->isTransparentContext())
11683 LookupDC = LookupDC->getParent();
11684
11685 while (true) {
11686 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011687
Rafael Espindola11dc6342013-04-25 20:12:36 +000011688 if (!Previous.empty()) {
11689 DC = LookupDC;
11690 break;
John McCall8a407372010-10-14 22:22:28 +000011691 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011692
11693 if (isTemplateId) {
11694 if (isa<TranslationUnitDecl>(LookupDC)) break;
11695 } else {
11696 if (LookupDC->isFileContext()) break;
11697 }
11698 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011699 }
11700
John McCall380aaa42010-10-13 06:22:15 +000011701 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011702
John McCall337ec3d2010-10-12 23:13:28 +000011703 // - There's a non-dependent scope specifier, in which case we
11704 // compute it and do a previous lookup there for a function
11705 // or function template.
11706 } else if (!SS.getScopeRep()->isDependent()) {
11707 DC = computeDeclContext(SS);
11708 if (!DC) return 0;
11709
11710 if (RequireCompleteDeclContext(SS, DC)) return 0;
11711
11712 LookupQualifiedName(Previous, DC);
11713
11714 // Ignore things found implicitly in the wrong scope.
11715 // TODO: better diagnostics for this case. Suggesting the right
11716 // qualified scope would be nice...
11717 LookupResult::Filter F = Previous.makeFilter();
11718 while (F.hasNext()) {
11719 NamedDecl *D = F.next();
11720 if (!DC->InEnclosingNamespaceSetOf(
11721 D->getDeclContext()->getRedeclContext()))
11722 F.erase();
11723 }
11724 F.done();
11725
11726 if (Previous.empty()) {
11727 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011728 Diag(Loc, diag::err_qualified_friend_not_found)
11729 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011730 return 0;
11731 }
11732
11733 // C++ [class.friend]p1: A friend of a class is a function or
11734 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011735 if (DC->Equals(CurContext))
11736 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011737 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011738 diag::warn_cxx98_compat_friend_is_member :
11739 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011740
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011741 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011742 // C++ [class.friend]p6:
11743 // A function can be defined in a friend declaration of a class if and
11744 // only if the class is a non-local class (9.8), the function name is
11745 // unqualified, and the function has namespace scope.
11746 SemaDiagnosticBuilder DB
11747 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11748
11749 DB << SS.getScopeRep();
11750 if (DC->isFileContext())
11751 DB << FixItHint::CreateRemoval(SS.getRange());
11752 SS.clear();
11753 }
John McCall337ec3d2010-10-12 23:13:28 +000011754
11755 // - There's a scope specifier that does not match any template
11756 // parameter lists, in which case we use some arbitrary context,
11757 // create a method or method template, and wait for instantiation.
11758 // - There's a scope specifier that does match some template
11759 // parameter lists, which we don't handle right now.
11760 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011761 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011762 // C++ [class.friend]p6:
11763 // A function can be defined in a friend declaration of a class if and
11764 // only if the class is a non-local class (9.8), the function name is
11765 // unqualified, and the function has namespace scope.
11766 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11767 << SS.getScopeRep();
11768 }
11769
John McCall337ec3d2010-10-12 23:13:28 +000011770 DC = CurContext;
11771 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011772 }
Douglas Gregor883af832011-10-10 01:11:59 +000011773
John McCall29ae6e52010-10-13 05:45:15 +000011774 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011775 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011776 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11777 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11778 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011779 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011780 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11781 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011782 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011783 }
John McCall67d1a672009-08-06 02:15:43 +000011784 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011785
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011786 // FIXME: This is an egregious hack to cope with cases where the scope stack
11787 // does not contain the declaration context, i.e., in an out-of-line
11788 // definition of a class.
11789 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11790 if (!DCScope) {
11791 FakeDCScope.setEntity(DC);
11792 DCScope = &FakeDCScope;
11793 }
Richard Smith4e9686b2013-08-09 04:35:01 +000011794
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011795 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011796 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011797 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011798 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011799
Douglas Gregor182ddf02009-09-28 00:08:27 +000011800 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011801
Richard Smith4e9686b2013-08-09 04:35:01 +000011802 // If we performed typo correction, we might have added a scope specifier
11803 // and changed the decl context.
11804 DC = ND->getDeclContext();
11805
John McCallab88d972009-08-31 22:39:49 +000011806 // Add the function declaration to the appropriate lookup tables,
11807 // adjusting the redeclarations list as necessary. We don't
11808 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011809 //
John McCallab88d972009-08-31 22:39:49 +000011810 // Also update the scope-based lookup if the target context's
11811 // lookup context is in lexical scope.
11812 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011813 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011814 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011815 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011816 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011817 }
John McCall02cace72009-08-28 07:59:38 +000011818
11819 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011820 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011821 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011822 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011823 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011824
John McCall1f2e1a92012-08-10 03:15:35 +000011825 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011826 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011827 } else {
11828 if (DC->isRecord()) CheckFriendAccess(ND);
11829
John McCall6102ca12010-10-16 06:59:13 +000011830 FunctionDecl *FD;
11831 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11832 FD = FTD->getTemplatedDecl();
11833 else
11834 FD = cast<FunctionDecl>(ND);
11835
David Majnemerf6a144f2013-06-25 23:09:30 +000011836 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11837 // default argument expression, that declaration shall be a definition
11838 // and shall be the only declaration of the function or function
11839 // template in the translation unit.
11840 if (functionDeclHasDefaultArgument(FD)) {
11841 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11842 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11843 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11844 } else if (!D.isFunctionDefinition())
11845 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11846 }
11847
John McCall6102ca12010-10-16 06:59:13 +000011848 // Mark templated-scope function declarations as unsupported.
11849 if (FD->getNumTemplateParameterLists())
11850 FrD->setUnsupportedFriend(true);
11851 }
John McCall337ec3d2010-10-12 23:13:28 +000011852
John McCalld226f652010-08-21 09:40:31 +000011853 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011854}
11855
John McCalld226f652010-08-21 09:40:31 +000011856void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11857 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011858
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011859 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011860 if (!Fn) {
11861 Diag(DelLoc, diag::err_deleted_non_function);
11862 return;
11863 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011864
Douglas Gregoref96ee02012-01-14 16:38:05 +000011865 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011866 // Don't consider the implicit declaration we generate for explicit
11867 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011868 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11869 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011870 Diag(DelLoc, diag::err_deleted_decl_not_first);
11871 Diag(Prev->getLocation(), diag::note_previous_declaration);
11872 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011873 // If the declaration wasn't the first, we delete the function anyway for
11874 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011875 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011876 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011877
11878 if (Fn->isDeleted())
11879 return;
11880
11881 // See if we're deleting a function which is already known to override a
11882 // non-deleted virtual function.
11883 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11884 bool IssuedDiagnostic = false;
11885 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11886 E = MD->end_overridden_methods();
11887 I != E; ++I) {
11888 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11889 if (!IssuedDiagnostic) {
11890 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11891 IssuedDiagnostic = true;
11892 }
11893 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11894 }
11895 }
11896 }
11897
Sean Hunt10620eb2011-05-06 20:44:56 +000011898 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011899}
Sebastian Redl13e88542009-04-27 21:33:24 +000011900
Sean Hunte4246a62011-05-12 06:15:49 +000011901void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011902 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011903
11904 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011905 if (MD->getParent()->isDependentType()) {
11906 MD->setDefaulted();
11907 MD->setExplicitlyDefaulted();
11908 return;
11909 }
11910
Sean Hunte4246a62011-05-12 06:15:49 +000011911 CXXSpecialMember Member = getSpecialMember(MD);
11912 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011913 if (!MD->isInvalidDecl())
11914 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000011915 return;
11916 }
11917
11918 MD->setDefaulted();
11919 MD->setExplicitlyDefaulted();
11920
Sean Huntcd10dec2011-05-23 23:14:04 +000011921 // If this definition appears within the record, do the checking when
11922 // the record is complete.
11923 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011924 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011925 // Find the uninstantiated declaration that actually had the '= default'
11926 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011927 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011928
Richard Smith12fef492013-03-27 00:22:47 +000011929 // If the method was defaulted on its first declaration, we will have
11930 // already performed the checking in CheckCompletedCXXClass. Such a
11931 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011932 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011933 return;
11934
Richard Smithb9d0b762012-07-27 04:22:15 +000011935 CheckExplicitlyDefaultedSpecialMember(MD);
11936
Richard Smith1d28caf2012-12-11 01:14:52 +000011937 // The exception specification is needed because we are defining the
11938 // function.
11939 ResolveExceptionSpec(DefaultLoc,
11940 MD->getType()->castAs<FunctionProtoType>());
11941
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011942 if (MD->isInvalidDecl())
11943 return;
11944
Sean Hunte4246a62011-05-12 06:15:49 +000011945 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011946 case CXXDefaultConstructor:
11947 DefineImplicitDefaultConstructor(DefaultLoc,
11948 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000011949 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011950 case CXXCopyConstructor:
11951 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000011952 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011953 case CXXCopyAssignment:
11954 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000011955 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011956 case CXXDestructor:
11957 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000011958 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011959 case CXXMoveConstructor:
11960 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000011961 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011962 case CXXMoveAssignment:
11963 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011964 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011965 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011966 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011967 }
11968 } else {
11969 Diag(DefaultLoc, diag::err_default_special_members);
11970 }
11971}
11972
Sebastian Redl13e88542009-04-27 21:33:24 +000011973static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011974 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011975 Stmt *SubStmt = *CI;
11976 if (!SubStmt)
11977 continue;
11978 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011979 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011980 diag::err_return_in_constructor_handler);
11981 if (!isa<Expr>(SubStmt))
11982 SearchForReturnInStmt(Self, SubStmt);
11983 }
11984}
11985
11986void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11987 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11988 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11989 SearchForReturnInStmt(*this, Handler);
11990 }
11991}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011992
David Blaikie299adab2013-01-18 23:03:15 +000011993bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011994 const CXXMethodDecl *Old) {
11995 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11996 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11997
11998 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11999
12000 // If the calling conventions match, everything is fine
12001 if (NewCC == OldCC)
12002 return false;
12003
Reid Kleckneref072032013-08-27 23:08:25 +000012004 Diag(New->getLocation(),
12005 diag::err_conflicting_overriding_cc_attributes)
12006 << New->getDeclName() << New->getType() << Old->getType();
12007 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12008 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000012009}
12010
Mike Stump1eb44332009-09-09 15:08:12 +000012011bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012012 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000012013 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
12014 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012015
Chandler Carruth73857792010-02-15 11:53:20 +000012016 if (Context.hasSameType(NewTy, OldTy) ||
12017 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012018 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000012019
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012020 // Check if the return types are covariant
12021 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000012022
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012023 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012024 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12025 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012026 NewClassTy = NewPT->getPointeeType();
12027 OldClassTy = OldPT->getPointeeType();
12028 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012029 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12030 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12031 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12032 NewClassTy = NewRT->getPointeeType();
12033 OldClassTy = OldRT->getPointeeType();
12034 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012035 }
12036 }
Mike Stump1eb44332009-09-09 15:08:12 +000012037
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012038 // The return types aren't either both pointers or references to a class type.
12039 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000012040 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012041 diag::err_different_return_type_for_overriding_virtual_function)
12042 << New->getDeclName() << NewTy << OldTy;
12043 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000012044
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012045 return true;
12046 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012047
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012048 // C++ [class.virtual]p6:
12049 // If the return type of D::f differs from the return type of B::f, the
12050 // class type in the return type of D::f shall be complete at the point of
12051 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000012052 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12053 if (!RT->isBeingDefined() &&
12054 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000012055 diag::err_covariant_return_incomplete,
12056 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012057 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000012058 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000012059
Douglas Gregora4923eb2009-11-16 21:35:15 +000012060 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012061 // Check if the new class derives from the old class.
12062 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12063 Diag(New->getLocation(),
12064 diag::err_covariant_return_not_derived)
12065 << New->getDeclName() << NewTy << OldTy;
12066 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12067 return true;
12068 }
Mike Stump1eb44332009-09-09 15:08:12 +000012069
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012070 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000012071 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000012072 diag::err_covariant_return_inaccessible_base,
12073 diag::err_covariant_return_ambiguous_derived_to_base_conv,
12074 // FIXME: Should this point to the return type?
12075 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000012076 // FIXME: this note won't trigger for delayed access control
12077 // diagnostics, and it's impossible to get an undelayed error
12078 // here from access control during the original parse because
12079 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012080 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12081 return true;
12082 }
12083 }
Mike Stump1eb44332009-09-09 15:08:12 +000012084
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012085 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000012086 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012087 Diag(New->getLocation(),
12088 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012089 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012090 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12091 return true;
12092 };
Mike Stump1eb44332009-09-09 15:08:12 +000012093
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012094
12095 // The new class type must have the same or less qualifiers as the old type.
12096 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12097 Diag(New->getLocation(),
12098 diag::err_covariant_return_type_class_type_more_qualified)
12099 << New->getDeclName() << NewTy << OldTy;
12100 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12101 return true;
12102 };
Mike Stump1eb44332009-09-09 15:08:12 +000012103
Anders Carlssonc3a68b22009-05-14 19:52:19 +000012104 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000012105}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012106
Douglas Gregor4ba31362009-12-01 17:24:26 +000012107/// \brief Mark the given method pure.
12108///
12109/// \param Method the method to be marked pure.
12110///
12111/// \param InitRange the source range that covers the "0" initializer.
12112bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000012113 SourceLocation EndLoc = InitRange.getEnd();
12114 if (EndLoc.isValid())
12115 Method->setRangeEnd(EndLoc);
12116
Douglas Gregor4ba31362009-12-01 17:24:26 +000012117 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12118 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000012119 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000012120 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000012121
12122 if (!Method->isInvalidDecl())
12123 Diag(Method->getLocation(), diag::err_non_virtual_pure)
12124 << Method->getDeclName() << InitRange;
12125 return true;
12126}
12127
Douglas Gregor552e2992012-02-21 02:22:07 +000012128/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012129static bool isStaticDataMember(const Decl *D) {
12130 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12131 return Var->isStaticDataMember();
12132
12133 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000012134}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012135
John McCall731ad842009-12-19 09:28:58 +000012136/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12137/// an initializer for the out-of-line declaration 'Dcl'. The scope
12138/// is a fresh scope pushed for just this purpose.
12139///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012140/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12141/// static data member of class X, names should be looked up in the scope of
12142/// class X.
John McCalld226f652010-08-21 09:40:31 +000012143void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012144 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012145 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012146
John McCall731ad842009-12-19 09:28:58 +000012147 // We should only get called for declarations with scope specifiers, like:
12148 // int foo::bar;
12149 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012150 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000012151
12152 // If we are parsing the initializer for a static data member, push a
12153 // new expression evaluation context that is associated with this static
12154 // data member.
12155 if (isStaticDataMember(D))
12156 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012157}
12158
12159/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000012160/// initializer for the out-of-line declaration 'D'.
12161void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012162 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000012163 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012164
Douglas Gregor552e2992012-02-21 02:22:07 +000012165 if (isStaticDataMember(D))
12166 PopExpressionEvaluationContext();
12167
John McCall731ad842009-12-19 09:28:58 +000012168 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000012169 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000012170}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012171
12172/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12173/// C++ if/switch/while/for statement.
12174/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000012175DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012176 // C++ 6.4p2:
12177 // The declarator shall not specify a function or an array.
12178 // The type-specifier-seq shall not contain typedef and shall not declare a
12179 // new class or enumeration.
12180 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12181 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012182
12183 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000012184 if (!Dcl)
12185 return true;
12186
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000012187 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12188 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012189 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000012190 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012191 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012192
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000012193 return Dcl;
12194}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012195
Douglas Gregordfe65432011-07-28 19:11:31 +000012196void Sema::LoadExternalVTableUses() {
12197 if (!ExternalSource)
12198 return;
12199
12200 SmallVector<ExternalVTableUse, 4> VTables;
12201 ExternalSource->ReadUsedVTables(VTables);
12202 SmallVector<VTableUse, 4> NewUses;
12203 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12204 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12205 = VTablesUsed.find(VTables[I].Record);
12206 // Even if a definition wasn't required before, it may be required now.
12207 if (Pos != VTablesUsed.end()) {
12208 if (!Pos->second && VTables[I].DefinitionRequired)
12209 Pos->second = true;
12210 continue;
12211 }
12212
12213 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12214 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12215 }
12216
12217 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12218}
12219
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012220void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12221 bool DefinitionRequired) {
12222 // Ignore any vtable uses in unevaluated operands or for classes that do
12223 // not have a vtable.
12224 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000012225 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000012226 return;
12227
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012228 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000012229 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012230 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12231 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12232 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12233 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000012234 // If we already had an entry, check to see if we are promoting this vtable
12235 // to required a definition. If so, we need to reappend to the VTableUses
12236 // list, since we may have already processed the first entry.
12237 if (DefinitionRequired && !Pos.first->second) {
12238 Pos.first->second = true;
12239 } else {
12240 // Otherwise, we can early exit.
12241 return;
12242 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012243 }
12244
12245 // Local classes need to have their virtual members marked
12246 // immediately. For all other classes, we mark their virtual members
12247 // at the end of the translation unit.
12248 if (Class->isLocalClass())
12249 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000012250 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012251 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000012252}
12253
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012254bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000012255 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012256 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000012257 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000012258
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012259 // Note: The VTableUses vector could grow as a result of marking
12260 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000012261 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012262 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000012263 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012264 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000012265 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012266 if (!Class)
12267 continue;
12268
12269 SourceLocation Loc = VTableUses[I].second;
12270
Richard Smithb9d0b762012-07-27 04:22:15 +000012271 bool DefineVTable = true;
12272
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012273 // If this class has a key function, but that key function is
12274 // defined in another translation unit, we don't need to emit the
12275 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000012276 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000012277 if (KeyFunction && !KeyFunction->hasBody()) {
Rafael Espindolafc218132013-08-26 23:23:21 +000012278 // The key function is in another translation unit.
12279 DefineVTable = false;
12280 TemplateSpecializationKind TSK =
12281 KeyFunction->getTemplateSpecializationKind();
12282 assert(TSK != TSK_ExplicitInstantiationDefinition &&
12283 TSK != TSK_ImplicitInstantiation &&
12284 "Instantiations don't have key functions");
12285 (void)TSK;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012286 } else if (!KeyFunction) {
12287 // If we have a class with no key function that is the subject
12288 // of an explicit instantiation declaration, suppress the
12289 // vtable; it will live with the explicit instantiation
12290 // definition.
12291 bool IsExplicitInstantiationDeclaration
12292 = Class->getTemplateSpecializationKind()
12293 == TSK_ExplicitInstantiationDeclaration;
12294 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12295 REnd = Class->redecls_end();
12296 R != REnd; ++R) {
12297 TemplateSpecializationKind TSK
12298 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12299 if (TSK == TSK_ExplicitInstantiationDeclaration)
12300 IsExplicitInstantiationDeclaration = true;
12301 else if (TSK == TSK_ExplicitInstantiationDefinition) {
12302 IsExplicitInstantiationDeclaration = false;
12303 break;
12304 }
12305 }
12306
12307 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000012308 DefineVTable = false;
12309 }
12310
12311 // The exception specifications for all virtual members may be needed even
12312 // if we are not providing an authoritative form of the vtable in this TU.
12313 // We may choose to emit it available_externally anyway.
12314 if (!DefineVTable) {
12315 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12316 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012317 }
12318
12319 // Mark all of the virtual members of this class as referenced, so
12320 // that we can build a vtable. Then, tell the AST consumer that a
12321 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000012322 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012323 MarkVirtualMembersReferenced(Loc, Class);
12324 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12325 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12326
12327 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000012328 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012329 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000012330 const FunctionDecl *KeyFunctionDef = 0;
12331 if (!KeyFunction ||
12332 (KeyFunction->hasBody(KeyFunctionDef) &&
12333 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012334 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12335 TSK_ExplicitInstantiationDefinition
12336 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12337 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012338 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012339 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012340 VTableUses.clear();
12341
Douglas Gregor78844032011-04-22 22:25:37 +000012342 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012343}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012344
Richard Smithb9d0b762012-07-27 04:22:15 +000012345void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12346 const CXXRecordDecl *RD) {
12347 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12348 E = RD->method_end(); I != E; ++I)
12349 if ((*I)->isVirtual() && !(*I)->isPure())
12350 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12351}
12352
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012353void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12354 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012355 // Mark all functions which will appear in RD's vtable as used.
12356 CXXFinalOverriderMap FinalOverriders;
12357 RD->getFinalOverriders(FinalOverriders);
12358 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12359 E = FinalOverriders.end();
12360 I != E; ++I) {
12361 for (OverridingMethods::const_iterator OI = I->second.begin(),
12362 OE = I->second.end();
12363 OI != OE; ++OI) {
12364 assert(OI->second.size() > 0 && "no final overrider");
12365 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012366
Richard Smithff817f72012-07-07 06:59:51 +000012367 // C++ [basic.def.odr]p2:
12368 // [...] A virtual member function is used if it is not pure. [...]
12369 if (!Overrider->isPure())
12370 MarkFunctionReferenced(Loc, Overrider);
12371 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012372 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012373
12374 // Only classes that have virtual bases need a VTT.
12375 if (RD->getNumVBases() == 0)
12376 return;
12377
12378 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12379 e = RD->bases_end(); i != e; ++i) {
12380 const CXXRecordDecl *Base =
12381 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012382 if (Base->getNumVBases() == 0)
12383 continue;
12384 MarkVirtualMembersReferenced(Loc, Base);
12385 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012386}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012387
12388/// SetIvarInitializers - This routine builds initialization ASTs for the
12389/// Objective-C implementation whose ivars need be initialized.
12390void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012391 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012392 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012393 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012394 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012395 CollectIvarsToConstructOrDestruct(OID, ivars);
12396 if (ivars.empty())
12397 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012398 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012399 for (unsigned i = 0; i < ivars.size(); i++) {
12400 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012401 if (Field->isInvalidDecl())
12402 continue;
12403
Sean Huntcbb67482011-01-08 20:30:50 +000012404 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012405 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12406 InitializationKind InitKind =
12407 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012408
12409 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12410 ExprResult MemberInit =
12411 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012412 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012413 // Note, MemberInit could actually come back empty if no initialization
12414 // is required (e.g., because it would call a trivial default constructor)
12415 if (!MemberInit.get() || MemberInit.isInvalid())
12416 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012417
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012418 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012419 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12420 SourceLocation(),
12421 MemberInit.takeAs<Expr>(),
12422 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012423 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012424
12425 // Be sure that the destructor is accessible and is marked as referenced.
12426 if (const RecordType *RecordTy
12427 = Context.getBaseElementType(Field->getType())
12428 ->getAs<RecordType>()) {
12429 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012430 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012431 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012432 CheckDestructorAccess(Field->getLocation(), Destructor,
12433 PDiag(diag::err_access_dtor_ivar)
12434 << Context.getBaseElementType(Field->getType()));
12435 }
12436 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012437 }
12438 ObjCImplementation->setIvarInitializers(Context,
12439 AllToInit.data(), AllToInit.size());
12440 }
12441}
Sean Huntfe57eef2011-05-04 05:57:24 +000012442
Sean Huntebcbe1d2011-05-04 23:29:54 +000012443static
12444void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12445 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12446 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12447 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12448 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012449 if (Ctor->isInvalidDecl())
12450 return;
12451
Richard Smitha8eaf002012-08-23 06:16:52 +000012452 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12453
12454 // Target may not be determinable yet, for instance if this is a dependent
12455 // call in an uninstantiated template.
12456 if (Target) {
12457 const FunctionDecl *FNTarget = 0;
12458 (void)Target->hasBody(FNTarget);
12459 Target = const_cast<CXXConstructorDecl*>(
12460 cast_or_null<CXXConstructorDecl>(FNTarget));
12461 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012462
12463 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12464 // Avoid dereferencing a null pointer here.
12465 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12466
12467 if (!Current.insert(Canonical))
12468 return;
12469
12470 // We know that beyond here, we aren't chaining into a cycle.
12471 if (!Target || !Target->isDelegatingConstructor() ||
12472 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012473 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012474 Current.clear();
12475 // We've hit a cycle.
12476 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12477 Current.count(TCanonical)) {
12478 // If we haven't diagnosed this cycle yet, do so now.
12479 if (!Invalid.count(TCanonical)) {
12480 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012481 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012482 << Ctor;
12483
Richard Smitha8eaf002012-08-23 06:16:52 +000012484 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012485 if (TCanonical != Canonical)
12486 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12487
12488 CXXConstructorDecl *C = Target;
12489 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012490 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012491 (void)C->getTargetConstructor()->hasBody(FNTarget);
12492 assert(FNTarget && "Ctor cycle through bodiless function");
12493
Richard Smitha8eaf002012-08-23 06:16:52 +000012494 C = const_cast<CXXConstructorDecl*>(
12495 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012496 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12497 }
12498 }
12499
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012500 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012501 Current.clear();
12502 } else {
12503 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12504 }
12505}
12506
12507
Sean Huntfe57eef2011-05-04 05:57:24 +000012508void Sema::CheckDelegatingCtorCycles() {
12509 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12510
Douglas Gregor0129b562011-07-27 21:57:17 +000012511 for (DelegatingCtorDeclsType::iterator
12512 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012513 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012514 I != E; ++I)
12515 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012516
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012517 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12518 CE = Invalid.end();
12519 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012520 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012521}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012522
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012523namespace {
12524 /// \brief AST visitor that finds references to the 'this' expression.
12525 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12526 Sema &S;
12527
12528 public:
12529 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12530
12531 bool VisitCXXThisExpr(CXXThisExpr *E) {
12532 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12533 << E->isImplicit();
12534 return false;
12535 }
12536 };
12537}
12538
12539bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12540 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12541 if (!TSInfo)
12542 return false;
12543
12544 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012545 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012546 if (!ProtoTL)
12547 return false;
12548
12549 // C++11 [expr.prim.general]p3:
12550 // [The expression this] shall not appear before the optional
12551 // cv-qualifier-seq and it shall not appear within the declaration of a
12552 // static member function (although its type and value category are defined
12553 // within a static member function as they are within a non-static member
12554 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012555 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012556 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012557 FindCXXThisExpr Finder(*this);
12558
12559 // If the return type came after the cv-qualifier-seq, check it now.
12560 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012561 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012562 return true;
12563
12564 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012565 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12566 return true;
12567
12568 return checkThisInStaticMemberFunctionAttributes(Method);
12569}
12570
12571bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12572 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12573 if (!TSInfo)
12574 return false;
12575
12576 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012577 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012578 if (!ProtoTL)
12579 return false;
12580
David Blaikie39e6ab42013-02-18 22:06:02 +000012581 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012582 FindCXXThisExpr Finder(*this);
12583
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012584 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012585 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012586 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012587 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012588 case EST_DynamicNone:
12589 case EST_MSAny:
12590 case EST_None:
12591 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012592
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012593 case EST_ComputedNoexcept:
12594 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12595 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012596
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012597 case EST_Dynamic:
12598 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012599 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012600 E != EEnd; ++E) {
12601 if (!Finder.TraverseType(*E))
12602 return true;
12603 }
12604 break;
12605 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012606
12607 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012608}
12609
12610bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12611 FindCXXThisExpr Finder(*this);
12612
12613 // Check attributes.
12614 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12615 A != AEnd; ++A) {
12616 // FIXME: This should be emitted by tblgen.
12617 Expr *Arg = 0;
12618 ArrayRef<Expr *> Args;
12619 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12620 Arg = G->getArg();
12621 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12622 Arg = G->getArg();
12623 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12624 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12625 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12626 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12627 else if (ExclusiveLockFunctionAttr *ELF
12628 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12629 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12630 else if (SharedLockFunctionAttr *SLF
12631 = dyn_cast<SharedLockFunctionAttr>(*A))
12632 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12633 else if (ExclusiveTrylockFunctionAttr *ETLF
12634 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12635 Arg = ETLF->getSuccessValue();
12636 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12637 } else if (SharedTrylockFunctionAttr *STLF
12638 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12639 Arg = STLF->getSuccessValue();
12640 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12641 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12642 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12643 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12644 Arg = LR->getArg();
12645 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12646 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12647 else if (ExclusiveLocksRequiredAttr *ELR
12648 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12649 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12650 else if (SharedLocksRequiredAttr *SLR
12651 = dyn_cast<SharedLocksRequiredAttr>(*A))
12652 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12653
12654 if (Arg && !Finder.TraverseStmt(Arg))
12655 return true;
12656
12657 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12658 if (!Finder.TraverseStmt(Args[I]))
12659 return true;
12660 }
12661 }
12662
12663 return false;
12664}
12665
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012666void
12667Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12668 ArrayRef<ParsedType> DynamicExceptions,
12669 ArrayRef<SourceRange> DynamicExceptionRanges,
12670 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012671 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012672 FunctionProtoType::ExtProtoInfo &EPI) {
12673 Exceptions.clear();
12674 EPI.ExceptionSpecType = EST;
12675 if (EST == EST_Dynamic) {
12676 Exceptions.reserve(DynamicExceptions.size());
12677 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12678 // FIXME: Preserve type source info.
12679 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12680
12681 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12682 collectUnexpandedParameterPacks(ET, Unexpanded);
12683 if (!Unexpanded.empty()) {
12684 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12685 UPPC_ExceptionType,
12686 Unexpanded);
12687 continue;
12688 }
12689
12690 // Check that the type is valid for an exception spec, and
12691 // drop it if not.
12692 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12693 Exceptions.push_back(ET);
12694 }
12695 EPI.NumExceptions = Exceptions.size();
12696 EPI.Exceptions = Exceptions.data();
12697 return;
12698 }
12699
12700 if (EST == EST_ComputedNoexcept) {
12701 // If an error occurred, there's no expression here.
12702 if (NoexceptExpr) {
12703 assert((NoexceptExpr->isTypeDependent() ||
12704 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12705 Context.BoolTy) &&
12706 "Parser should have made sure that the expression is boolean");
12707 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12708 EPI.ExceptionSpecType = EST_BasicNoexcept;
12709 return;
12710 }
12711
12712 if (!NoexceptExpr->isValueDependent())
12713 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012714 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012715 /*AllowFold*/ false).take();
12716 EPI.NoexceptExpr = NoexceptExpr;
12717 }
12718 return;
12719 }
12720}
12721
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012722/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12723Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12724 // Implicitly declared functions (e.g. copy constructors) are
12725 // __host__ __device__
12726 if (D->isImplicit())
12727 return CFT_HostDevice;
12728
12729 if (D->hasAttr<CUDAGlobalAttr>())
12730 return CFT_Global;
12731
12732 if (D->hasAttr<CUDADeviceAttr>()) {
12733 if (D->hasAttr<CUDAHostAttr>())
12734 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012735 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012736 }
12737
12738 return CFT_Host;
12739}
12740
12741bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12742 CUDAFunctionTarget CalleeTarget) {
12743 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12744 // Callable from the device only."
12745 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12746 return true;
12747
12748 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12749 // Callable from the host only."
12750 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12751 // Callable from the host only."
12752 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12753 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12754 return true;
12755
12756 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12757 return true;
12758
12759 return false;
12760}
John McCall76da55d2013-04-16 07:28:30 +000012761
12762/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12763///
12764MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12765 SourceLocation DeclStart,
12766 Declarator &D, Expr *BitWidth,
12767 InClassInitStyle InitStyle,
12768 AccessSpecifier AS,
12769 AttributeList *MSPropertyAttr) {
12770 IdentifierInfo *II = D.getIdentifier();
12771 if (!II) {
12772 Diag(DeclStart, diag::err_anonymous_property);
12773 return NULL;
12774 }
12775 SourceLocation Loc = D.getIdentifierLoc();
12776
12777 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12778 QualType T = TInfo->getType();
12779 if (getLangOpts().CPlusPlus) {
12780 CheckExtraCXXDefaultArguments(D);
12781
12782 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12783 UPPC_DataMemberType)) {
12784 D.setInvalidType();
12785 T = Context.IntTy;
12786 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12787 }
12788 }
12789
12790 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12791
12792 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12793 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12794 diag::err_invalid_thread)
12795 << DeclSpec::getSpecifierName(TSCS);
12796
12797 // Check to see if this name was declared as a member previously
12798 NamedDecl *PrevDecl = 0;
12799 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12800 LookupName(Previous, S);
12801 switch (Previous.getResultKind()) {
12802 case LookupResult::Found:
12803 case LookupResult::FoundUnresolvedValue:
12804 PrevDecl = Previous.getAsSingle<NamedDecl>();
12805 break;
12806
12807 case LookupResult::FoundOverloaded:
12808 PrevDecl = Previous.getRepresentativeDecl();
12809 break;
12810
12811 case LookupResult::NotFound:
12812 case LookupResult::NotFoundInCurrentInstantiation:
12813 case LookupResult::Ambiguous:
12814 break;
12815 }
12816
12817 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12818 // Maybe we will complain about the shadowed template parameter.
12819 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12820 // Just pretend that we didn't see the previous declaration.
12821 PrevDecl = 0;
12822 }
12823
12824 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12825 PrevDecl = 0;
12826
12827 SourceLocation TSSL = D.getLocStart();
12828 MSPropertyDecl *NewPD;
12829 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12830 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12831 II, T, TInfo, TSSL,
12832 Data.GetterId, Data.SetterId);
12833 ProcessDeclAttributes(TUScope, NewPD, D);
12834 NewPD->setAccess(AS);
12835
12836 if (NewPD->isInvalidDecl())
12837 Record->setInvalidDecl();
12838
12839 if (D.getDeclSpec().isModulePrivateSpecified())
12840 NewPD->setModulePrivate();
12841
12842 if (NewPD->isInvalidDecl() && PrevDecl) {
12843 // Don't introduce NewFD into scope; there's already something
12844 // with the same name in the same scope.
12845 } else if (II) {
12846 PushOnScopeChains(NewPD, S);
12847 } else
12848 Record->addDecl(NewPD);
12849
12850 return NewPD;
12851}