blob: 6ebfb57974e7f39c20c8dd849cd58b744b062734 [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:
441 // 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
444 // 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;
453 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
454 // Ignore default parameters of old decl if they are not in
455 // the same scope.
456 OldParamHasDfl = false;
457
458 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000459
Francois Pichet8d051e02011-04-10 03:03:52 +0000460 unsigned DiagDefaultParamID =
461 diag::err_param_default_argument_redefinition;
462
463 // MSVC accepts that default parameters be redefined for member functions
464 // of template class. The new default parameter's value is ignored.
465 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000466 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000467 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
468 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000469 // Merge the old default argument into the new parameter.
470 NewParam->setHasInheritedDefaultArg();
471 if (OldParam->hasUninstantiatedDefaultArg())
472 NewParam->setUninstantiatedDefaultArg(
473 OldParam->getUninstantiatedDefaultArg());
474 else
475 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000476 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000477 Invalid = false;
478 }
479 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000480
Francois Pichet8cf90492011-04-10 04:58:30 +0000481 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
482 // hint here. Alternatively, we could walk the type-source information
483 // for NewParam to find the last source location in the type... but it
484 // isn't worth the effort right now. This is the kind of test case that
485 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000486 // int f(int);
487 // void g(int (*fp)(int) = f);
488 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000489 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000490 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000491
492 // Look for the function declaration where the default argument was
493 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000494 for (FunctionDecl *Older = Old->getPreviousDecl();
495 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000496 if (!Older->getParamDecl(p)->hasDefaultArg())
497 break;
498
499 OldParam = Older->getParamDecl(p);
500 }
501
502 Diag(OldParam->getLocation(), diag::note_previous_definition)
503 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000504 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000505 // Merge the old default argument into the new parameter.
506 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000507 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000508 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000509 if (OldParam->hasUninstantiatedDefaultArg())
510 NewParam->setUninstantiatedDefaultArg(
511 OldParam->getUninstantiatedDefaultArg());
512 else
John McCall3d6c1782010-05-04 01:53:42 +0000513 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000514 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000515 if (New->getDescribedFunctionTemplate()) {
516 // Paragraph 4, quoted above, only applies to non-template functions.
517 Diag(NewParam->getLocation(),
518 diag::err_param_default_argument_template_redecl)
519 << NewParam->getDefaultArgRange();
520 Diag(Old->getLocation(), diag::note_template_prev_declaration)
521 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000522 } else if (New->getTemplateSpecializationKind()
523 != TSK_ImplicitInstantiation &&
524 New->getTemplateSpecializationKind() != TSK_Undeclared) {
525 // C++ [temp.expr.spec]p21:
526 // Default function arguments shall not be specified in a declaration
527 // or a definition for one of the following explicit specializations:
528 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000529 // - the explicit specialization of a member function template;
530 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000531 // template where the class template specialization to which the
532 // member function specialization belongs is implicitly
533 // instantiated.
534 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
535 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
536 << New->getDeclName()
537 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000538 } else if (New->getDeclContext()->isDependentContext()) {
539 // C++ [dcl.fct.default]p6 (DR217):
540 // Default arguments for a member function of a class template shall
541 // be specified on the initial declaration of the member function
542 // within the class template.
543 //
544 // Reading the tea leaves a bit in DR217 and its reference to DR205
545 // leads me to the conclusion that one cannot add default function
546 // arguments for an out-of-line definition of a member function of a
547 // dependent type.
548 int WhichKind = 2;
549 if (CXXRecordDecl *Record
550 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
551 if (Record->getDescribedClassTemplate())
552 WhichKind = 0;
553 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
554 WhichKind = 1;
555 else
556 WhichKind = 2;
557 }
558
559 Diag(NewParam->getLocation(),
560 diag::err_param_default_argument_member_template_redecl)
561 << WhichKind
562 << NewParam->getDefaultArgRange();
563 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000564 }
565 }
566
Richard Smithb8abff62012-11-28 03:45:24 +0000567 // DR1344: If a default argument is added outside a class definition and that
568 // default argument makes the function a special member function, the program
569 // is ill-formed. This can only happen for constructors.
570 if (isa<CXXConstructorDecl>(New) &&
571 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
572 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
573 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
574 if (NewSM != OldSM) {
575 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
576 assert(NewParam->hasDefaultArg());
577 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
578 << NewParam->getDefaultArgRange() << NewSM;
579 Diag(Old->getLocation(), diag::note_previous_declaration);
580 }
581 }
582
Richard Smithff234882012-02-20 23:28:05 +0000583 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000584 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000585 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000586 if (New->isConstexpr() != Old->isConstexpr()) {
587 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
588 << New << New->isConstexpr();
589 Diag(Old->getLocation(), diag::note_previous_declaration);
590 Invalid = true;
591 }
592
David Majnemerf6a144f2013-06-25 23:09:30 +0000593 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
NAKAMURA Takumifd527a42013-07-17 17:57:52 +0000594 // argument expression, that declaration shall be a definition and shall be
David Majnemerf6a144f2013-06-25 23:09:30 +0000595 // the only declaration of the function or function template in the
596 // translation unit.
597 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
598 functionDeclHasDefaultArgument(Old)) {
599 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
600 Diag(Old->getLocation(), diag::note_previous_declaration);
601 Invalid = true;
602 }
603
Douglas Gregore13ad832010-02-12 07:32:17 +0000604 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000605 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000606
Douglas Gregorcda9c672009-02-16 17:45:42 +0000607 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000608}
609
Sebastian Redl60618fa2011-03-12 11:50:43 +0000610/// \brief Merge the exception specifications of two variable declarations.
611///
612/// This is called when there's a redeclaration of a VarDecl. The function
613/// checks if the redeclaration might have an exception specification and
614/// validates compatibility and merges the specs if necessary.
615void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
616 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000617 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000618 return;
619
620 assert(Context.hasSameType(New->getType(), Old->getType()) &&
621 "Should only be called if types are otherwise the same.");
622
623 QualType NewType = New->getType();
624 QualType OldType = Old->getType();
625
626 // We're only interested in pointers and references to functions, as well
627 // as pointers to member functions.
628 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
629 NewType = R->getPointeeType();
630 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
631 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
632 NewType = P->getPointeeType();
633 OldType = OldType->getAs<PointerType>()->getPointeeType();
634 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
635 NewType = M->getPointeeType();
636 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
637 }
638
639 if (!NewType->isFunctionProtoType())
640 return;
641
642 // There's lots of special cases for functions. For function pointers, system
643 // libraries are hopefully not as broken so that we don't need these
644 // workarounds.
645 if (CheckEquivalentExceptionSpec(
646 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
647 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
648 New->setInvalidDecl();
649 }
650}
651
Chris Lattner3d1cee32008-04-08 05:04:30 +0000652/// CheckCXXDefaultArguments - Verify that the default arguments for a
653/// function declaration are well-formed according to C++
654/// [dcl.fct.default].
655void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
656 unsigned NumParams = FD->getNumParams();
657 unsigned p;
658
659 // Find first parameter with a default argument
660 for (p = 0; p < NumParams; ++p) {
661 ParmVarDecl *Param = FD->getParamDecl(p);
Richard Smith7974c602013-04-17 16:25:20 +0000662 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000663 break;
664 }
665
666 // C++ [dcl.fct.default]p4:
667 // In a given function declaration, all parameters
668 // subsequent to a parameter with a default argument shall
669 // have default arguments supplied in this or previous
670 // declarations. A default argument shall not be redefined
671 // by a later declaration (not even to the same value).
672 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000673 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000674 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000675 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000676 if (Param->isInvalidDecl())
677 /* We already complained about this parameter. */;
678 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000679 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000680 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000681 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000682 else
Mike Stump1eb44332009-09-09 15:08:12 +0000683 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000684 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattner3d1cee32008-04-08 05:04:30 +0000686 LastMissingDefaultArg = p;
687 }
688 }
689
690 if (LastMissingDefaultArg > 0) {
691 // Some default arguments were missing. Clear out all of the
692 // default arguments up to (and including) the last missing
693 // default argument, so that we leave the function parameters
694 // in a semantically valid state.
695 for (p = 0; p <= LastMissingDefaultArg; ++p) {
696 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000697 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000698 Param->setDefaultArg(0);
699 }
700 }
701 }
702}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000703
Richard Smith9f569cc2011-10-01 02:31:28 +0000704// CheckConstexprParameterTypes - Check whether a function's parameter types
705// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000706// diagnostic and return false.
707static bool CheckConstexprParameterTypes(Sema &SemaRef,
708 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000709 unsigned ArgIndex = 0;
710 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
711 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
712 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
713 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
714 SourceLocation ParamLoc = PD->getLocation();
715 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000716 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000717 diag::err_constexpr_non_literal_param,
718 ArgIndex+1, PD->getSourceRange(),
719 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000720 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000721 }
Joao Matos17d35c32012-08-31 22:18:20 +0000722 return true;
723}
724
725/// \brief Get diagnostic %select index for tag kind for
726/// record diagnostic message.
727/// WARNING: Indexes apply to particular diagnostics only!
728///
729/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000730static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000731 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000732 case TTK_Struct: return 0;
733 case TTK_Interface: return 1;
734 case TTK_Class: return 2;
735 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000736 }
Joao Matos17d35c32012-08-31 22:18:20 +0000737}
738
739// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
740// the requirements of a constexpr function definition or a constexpr
741// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000742// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000743//
Richard Smith86c3ae42012-02-13 03:54:03 +0000744// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
745bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000746 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
747 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000748 // C++11 [dcl.constexpr]p4:
749 // The definition of a constexpr constructor shall satisfy the following
750 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000751 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000752 const CXXRecordDecl *RD = MD->getParent();
753 if (RD->getNumVBases()) {
754 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
755 << isa<CXXConstructorDecl>(NewFD)
756 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
757 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
758 E = RD->vbases_end(); I != E; ++I)
759 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000760 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000761 return false;
762 }
Richard Smith35340502012-01-13 04:54:00 +0000763 }
764
765 if (!isa<CXXConstructorDecl>(NewFD)) {
766 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000767 // The definition of a constexpr function shall satisfy the following
768 // constraints:
769 // - it shall not be virtual;
770 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
771 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000772 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000773
Richard Smith86c3ae42012-02-13 03:54:03 +0000774 // If it's not obvious why this function is virtual, find an overridden
775 // function which uses the 'virtual' keyword.
776 const CXXMethodDecl *WrittenVirtual = Method;
777 while (!WrittenVirtual->isVirtualAsWritten())
778 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
779 if (WrittenVirtual != Method)
780 Diag(WrittenVirtual->getLocation(),
781 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000782 return false;
783 }
784
785 // - its return type shall be a literal type;
786 QualType RT = NewFD->getResultType();
787 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000788 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000789 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000790 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000791 }
792
Richard Smith35340502012-01-13 04:54:00 +0000793 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000794 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000795 return false;
796
Richard Smith9f569cc2011-10-01 02:31:28 +0000797 return true;
798}
799
800/// Check the given declaration statement is legal within a constexpr function
Richard Smitha10b9782013-04-22 15:31:51 +0000801/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
Richard Smith9f569cc2011-10-01 02:31:28 +0000802///
Richard Smitha10b9782013-04-22 15:31:51 +0000803/// \return true if the body is OK (maybe only as an extension), false if we
804/// have diagnosed a problem.
Richard Smith9f569cc2011-10-01 02:31:28 +0000805static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
Richard Smitha10b9782013-04-22 15:31:51 +0000806 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
807 // C++11 [dcl.constexpr]p3 and p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000808 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
809 // contain only
810 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
811 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
812 switch ((*DclIt)->getKind()) {
813 case Decl::StaticAssert:
814 case Decl::Using:
815 case Decl::UsingShadow:
816 case Decl::UsingDirective:
817 case Decl::UnresolvedUsingTypename:
Richard Smitha10b9782013-04-22 15:31:51 +0000818 case Decl::UnresolvedUsingValue:
Richard Smith9f569cc2011-10-01 02:31:28 +0000819 // - static_assert-declarations
820 // - using-declarations,
821 // - using-directives,
822 continue;
823
824 case Decl::Typedef:
825 case Decl::TypeAlias: {
826 // - typedef declarations and alias-declarations that do not define
827 // classes or enumerations,
828 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
829 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
830 // Don't allow variably-modified types in constexpr functions.
831 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
832 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
833 << TL.getSourceRange() << TL.getType()
834 << isa<CXXConstructorDecl>(Dcl);
835 return false;
836 }
837 continue;
838 }
839
840 case Decl::Enum:
841 case Decl::CXXRecord:
Richard Smitha10b9782013-04-22 15:31:51 +0000842 // C++1y allows types to be defined, not just declared.
843 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
844 SemaRef.Diag(DS->getLocStart(),
845 SemaRef.getLangOpts().CPlusPlus1y
846 ? diag::warn_cxx11_compat_constexpr_type_definition
847 : diag::ext_constexpr_type_definition)
Richard Smith9f569cc2011-10-01 02:31:28 +0000848 << isa<CXXConstructorDecl>(Dcl);
Richard Smith9f569cc2011-10-01 02:31:28 +0000849 continue;
850
Richard Smitha10b9782013-04-22 15:31:51 +0000851 case Decl::EnumConstant:
852 case Decl::IndirectField:
853 case Decl::ParmVar:
854 // These can only appear with other declarations which are banned in
855 // C++11 and permitted in C++1y, so ignore them.
856 continue;
857
858 case Decl::Var: {
859 // C++1y [dcl.constexpr]p3 allows anything except:
860 // a definition of a variable of non-literal type or of static or
861 // thread storage duration or for which no initialization is performed.
862 VarDecl *VD = cast<VarDecl>(*DclIt);
863 if (VD->isThisDeclarationADefinition()) {
864 if (VD->isStaticLocal()) {
865 SemaRef.Diag(VD->getLocation(),
866 diag::err_constexpr_local_var_static)
867 << isa<CXXConstructorDecl>(Dcl)
868 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
869 return false;
870 }
Richard Smithbebf5b12013-04-26 14:36:30 +0000871 if (!VD->getType()->isDependentType() &&
872 SemaRef.RequireLiteralType(
Richard Smitha10b9782013-04-22 15:31:51 +0000873 VD->getLocation(), VD->getType(),
874 diag::err_constexpr_local_var_non_literal_type,
875 isa<CXXConstructorDecl>(Dcl)))
876 return false;
877 if (!VD->hasInit()) {
878 SemaRef.Diag(VD->getLocation(),
879 diag::err_constexpr_local_var_no_init)
880 << isa<CXXConstructorDecl>(Dcl);
881 return false;
882 }
883 }
884 SemaRef.Diag(VD->getLocation(),
885 SemaRef.getLangOpts().CPlusPlus1y
886 ? diag::warn_cxx11_compat_constexpr_local_var
887 : diag::ext_constexpr_local_var)
Richard Smith9f569cc2011-10-01 02:31:28 +0000888 << isa<CXXConstructorDecl>(Dcl);
Richard Smitha10b9782013-04-22 15:31:51 +0000889 continue;
890 }
891
892 case Decl::NamespaceAlias:
893 case Decl::Function:
894 // These are disallowed in C++11 and permitted in C++1y. Allow them
895 // everywhere as an extension.
896 if (!Cxx1yLoc.isValid())
897 Cxx1yLoc = DS->getLocStart();
898 continue;
Richard Smith9f569cc2011-10-01 02:31:28 +0000899
900 default:
901 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
902 << isa<CXXConstructorDecl>(Dcl);
903 return false;
904 }
905 }
906
907 return true;
908}
909
910/// Check that the given field is initialized within a constexpr constructor.
911///
912/// \param Dcl The constexpr constructor being checked.
913/// \param Field The field being checked. This may be a member of an anonymous
914/// struct or union nested within the class being checked.
915/// \param Inits All declarations, including anonymous struct/union members and
916/// indirect members, for which any initialization was provided.
917/// \param Diagnosed Set to true if an error is produced.
918static void CheckConstexprCtorInitializer(Sema &SemaRef,
919 const FunctionDecl *Dcl,
920 FieldDecl *Field,
921 llvm::SmallSet<Decl*, 16> &Inits,
922 bool &Diagnosed) {
Eli Friedman5fb478b2013-06-28 21:07:41 +0000923 if (Field->isInvalidDecl())
924 return;
925
Douglas Gregord61db332011-10-10 17:22:13 +0000926 if (Field->isUnnamedBitfield())
927 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000928
929 if (Field->isAnonymousStructOrUnion() &&
930 Field->getType()->getAsCXXRecordDecl()->isEmpty())
931 return;
932
Richard Smith9f569cc2011-10-01 02:31:28 +0000933 if (!Inits.count(Field)) {
934 if (!Diagnosed) {
935 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
936 Diagnosed = true;
937 }
938 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
939 } else if (Field->isAnonymousStructOrUnion()) {
940 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
941 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
942 I != E; ++I)
943 // If an anonymous union contains an anonymous struct of which any member
944 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000945 if (!RD->isUnion() || Inits.count(*I))
946 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000947 }
948}
949
Richard Smitha10b9782013-04-22 15:31:51 +0000950/// Check the provided statement is allowed in a constexpr function
951/// definition.
952static bool
953CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
Robert Wilhelme7205c02013-08-10 12:33:24 +0000954 SmallVectorImpl<SourceLocation> &ReturnStmts,
Richard Smitha10b9782013-04-22 15:31:51 +0000955 SourceLocation &Cxx1yLoc) {
956 // - its function-body shall be [...] a compound-statement that contains only
957 switch (S->getStmtClass()) {
958 case Stmt::NullStmtClass:
959 // - null statements,
960 return true;
961
962 case Stmt::DeclStmtClass:
963 // - static_assert-declarations
964 // - using-declarations,
965 // - using-directives,
966 // - typedef declarations and alias-declarations that do not define
967 // classes or enumerations,
968 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
969 return false;
970 return true;
971
972 case Stmt::ReturnStmtClass:
973 // - and exactly one return statement;
974 if (isa<CXXConstructorDecl>(Dcl)) {
975 // C++1y allows return statements in constexpr constructors.
976 if (!Cxx1yLoc.isValid())
977 Cxx1yLoc = S->getLocStart();
978 return true;
979 }
980
981 ReturnStmts.push_back(S->getLocStart());
982 return true;
983
984 case Stmt::CompoundStmtClass: {
985 // C++1y allows compound-statements.
986 if (!Cxx1yLoc.isValid())
987 Cxx1yLoc = S->getLocStart();
988
989 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
990 for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
991 BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
992 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
993 Cxx1yLoc))
994 return false;
995 }
996 return true;
997 }
998
999 case Stmt::AttributedStmtClass:
1000 if (!Cxx1yLoc.isValid())
1001 Cxx1yLoc = S->getLocStart();
1002 return true;
1003
1004 case Stmt::IfStmtClass: {
1005 // C++1y allows if-statements.
1006 if (!Cxx1yLoc.isValid())
1007 Cxx1yLoc = S->getLocStart();
1008
1009 IfStmt *If = cast<IfStmt>(S);
1010 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1011 Cxx1yLoc))
1012 return false;
1013 if (If->getElse() &&
1014 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1015 Cxx1yLoc))
1016 return false;
1017 return true;
1018 }
1019
1020 case Stmt::WhileStmtClass:
1021 case Stmt::DoStmtClass:
1022 case Stmt::ForStmtClass:
1023 case Stmt::CXXForRangeStmtClass:
1024 case Stmt::ContinueStmtClass:
1025 // C++1y allows all of these. We don't allow them as extensions in C++11,
1026 // because they don't make sense without variable mutation.
1027 if (!SemaRef.getLangOpts().CPlusPlus1y)
1028 break;
1029 if (!Cxx1yLoc.isValid())
1030 Cxx1yLoc = S->getLocStart();
1031 for (Stmt::child_range Children = S->children(); Children; ++Children)
1032 if (*Children &&
1033 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1034 Cxx1yLoc))
1035 return false;
1036 return true;
1037
1038 case Stmt::SwitchStmtClass:
1039 case Stmt::CaseStmtClass:
1040 case Stmt::DefaultStmtClass:
1041 case Stmt::BreakStmtClass:
1042 // C++1y allows switch-statements, and since they don't need variable
1043 // mutation, we can reasonably allow them in C++11 as an extension.
1044 if (!Cxx1yLoc.isValid())
1045 Cxx1yLoc = S->getLocStart();
1046 for (Stmt::child_range Children = S->children(); Children; ++Children)
1047 if (*Children &&
1048 !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1049 Cxx1yLoc))
1050 return false;
1051 return true;
1052
1053 default:
1054 if (!isa<Expr>(S))
1055 break;
1056
1057 // C++1y allows expression-statements.
1058 if (!Cxx1yLoc.isValid())
1059 Cxx1yLoc = S->getLocStart();
1060 return true;
1061 }
1062
1063 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1064 << isa<CXXConstructorDecl>(Dcl);
1065 return false;
1066}
1067
Richard Smith9f569cc2011-10-01 02:31:28 +00001068/// Check the body for the given constexpr function declaration only contains
1069/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1070///
1071/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +00001072bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001073 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +00001074 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +00001075 // The definition of a constexpr function shall satisfy the following
1076 // constraints: [...]
1077 // - its function-body shall be = delete, = default, or a
1078 // compound-statement
1079 //
Richard Smith5ba73e12012-02-04 00:33:54 +00001080 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +00001081 // In the definition of a constexpr constructor, [...]
1082 // - its function-body shall not be a function-try-block;
1083 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1084 << isa<CXXConstructorDecl>(Dcl);
1085 return false;
1086 }
1087
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001088 SmallVector<SourceLocation, 4> ReturnStmts;
Richard Smitha10b9782013-04-22 15:31:51 +00001089
1090 // - its function-body shall be [...] a compound-statement that contains only
1091 // [... list of cases ...]
1092 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1093 SourceLocation Cxx1yLoc;
Richard Smith9f569cc2011-10-01 02:31:28 +00001094 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1095 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
Richard Smitha10b9782013-04-22 15:31:51 +00001096 if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1097 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +00001098 }
1099
Richard Smitha10b9782013-04-22 15:31:51 +00001100 if (Cxx1yLoc.isValid())
1101 Diag(Cxx1yLoc,
1102 getLangOpts().CPlusPlus1y
1103 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1104 : diag::ext_constexpr_body_invalid_stmt)
1105 << isa<CXXConstructorDecl>(Dcl);
1106
Richard Smith9f569cc2011-10-01 02:31:28 +00001107 if (const CXXConstructorDecl *Constructor
1108 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1109 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +00001110 // DR1359:
1111 // - every non-variant non-static data member and base class sub-object
1112 // shall be initialized;
1113 // - if the class is a non-empty union, or for each non-empty anonymous
1114 // union member of a non-union class, exactly one non-static data member
1115 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +00001116 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +00001117 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001118 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1119 return false;
1120 }
Richard Smith6e433752011-10-10 16:38:04 +00001121 } else if (!Constructor->isDependentContext() &&
1122 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001123 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1124
1125 // Skip detailed checking if we have enough initializers, and we would
1126 // allow at most one initializer per member.
1127 bool AnyAnonStructUnionMembers = false;
1128 unsigned Fields = 0;
1129 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1130 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +00001131 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00001132 AnyAnonStructUnionMembers = true;
1133 break;
1134 }
1135 }
1136 if (AnyAnonStructUnionMembers ||
1137 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1138 // Check initialization of non-static data members. Base classes are
1139 // always initialized so do not need to be checked. Dependent bases
1140 // might not have initializers in the member initializer list.
1141 llvm::SmallSet<Decl*, 16> Inits;
1142 for (CXXConstructorDecl::init_const_iterator
1143 I = Constructor->init_begin(), E = Constructor->init_end();
1144 I != E; ++I) {
1145 if (FieldDecl *FD = (*I)->getMember())
1146 Inits.insert(FD);
1147 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1148 Inits.insert(ID->chain_begin(), ID->chain_end());
1149 }
1150
1151 bool Diagnosed = false;
1152 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1153 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001154 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +00001155 if (Diagnosed)
1156 return false;
1157 }
1158 }
Richard Smith9f569cc2011-10-01 02:31:28 +00001159 } else {
1160 if (ReturnStmts.empty()) {
Richard Smitha10b9782013-04-22 15:31:51 +00001161 // C++1y doesn't require constexpr functions to contain a 'return'
1162 // statement. We still do, unless the return type is void, because
1163 // otherwise if there's no return statement, the function cannot
1164 // be used in a core constant expression.
Richard Smithbebf5b12013-04-26 14:36:30 +00001165 bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
Richard Smitha10b9782013-04-22 15:31:51 +00001166 Diag(Dcl->getLocation(),
Richard Smithbebf5b12013-04-26 14:36:30 +00001167 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1168 : diag::err_constexpr_body_no_return);
1169 return OK;
Richard Smith9f569cc2011-10-01 02:31:28 +00001170 }
1171 if (ReturnStmts.size() > 1) {
Richard Smitha10b9782013-04-22 15:31:51 +00001172 Diag(ReturnStmts.back(),
1173 getLangOpts().CPlusPlus1y
1174 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1175 : diag::ext_constexpr_body_multiple_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001176 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1177 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
Richard Smith9f569cc2011-10-01 02:31:28 +00001178 }
1179 }
1180
Richard Smith5ba73e12012-02-04 00:33:54 +00001181 // C++11 [dcl.constexpr]p5:
1182 // if no function argument values exist such that the function invocation
1183 // substitution would produce a constant expression, the program is
1184 // ill-formed; no diagnostic required.
1185 // C++11 [dcl.constexpr]p3:
1186 // - every constructor call and implicit conversion used in initializing the
1187 // return value shall be one of those allowed in a constant expression.
1188 // C++11 [dcl.constexpr]p4:
1189 // - every constructor involved in initializing non-static data members and
1190 // base class sub-objects shall be a constexpr constructor.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001191 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +00001192 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smithafee0ff2012-12-09 05:55:43 +00001193 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
Richard Smith745f5142012-01-27 01:14:48 +00001194 << isa<CXXConstructorDecl>(Dcl);
1195 for (size_t I = 0, N = Diags.size(); I != N; ++I)
1196 Diag(Diags[I].first, Diags[I].second);
Richard Smithafee0ff2012-12-09 05:55:43 +00001197 // Don't return false here: we allow this for compatibility in
1198 // system headers.
Richard Smith745f5142012-01-27 01:14:48 +00001199 }
1200
Richard Smith9f569cc2011-10-01 02:31:28 +00001201 return true;
1202}
1203
Douglas Gregorb48fe382008-10-31 09:07:45 +00001204/// isCurrentClassName - Determine whether the identifier II is the
1205/// name of the class type currently being defined. In the case of
1206/// nested classes, this will only return true if II is the name of
1207/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001208bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1209 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001210 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001211
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001212 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001213 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001214 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001215 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1216 } else
1217 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1218
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001219 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001220 return &II == CurDecl->getIdentifier();
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00001221 return false;
Douglas Gregorb48fe382008-10-31 09:07:45 +00001222}
1223
Douglas Gregor229d47a2012-11-10 07:24:09 +00001224/// \brief Determine whether the given class is a base class of the given
1225/// class, including looking at dependent bases.
1226static bool findCircularInheritance(const CXXRecordDecl *Class,
1227 const CXXRecordDecl *Current) {
1228 SmallVector<const CXXRecordDecl*, 8> Queue;
1229
1230 Class = Class->getCanonicalDecl();
1231 while (true) {
1232 for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1233 E = Current->bases_end();
1234 I != E; ++I) {
1235 CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1236 if (!Base)
1237 continue;
1238
1239 Base = Base->getDefinition();
1240 if (!Base)
1241 continue;
1242
1243 if (Base->getCanonicalDecl() == Class)
1244 return true;
1245
1246 Queue.push_back(Base);
1247 }
1248
1249 if (Queue.empty())
1250 return false;
1251
1252 Current = Queue.back();
1253 Queue.pop_back();
1254 }
1255
1256 return false;
Douglas Gregord777e282012-11-10 01:18:17 +00001257}
1258
Mike Stump1eb44332009-09-09 15:08:12 +00001259/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001260///
1261/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1262/// and returns NULL otherwise.
1263CXXBaseSpecifier *
1264Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1265 SourceRange SpecifierRange,
1266 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001267 TypeSourceInfo *TInfo,
1268 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001269 QualType BaseType = TInfo->getType();
1270
Douglas Gregor2943aed2009-03-03 04:44:36 +00001271 // C++ [class.union]p1:
1272 // A union shall not have base classes.
1273 if (Class->isUnion()) {
1274 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1275 << SpecifierRange;
1276 return 0;
1277 }
1278
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001279 if (EllipsisLoc.isValid() &&
1280 !TInfo->getType()->containsUnexpandedParameterPack()) {
1281 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1282 << TInfo->getTypeLoc().getSourceRange();
1283 EllipsisLoc = SourceLocation();
1284 }
Douglas Gregord777e282012-11-10 01:18:17 +00001285
1286 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1287
1288 if (BaseType->isDependentType()) {
1289 // Make sure that we don't have circular inheritance among our dependent
1290 // bases. For non-dependent bases, the check for completeness below handles
1291 // this.
1292 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1293 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1294 ((BaseDecl = BaseDecl->getDefinition()) &&
Douglas Gregor229d47a2012-11-10 07:24:09 +00001295 findCircularInheritance(Class, BaseDecl))) {
Douglas Gregord777e282012-11-10 01:18:17 +00001296 Diag(BaseLoc, diag::err_circular_inheritance)
1297 << BaseType << Context.getTypeDeclType(Class);
1298
1299 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1300 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1301 << BaseType;
1302
1303 return 0;
1304 }
1305 }
1306
Mike Stump1eb44332009-09-09 15:08:12 +00001307 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001308 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001309 Access, TInfo, EllipsisLoc);
Douglas Gregord777e282012-11-10 01:18:17 +00001310 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001311
1312 // Base specifiers must be record types.
1313 if (!BaseType->isRecordType()) {
1314 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1315 return 0;
1316 }
1317
1318 // C++ [class.union]p1:
1319 // A union shall not be used as a base class.
1320 if (BaseType->isUnionType()) {
1321 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1322 return 0;
1323 }
1324
1325 // C++ [class.derived]p2:
1326 // The class-name in a base-specifier shall not be an incompletely
1327 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001328 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001329 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001330 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001331 return 0;
John McCall572fc622010-08-17 07:23:57 +00001332 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001333
Eli Friedman1d954f62009-08-15 21:55:26 +00001334 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001335 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001336 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001337 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001338 assert(BaseDecl && "Base type is not incomplete, but has no definition");
David Majnemer2f686692013-06-22 06:43:58 +00001339 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
Eli Friedman1d954f62009-08-15 21:55:26 +00001340 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001341
Anders Carlsson1d209272011-03-25 14:55:14 +00001342 // C++ [class]p3:
1343 // If a class is marked final and it appears as a base-type-specifier in
1344 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001345 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001346 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1347 << CXXBaseDecl->getDeclName();
1348 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1349 << CXXBaseDecl->getDeclName();
1350 return 0;
1351 }
1352
John McCall572fc622010-08-17 07:23:57 +00001353 if (BaseDecl->isInvalidDecl())
1354 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001355
1356 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001357 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001358 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001359 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001360}
1361
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001362/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1363/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001364/// example:
1365/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001366/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001367BaseResult
John McCalld226f652010-08-21 09:40:31 +00001368Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Richard Smith05321402013-02-19 23:47:15 +00001369 ParsedAttributes &Attributes,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001370 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001371 ParsedType basetype, SourceLocation BaseLoc,
1372 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001373 if (!classdecl)
1374 return true;
1375
Douglas Gregor40808ce2009-03-09 23:48:35 +00001376 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001377 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001378 if (!Class)
1379 return true;
1380
Richard Smith05321402013-02-19 23:47:15 +00001381 // We do not support any C++11 attributes on base-specifiers yet.
1382 // Diagnose any attributes we see.
1383 if (!Attributes.empty()) {
1384 for (AttributeList *Attr = Attributes.getList(); Attr;
1385 Attr = Attr->getNext()) {
1386 if (Attr->isInvalid() ||
1387 Attr->getKind() == AttributeList::IgnoredAttribute)
1388 continue;
1389 Diag(Attr->getLoc(),
1390 Attr->getKind() == AttributeList::UnknownAttribute
1391 ? diag::warn_unknown_attribute_ignored
1392 : diag::err_base_specifier_attribute)
1393 << Attr->getName();
1394 }
1395 }
1396
Nick Lewycky56062202010-07-26 16:56:01 +00001397 TypeSourceInfo *TInfo = 0;
1398 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001399
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001400 if (EllipsisLoc.isInvalid() &&
1401 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001402 UPPC_BaseType))
1403 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001404
Douglas Gregor2943aed2009-03-03 04:44:36 +00001405 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001406 Virtual, Access, TInfo,
1407 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001408 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001409 else
1410 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Douglas Gregor2943aed2009-03-03 04:44:36 +00001412 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001413}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001414
Douglas Gregor2943aed2009-03-03 04:44:36 +00001415/// \brief Performs the actual work of attaching the given base class
1416/// specifiers to a C++ class.
1417bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1418 unsigned NumBases) {
1419 if (NumBases == 0)
1420 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001421
1422 // Used to keep track of which base types we have already seen, so
1423 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001424 // that the key is always the unqualified canonical type of the base
1425 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001426 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1427
1428 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001429 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001430 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001431 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001432 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001433 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001434 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001435
1436 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1437 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001438 // C++ [class.mi]p3:
1439 // A class shall not be specified as a direct base class of a
1440 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001441 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001442 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001443 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001444 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001445
1446 // Delete the duplicate base class specifier; we're going to
1447 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001448 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001449
1450 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001451 } else {
1452 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001453 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001454 Bases[NumGoodBases++] = Bases[idx];
John McCalle402e722012-09-25 07:32:39 +00001455 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1456 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1457 if (Class->isInterface() &&
1458 (!RD->isInterface() ||
1459 KnownBase->getAccessSpecifier() != AS_public)) {
1460 // The Microsoft extension __interface does not permit bases that
1461 // are not themselves public interfaces.
1462 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1463 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1464 << RD->getSourceRange();
1465 Invalid = true;
1466 }
1467 if (RD->hasAttr<WeakAttr>())
1468 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1469 }
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001470 }
1471 }
1472
1473 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001474 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001475
1476 // Delete the remaining (good) base class specifiers, since their
1477 // data has been copied into the CXXRecordDecl.
1478 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001479 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001480
1481 return Invalid;
1482}
1483
1484/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1485/// class, after checking whether there are any duplicate base
1486/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001487void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001488 unsigned NumBases) {
1489 if (!ClassDecl || !Bases || !NumBases)
1490 return;
1491
1492 AdjustDeclIfTemplate(ClassDecl);
Robert Wilhelm0d317a02013-07-22 05:04:01 +00001493 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001494}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001495
Douglas Gregora8f32e02009-10-06 17:59:45 +00001496/// \brief Determine whether the type \p Derived is a C++ class that is
1497/// derived from the type \p Base.
1498bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001499 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001500 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001501
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001502 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001503 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001504 return false;
1505
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001506 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001507 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001508 return false;
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001509
1510 // If either the base or the derived type is invalid, don't try to
1511 // check whether one is derived from the other.
1512 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1513 return false;
1514
John McCall86ff3082010-02-04 22:26:26 +00001515 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1516 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001517}
1518
1519/// \brief Determine whether the type \p Derived is a C++ class that is
1520/// derived from the type \p Base.
1521bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001522 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001523 return false;
1524
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001525 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001526 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001527 return false;
1528
Douglas Gregor0162c1c2013-03-26 23:36:30 +00001529 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
John McCall3cb0ebd2010-03-10 03:28:59 +00001530 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001531 return false;
1532
Douglas Gregora8f32e02009-10-06 17:59:45 +00001533 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1534}
1535
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001536void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001537 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001538 assert(BasePathArray.empty() && "Base path array must be empty!");
1539 assert(Paths.isRecordingPaths() && "Must record paths!");
1540
1541 const CXXBasePath &Path = Paths.front();
1542
1543 // We first go backward and check if we have a virtual base.
1544 // FIXME: It would be better if CXXBasePath had the base specifier for
1545 // the nearest virtual base.
1546 unsigned Start = 0;
1547 for (unsigned I = Path.size(); I != 0; --I) {
1548 if (Path[I - 1].Base->isVirtual()) {
1549 Start = I - 1;
1550 break;
1551 }
1552 }
1553
1554 // Now add all bases.
1555 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001556 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001557}
1558
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001559/// \brief Determine whether the given base path includes a virtual
1560/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001561bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1562 for (CXXCastPath::const_iterator B = BasePath.begin(),
1563 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001564 B != BEnd; ++B)
1565 if ((*B)->isVirtual())
1566 return true;
1567
1568 return false;
1569}
1570
Douglas Gregora8f32e02009-10-06 17:59:45 +00001571/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1572/// conversion (where Derived and Base are class types) is
1573/// well-formed, meaning that the conversion is unambiguous (and
1574/// that all of the base classes are accessible). Returns true
1575/// and emits a diagnostic if the code is ill-formed, returns false
1576/// otherwise. Loc is the location where this routine should point to
1577/// if there is an error, and Range is the source range to highlight
1578/// if there is an error.
1579bool
1580Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001581 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001582 unsigned AmbigiousBaseConvID,
1583 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001584 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001585 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001586 // First, determine whether the path from Derived to Base is
1587 // ambiguous. This is slightly more expensive than checking whether
1588 // the Derived to Base conversion exists, because here we need to
1589 // explore multiple paths to determine if there is an ambiguity.
1590 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1591 /*DetectVirtual=*/false);
1592 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1593 assert(DerivationOkay &&
1594 "Can only be used with a derived-to-base conversion");
1595 (void)DerivationOkay;
1596
1597 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001598 if (InaccessibleBaseID) {
1599 // Check that the base class can be accessed.
1600 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1601 InaccessibleBaseID)) {
1602 case AR_inaccessible:
1603 return true;
1604 case AR_accessible:
1605 case AR_dependent:
1606 case AR_delayed:
1607 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001608 }
John McCall6b2accb2010-02-10 09:31:12 +00001609 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001610
1611 // Build a base path if necessary.
1612 if (BasePath)
1613 BuildBasePathArray(Paths, *BasePath);
1614 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001615 }
1616
David Majnemer2f686692013-06-22 06:43:58 +00001617 if (AmbigiousBaseConvID) {
1618 // We know that the derived-to-base conversion is ambiguous, and
1619 // we're going to produce a diagnostic. Perform the derived-to-base
1620 // search just one more time to compute all of the possible paths so
1621 // that we can print them out. This is more expensive than any of
1622 // the previous derived-to-base checks we've done, but at this point
1623 // performance isn't as much of an issue.
1624 Paths.clear();
1625 Paths.setRecordingPaths(true);
1626 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1627 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1628 (void)StillOkay;
1629
1630 // Build up a textual representation of the ambiguous paths, e.g.,
1631 // D -> B -> A, that will be used to illustrate the ambiguous
1632 // conversions in the diagnostic. We only print one of the paths
1633 // to each base class subobject.
1634 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1635
1636 Diag(Loc, AmbigiousBaseConvID)
1637 << Derived << Base << PathDisplayStr << Range << Name;
1638 }
Douglas Gregora8f32e02009-10-06 17:59:45 +00001639 return true;
1640}
1641
1642bool
1643Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001644 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001645 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001646 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001647 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001648 IgnoreAccess ? 0
1649 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001650 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001651 Loc, Range, DeclarationName(),
1652 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001653}
1654
1655
1656/// @brief Builds a string representing ambiguous paths from a
1657/// specific derived class to different subobjects of the same base
1658/// class.
1659///
1660/// This function builds a string that can be used in error messages
1661/// to show the different paths that one can take through the
1662/// inheritance hierarchy to go from the derived class to different
1663/// subobjects of a base class. The result looks something like this:
1664/// @code
1665/// struct D -> struct B -> struct A
1666/// struct D -> struct C -> struct A
1667/// @endcode
1668std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1669 std::string PathDisplayStr;
1670 std::set<unsigned> DisplayedPaths;
1671 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1672 Path != Paths.end(); ++Path) {
1673 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1674 // We haven't displayed a path to this particular base
1675 // class subobject yet.
1676 PathDisplayStr += "\n ";
1677 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1678 for (CXXBasePath::const_iterator Element = Path->begin();
1679 Element != Path->end(); ++Element)
1680 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1681 }
1682 }
1683
1684 return PathDisplayStr;
1685}
1686
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001687//===----------------------------------------------------------------------===//
1688// C++ class member Handling
1689//===----------------------------------------------------------------------===//
1690
Abramo Bagnara6206d532010-06-05 05:09:32 +00001691/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001692bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1693 SourceLocation ASLoc,
1694 SourceLocation ColonLoc,
1695 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001696 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001697 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001698 ASLoc, ColonLoc);
1699 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001700 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001701}
1702
Richard Smitha4b39652012-08-06 03:25:17 +00001703/// CheckOverrideControl - Check C++11 override control semantics.
1704void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001705 if (D->isInvalidDecl())
1706 return;
1707
Chris Lattner5f9e2722011-07-23 10:55:15 +00001708 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001709
Richard Smitha4b39652012-08-06 03:25:17 +00001710 // Do we know which functions this declaration might be overriding?
1711 bool OverridesAreKnown = !MD ||
1712 (!MD->getParent()->hasAnyDependentBases() &&
1713 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001714
Richard Smitha4b39652012-08-06 03:25:17 +00001715 if (!MD || !MD->isVirtual()) {
1716 if (OverridesAreKnown) {
1717 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1718 Diag(OA->getLocation(),
1719 diag::override_keyword_only_allowed_on_virtual_member_functions)
1720 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1721 D->dropAttr<OverrideAttr>();
1722 }
1723 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1724 Diag(FA->getLocation(),
1725 diag::override_keyword_only_allowed_on_virtual_member_functions)
1726 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1727 D->dropAttr<FinalAttr>();
1728 }
1729 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001730 return;
1731 }
Richard Smitha4b39652012-08-06 03:25:17 +00001732
1733 if (!OverridesAreKnown)
1734 return;
1735
1736 // C++11 [class.virtual]p5:
1737 // If a virtual function is marked with the virt-specifier override and
1738 // does not override a member function of a base class, the program is
1739 // ill-formed.
1740 bool HasOverriddenMethods =
1741 MD->begin_overridden_methods() != MD->end_overridden_methods();
1742 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1743 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1744 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001745}
1746
Richard Smitha4b39652012-08-06 03:25:17 +00001747/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001748/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001749/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001750bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1751 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001752 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001753 return false;
1754
1755 Diag(New->getLocation(), diag::err_final_function_overridden)
1756 << New->getDeclName();
1757 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1758 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001759}
1760
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001761static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001762 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1763 // FIXME: Destruction of ObjC lifetime types has side-effects.
1764 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1765 return !RD->isCompleteDefinition() ||
1766 !RD->hasTrivialDefaultConstructor() ||
1767 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001768 return false;
1769}
1770
John McCall76da55d2013-04-16 07:28:30 +00001771static AttributeList *getMSPropertyAttr(AttributeList *list) {
1772 for (AttributeList* it = list; it != 0; it = it->getNext())
1773 if (it->isDeclspecPropertyAttribute())
1774 return it;
1775 return 0;
1776}
1777
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001778/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1779/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001780/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001781/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1782/// present (but parsing it has been deferred).
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001783NamedDecl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001784Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001785 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001786 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001787 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001788 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001789 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1790 DeclarationName Name = NameInfo.getName();
1791 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001792
1793 // For anonymous bitfields, the location should point to the type.
1794 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001795 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001796
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001797 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001798
John McCall4bde1e12010-06-04 08:34:12 +00001799 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001800 assert(!DS.isFriendSpecified());
1801
Richard Smith1ab0d902011-06-25 02:28:38 +00001802 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001803
John McCalle402e722012-09-25 07:32:39 +00001804 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1805 // The Microsoft extension __interface only permits public member functions
1806 // and prohibits constructors, destructors, operators, non-public member
1807 // functions, static methods and data members.
1808 unsigned InvalidDecl;
1809 bool ShowDeclName = true;
1810 if (!isFunc)
1811 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1812 else if (AS != AS_public)
1813 InvalidDecl = 2;
1814 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1815 InvalidDecl = 3;
1816 else switch (Name.getNameKind()) {
1817 case DeclarationName::CXXConstructorName:
1818 InvalidDecl = 4;
1819 ShowDeclName = false;
1820 break;
1821
1822 case DeclarationName::CXXDestructorName:
1823 InvalidDecl = 5;
1824 ShowDeclName = false;
1825 break;
1826
1827 case DeclarationName::CXXOperatorName:
1828 case DeclarationName::CXXConversionFunctionName:
1829 InvalidDecl = 6;
1830 break;
1831
1832 default:
1833 InvalidDecl = 0;
1834 break;
1835 }
1836
1837 if (InvalidDecl) {
1838 if (ShowDeclName)
1839 Diag(Loc, diag::err_invalid_member_in_interface)
1840 << (InvalidDecl-1) << Name;
1841 else
1842 Diag(Loc, diag::err_invalid_member_in_interface)
1843 << (InvalidDecl-1) << "";
1844 return 0;
1845 }
1846 }
1847
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001848 // C++ 9.2p6: A member shall not be declared to have automatic storage
1849 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001850 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1851 // data members and cannot be applied to names declared const or static,
1852 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001853 switch (DS.getStorageClassSpec()) {
Richard Smithec642442013-04-12 22:46:28 +00001854 case DeclSpec::SCS_unspecified:
1855 case DeclSpec::SCS_typedef:
1856 case DeclSpec::SCS_static:
1857 break;
1858 case DeclSpec::SCS_mutable:
1859 if (isFunc) {
1860 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Richard Smithec642442013-04-12 22:46:28 +00001862 // FIXME: It would be nicer if the keyword was ignored only for this
1863 // declarator. Otherwise we could get follow-up errors.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001864 D.getMutableDeclSpec().ClearStorageClassSpecs();
Richard Smithec642442013-04-12 22:46:28 +00001865 }
1866 break;
1867 default:
1868 Diag(DS.getStorageClassSpecLoc(),
1869 diag::err_storageclass_invalid_for_member);
1870 D.getMutableDeclSpec().ClearStorageClassSpecs();
1871 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001872 }
1873
Sebastian Redl669d5d72008-11-14 23:42:31 +00001874 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1875 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001876 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001877
David Blaikie1d87fba2013-01-30 01:22:18 +00001878 if (DS.isConstexprSpecified() && isInstField) {
1879 SemaDiagnosticBuilder B =
1880 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1881 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1882 if (InitStyle == ICIS_NoInit) {
1883 B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1884 D.getMutableDeclSpec().ClearConstexprSpec();
1885 const char *PrevSpec;
1886 unsigned DiagID;
1887 bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1888 PrevSpec, DiagID, getLangOpts());
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001889 (void)Failed;
David Blaikie1d87fba2013-01-30 01:22:18 +00001890 assert(!Failed && "Making a constexpr member const shouldn't fail");
1891 } else {
1892 B << 1;
1893 const char *PrevSpec;
1894 unsigned DiagID;
David Blaikie1d87fba2013-01-30 01:22:18 +00001895 if (D.getMutableDeclSpec().SetStorageClassSpec(
1896 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
Matt Beaumont-Gay3e55e3e2013-01-31 00:08:03 +00001897 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
David Blaikie1d87fba2013-01-30 01:22:18 +00001898 "This is the only DeclSpec that should fail to be applied");
1899 B << 1;
1900 } else {
1901 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1902 isInstField = false;
1903 }
1904 }
1905 }
1906
Rafael Espindolafc35cbc2013-01-08 20:44:06 +00001907 NamedDecl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001908 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001909 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001910
1911 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001912 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001913 Diag(Loc, diag::err_bad_variable_name)
1914 << Name;
1915 return 0;
1916 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001917
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001918 IdentifierInfo *II = Name.getAsIdentifierInfo();
1919
Douglas Gregorf2503652011-09-21 14:40:46 +00001920 // Member field could not be with "template" keyword.
1921 // So TemplateParameterLists should be empty in this case.
1922 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001923 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001924 if (TemplateParams->size()) {
1925 // There is no such thing as a member field template.
1926 Diag(D.getIdentifierLoc(), diag::err_template_member)
1927 << II
1928 << SourceRange(TemplateParams->getTemplateLoc(),
1929 TemplateParams->getRAngleLoc());
1930 } else {
1931 // There is an extraneous 'template<>' for this member.
1932 Diag(TemplateParams->getTemplateLoc(),
1933 diag::err_template_member_noparams)
1934 << II
1935 << SourceRange(TemplateParams->getTemplateLoc(),
1936 TemplateParams->getRAngleLoc());
1937 }
1938 return 0;
1939 }
1940
Douglas Gregor922fff22010-10-13 22:19:53 +00001941 if (SS.isSet() && !SS.isInvalid()) {
1942 // The user provided a superfluous scope specifier inside a class
1943 // definition:
1944 //
1945 // class X {
1946 // int X::member;
1947 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001948 if (DeclContext *DC = computeDeclContext(SS, false))
1949 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001950 else
1951 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1952 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001953
Douglas Gregor922fff22010-10-13 22:19:53 +00001954 SS.clear();
1955 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001956
John McCall76da55d2013-04-16 07:28:30 +00001957 AttributeList *MSPropertyAttr =
1958 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
Eli Friedmanb26f0122013-06-28 20:48:34 +00001959 if (MSPropertyAttr) {
1960 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1961 BitWidth, InitStyle, AS, MSPropertyAttr);
1962 if (!Member)
1963 return 0;
1964 isInstField = false;
1965 } else {
1966 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1967 BitWidth, InitStyle, AS);
1968 assert(Member && "HandleField never returns null");
1969 }
1970 } else {
1971 assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1972
1973 Member = HandleDeclarator(S, D, TemplateParameterLists);
1974 if (!Member)
1975 return 0;
1976
1977 // Non-instance-fields can't have a bitfield.
1978 if (BitWidth) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001979 if (Member->isInvalidDecl()) {
1980 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001981 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001982 // C++ 9.6p3: A bit-field shall not be a static member.
1983 // "static member 'A' cannot be a bit-field"
1984 Diag(Loc, diag::err_static_not_bitfield)
1985 << Name << BitWidth->getSourceRange();
1986 } else if (isa<TypedefDecl>(Member)) {
1987 // "typedef member 'x' cannot be a bit-field"
1988 Diag(Loc, diag::err_typedef_not_bitfield)
1989 << Name << BitWidth->getSourceRange();
1990 } else {
1991 // A function typedef ("typedef int f(); f a;").
1992 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1993 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001994 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001995 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001996 }
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Chris Lattner8b963ef2009-03-05 23:01:03 +00001998 BitWidth = 0;
1999 Member->setInvalidDecl();
2000 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00002001
2002 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Larisse Voufoef4579c2013-08-06 01:03:05 +00002004 // If we have declared a member function template or static data member
2005 // template, set the access of the templated declaration as well.
Douglas Gregor37b372b2009-08-20 22:52:58 +00002006 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2007 FunTmpl->getTemplatedDecl()->setAccess(AS);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002008 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2009 VarTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00002010 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002011
Richard Smitha4b39652012-08-06 03:25:17 +00002012 if (VS.isOverrideSpecified())
2013 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2014 if (VS.isFinalSpecified())
2015 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00002016
Douglas Gregorf5251602011-03-08 17:10:18 +00002017 if (VS.getLastLocation().isValid()) {
2018 // Update the end location of a method that has a virt-specifiers.
2019 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2020 MD->setRangeEnd(VS.getLastLocation());
2021 }
Richard Smitha4b39652012-08-06 03:25:17 +00002022
Anders Carlsson4ebf1602011-01-20 06:29:02 +00002023 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00002024
Douglas Gregor10bd3682008-11-17 22:58:34 +00002025 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002026
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002027 if (isInstField) {
2028 FieldDecl *FD = cast<FieldDecl>(Member);
2029 FieldCollector->Add(FD);
2030
2031 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2032 FD->getLocation())
2033 != DiagnosticsEngine::Ignored) {
2034 // Remember all explicit private FieldDecls that have a name, no side
2035 // effects and are not part of a dependent type declaration.
2036 if (!FD->isImplicit() && FD->getDeclName() &&
2037 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00002038 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00002039 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002040 !InitializationHasSideEffects(*FD))
2041 UnusedPrivateFields.insert(FD);
2042 }
2043 }
2044
John McCalld226f652010-08-21 09:40:31 +00002045 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002046}
2047
Hans Wennborg471f9852012-09-18 15:58:06 +00002048namespace {
2049 class UninitializedFieldVisitor
2050 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2051 Sema &S;
2052 ValueDecl *VD;
2053 public:
2054 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2055 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002056 S(S) {
2057 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2058 this->VD = IFD->getAnonField();
2059 else
2060 this->VD = VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002061 }
2062
2063 void HandleExpr(Expr *E) {
2064 if (!E) return;
2065
2066 // Expressions like x(x) sometimes lack the surrounding expressions
2067 // but need to be checked anyways.
2068 HandleValue(E);
2069 Visit(E);
2070 }
2071
2072 void HandleValue(Expr *E) {
2073 E = E->IgnoreParens();
2074
2075 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2076 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002077 return;
2078
2079 // FieldME is the inner-most MemberExpr that is not an anonymous struct
2080 // or union.
2081 MemberExpr *FieldME = ME;
2082
Hans Wennborg471f9852012-09-18 15:58:06 +00002083 Expr *Base = E;
2084 while (isa<MemberExpr>(Base)) {
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002085 ME = cast<MemberExpr>(Base);
2086
2087 if (isa<VarDecl>(ME->getMemberDecl()))
2088 return;
2089
2090 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2091 if (!FD->isAnonymousStructOrUnion())
2092 FieldME = ME;
2093
Hans Wennborg471f9852012-09-18 15:58:06 +00002094 Base = ME->getBase();
2095 }
2096
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002097 if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg471f9852012-09-18 15:58:06 +00002098 unsigned diag = VD->getType()->isReferenceType()
2099 ? diag::warn_reference_field_is_uninit
2100 : diag::warn_field_is_uninit;
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002101 S.Diag(FieldME->getExprLoc(), diag) << VD;
Hans Wennborg471f9852012-09-18 15:58:06 +00002102 }
Nick Lewycky621ba4f2012-11-15 08:19:20 +00002103 return;
Hans Wennborg471f9852012-09-18 15:58:06 +00002104 }
2105
2106 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2107 HandleValue(CO->getTrueExpr());
2108 HandleValue(CO->getFalseExpr());
2109 return;
2110 }
2111
2112 if (BinaryConditionalOperator *BCO =
2113 dyn_cast<BinaryConditionalOperator>(E)) {
2114 HandleValue(BCO->getCommon());
2115 HandleValue(BCO->getFalseExpr());
2116 return;
2117 }
2118
2119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2120 switch (BO->getOpcode()) {
2121 default:
2122 return;
2123 case(BO_PtrMemD):
2124 case(BO_PtrMemI):
2125 HandleValue(BO->getLHS());
2126 return;
2127 case(BO_Comma):
2128 HandleValue(BO->getRHS());
2129 return;
2130 }
2131 }
2132 }
2133
2134 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2135 if (E->getCastKind() == CK_LValueToRValue)
2136 HandleValue(E->getSubExpr());
2137
2138 Inherited::VisitImplicitCastExpr(E);
2139 }
2140
2141 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2142 Expr *Callee = E->getCallee();
2143 if (isa<MemberExpr>(Callee))
2144 HandleValue(Callee);
2145
2146 Inherited::VisitCXXMemberCallExpr(E);
2147 }
2148 };
2149 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2150 ValueDecl *VD) {
2151 UninitializedFieldVisitor(S, VD).HandleExpr(E);
2152 }
2153} // namespace
2154
Richard Smith7a614d82011-06-11 17:19:42 +00002155/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002156/// in-class initializer for a non-static C++ class member, and after
2157/// instantiating an in-class initializer in a class template. Such actions
2158/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00002159void
Richard Smithca523302012-06-10 03:12:00 +00002160Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00002161 Expr *InitExpr) {
2162 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00002163 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2164 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00002165
2166 if (!InitExpr) {
2167 FD->setInvalidDecl();
2168 FD->removeInClassInitializer();
2169 return;
2170 }
2171
Peter Collingbournefef21892011-10-23 18:59:44 +00002172 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2173 FD->setInvalidDecl();
2174 FD->removeInClassInitializer();
2175 return;
2176 }
2177
Hans Wennborg471f9852012-09-18 15:58:06 +00002178 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2179 != DiagnosticsEngine::Ignored) {
2180 CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2181 }
2182
Richard Smith7a614d82011-06-11 17:19:42 +00002183 ExprResult Init = InitExpr;
Richard Smithc83c2302012-12-19 01:39:02 +00002184 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl33deb352012-02-22 10:50:08 +00002185 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00002186 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00002187 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00002188 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002189 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2190 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
Richard Smith7a614d82011-06-11 17:19:42 +00002191 if (Init.isInvalid()) {
2192 FD->setInvalidDecl();
2193 return;
2194 }
Richard Smith7a614d82011-06-11 17:19:42 +00002195 }
2196
Richard Smith41956372013-01-14 22:39:08 +00002197 // C++11 [class.base.init]p7:
Richard Smith7a614d82011-06-11 17:19:42 +00002198 // The initialization of each base and member constitutes a
2199 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002200 Init = ActOnFinishFullExpr(Init.take(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00002201 if (Init.isInvalid()) {
2202 FD->setInvalidDecl();
2203 return;
2204 }
2205
2206 InitExpr = Init.release();
2207
2208 FD->setInClassInitializer(InitExpr);
2209}
2210
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002211/// \brief Find the direct and/or virtual base specifiers that
2212/// correspond to the given base type, for use in base initialization
2213/// within a constructor.
2214static bool FindBaseInitializer(Sema &SemaRef,
2215 CXXRecordDecl *ClassDecl,
2216 QualType BaseType,
2217 const CXXBaseSpecifier *&DirectBaseSpec,
2218 const CXXBaseSpecifier *&VirtualBaseSpec) {
2219 // First, check for a direct base class.
2220 DirectBaseSpec = 0;
2221 for (CXXRecordDecl::base_class_const_iterator Base
2222 = ClassDecl->bases_begin();
2223 Base != ClassDecl->bases_end(); ++Base) {
2224 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2225 // We found a direct base of this type. That's what we're
2226 // initializing.
2227 DirectBaseSpec = &*Base;
2228 break;
2229 }
2230 }
2231
2232 // Check for a virtual base class.
2233 // FIXME: We might be able to short-circuit this if we know in advance that
2234 // there are no virtual bases.
2235 VirtualBaseSpec = 0;
2236 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2237 // We haven't found a base yet; search the class hierarchy for a
2238 // virtual base class.
2239 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2240 /*DetectVirtual=*/false);
2241 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2242 BaseType, Paths)) {
2243 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2244 Path != Paths.end(); ++Path) {
2245 if (Path->back().Base->isVirtual()) {
2246 VirtualBaseSpec = Path->back().Base;
2247 break;
2248 }
2249 }
2250 }
2251 }
2252
2253 return DirectBaseSpec || VirtualBaseSpec;
2254}
2255
Sebastian Redl6df65482011-09-24 17:48:25 +00002256/// \brief Handle a C++ member initializer using braced-init-list syntax.
2257MemInitResult
2258Sema::ActOnMemInitializer(Decl *ConstructorD,
2259 Scope *S,
2260 CXXScopeSpec &SS,
2261 IdentifierInfo *MemberOrBase,
2262 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002263 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002264 SourceLocation IdLoc,
2265 Expr *InitList,
2266 SourceLocation EllipsisLoc) {
2267 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002268 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00002269 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002270}
2271
2272/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00002273MemInitResult
John McCalld226f652010-08-21 09:40:31 +00002274Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002275 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00002276 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002277 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00002278 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002279 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00002280 SourceLocation IdLoc,
2281 SourceLocation LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002282 ArrayRef<Expr *> Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002283 SourceLocation RParenLoc,
2284 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002285 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
Dmitri Gribenkoa36bbac2013-05-09 23:51:52 +00002286 Args, RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002287 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002288 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00002289}
2290
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002291namespace {
2292
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00002293// Callback to only accept typo corrections that can be a valid C++ member
2294// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002295class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002296public:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002297 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2298 : ClassDecl(ClassDecl) {}
2299
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002300 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002301 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2302 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2303 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002304 return isa<TypeDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002305 }
2306 return false;
2307 }
2308
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002309private:
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002310 CXXRecordDecl *ClassDecl;
2311};
2312
2313}
2314
Sebastian Redl6df65482011-09-24 17:48:25 +00002315/// \brief Handle a C++ member initializer.
2316MemInitResult
2317Sema::BuildMemInitializer(Decl *ConstructorD,
2318 Scope *S,
2319 CXXScopeSpec &SS,
2320 IdentifierInfo *MemberOrBase,
2321 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00002322 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00002323 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002324 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002325 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00002326 if (!ConstructorD)
2327 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002328
Douglas Gregorefd5bda2009-08-24 11:57:43 +00002329 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00002330
2331 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00002332 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002333 if (!Constructor) {
2334 // The user wrote a constructor initializer on a function that is
2335 // not a C++ constructor. Ignore the error for now, because we may
2336 // have more member initializers coming; we'll diagnose it just
2337 // once in ActOnMemInitializers.
2338 return true;
2339 }
2340
2341 CXXRecordDecl *ClassDecl = Constructor->getParent();
2342
2343 // C++ [class.base.init]p2:
2344 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00002345 // constructor's class and, if not found in that scope, are looked
2346 // up in the scope containing the constructor's definition.
2347 // [Note: if the constructor's class contains a member with the
2348 // same name as a direct or virtual base class of the class, a
2349 // mem-initializer-id naming the member or base class and composed
2350 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00002351 // mem-initializer-id for the hidden base class may be specified
2352 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00002353 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002354 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00002355 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00002356 = ClassDecl->lookup(MemberOrBase);
David Blaikie3bc93e32012-12-19 00:45:41 +00002357 if (!Result.empty()) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00002358 ValueDecl *Member;
David Blaikie3bc93e32012-12-19 00:45:41 +00002359 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2360 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002361 if (EllipsisLoc.isValid())
2362 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002363 << MemberOrBase
2364 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002365
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002366 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002367 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00002368 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002369 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00002370 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00002371 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00002372 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00002373
2374 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00002375 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00002376 } else if (DS.getTypeSpecType() == TST_decltype) {
2377 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00002378 } else {
2379 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2380 LookupParsedName(R, S, &SS);
2381
2382 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2383 if (!TyD) {
2384 if (R.isAmbiguous()) return true;
2385
John McCallfd225442010-04-09 19:01:14 +00002386 // We don't want access-control diagnostics here.
2387 R.suppressDiagnostics();
2388
Douglas Gregor7a886e12010-01-19 06:46:48 +00002389 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2390 bool NotUnknownSpecialization = false;
2391 DeclContext *DC = computeDeclContext(SS, false);
2392 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2393 NotUnknownSpecialization = !Record->hasAnyDependentBases();
2394
2395 if (!NotUnknownSpecialization) {
2396 // When the scope specifier can refer to a member of an unknown
2397 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00002398 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2399 SS.getWithLocInContext(Context),
2400 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00002401 if (BaseType.isNull())
2402 return true;
2403
Douglas Gregor7a886e12010-01-19 06:46:48 +00002404 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00002405 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002406 }
2407 }
2408
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002409 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002410 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002411 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002412 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002413 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00002414 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002415 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00002416 // We have found a non-static data member with a similar
2417 // name to what was typed; complain and initialize that
2418 // member.
Richard Smith2d670972013-08-17 00:46:16 +00002419 diagnoseTypo(Corr,
2420 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2421 << MemberOrBase << true);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002422 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00002423 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002424 const CXXBaseSpecifier *DirectBaseSpec;
2425 const CXXBaseSpecifier *VirtualBaseSpec;
2426 if (FindBaseInitializer(*this, ClassDecl,
2427 Context.getTypeDeclType(Type),
2428 DirectBaseSpec, VirtualBaseSpec)) {
2429 // We have found a direct or virtual base class with a
2430 // similar name to what was typed; complain and initialize
2431 // that base class.
Richard Smith2d670972013-08-17 00:46:16 +00002432 diagnoseTypo(Corr,
2433 PDiag(diag::err_mem_init_not_member_or_class_suggest)
2434 << MemberOrBase << false,
2435 PDiag() /*Suppress note, we provide our own.*/);
Douglas Gregor0d535c82010-01-07 00:26:25 +00002436
Richard Smith2d670972013-08-17 00:46:16 +00002437 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2438 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00002439 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00002440 diag::note_base_class_specified_here)
2441 << BaseSpec->getType()
2442 << BaseSpec->getSourceRange();
2443
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002444 TyD = Type;
2445 }
2446 }
2447 }
2448
Douglas Gregor7a886e12010-01-19 06:46:48 +00002449 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002450 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002451 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00002452 return true;
2453 }
John McCall2b194412009-12-21 10:41:20 +00002454 }
2455
Douglas Gregor7a886e12010-01-19 06:46:48 +00002456 if (BaseType.isNull()) {
2457 BaseType = Context.getTypeDeclType(TyD);
2458 if (SS.isSet()) {
2459 NestedNameSpecifier *Qualifier =
2460 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002461
Douglas Gregor7a886e12010-01-19 06:46:48 +00002462 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002463 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002464 }
John McCall2b194412009-12-21 10:41:20 +00002465 }
2466 }
Mike Stump1eb44332009-09-09 15:08:12 +00002467
John McCalla93c9342009-12-07 02:54:59 +00002468 if (!TInfo)
2469 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002470
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002471 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002472}
2473
Chandler Carruth81c64772011-09-03 01:14:15 +00002474/// Checks a member initializer expression for cases where reference (or
2475/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002476static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2477 Expr *Init,
2478 SourceLocation IdLoc) {
2479 QualType MemberTy = Member->getType();
2480
2481 // We only handle pointers and references currently.
2482 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2483 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2484 return;
2485
2486 const bool IsPointer = MemberTy->isPointerType();
2487 if (IsPointer) {
2488 if (const UnaryOperator *Op
2489 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2490 // The only case we're worried about with pointers requires taking the
2491 // address.
2492 if (Op->getOpcode() != UO_AddrOf)
2493 return;
2494
2495 Init = Op->getSubExpr();
2496 } else {
2497 // We only handle address-of expression initializers for pointers.
2498 return;
2499 }
2500 }
2501
Richard Smitha4bb99c2013-06-12 21:51:50 +00002502 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002503 // We only warn when referring to a non-reference parameter declaration.
2504 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2505 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002506 return;
2507
2508 S.Diag(Init->getExprLoc(),
2509 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2510 : diag::warn_bind_ref_member_to_parameter)
2511 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002512 } else {
2513 // Other initializers are fine.
2514 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002515 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002516
2517 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2518 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002519}
2520
John McCallf312b1e2010-08-26 23:41:50 +00002521MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002522Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002523 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002524 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2525 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2526 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002527 "Member must be a FieldDecl or IndirectFieldDecl");
2528
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002529 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002530 return true;
2531
Douglas Gregor464b2f02010-11-05 22:21:31 +00002532 if (Member->isInvalidDecl())
2533 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002534
John McCallb4190042009-11-04 23:02:40 +00002535 // Diagnose value-uses of fields to initialize themselves, e.g.
2536 // foo(foo)
2537 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002538 // TODO: implement -Wuninitialized and fold this into that framework.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002539 MultiExprArg Args;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002540 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002541 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Richard Smithc83c2302012-12-19 01:39:02 +00002542 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002543 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
Richard Smithc83c2302012-12-19 01:39:02 +00002544 } else {
2545 // Template instantiation doesn't reconstruct ParenListExprs for us.
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002546 Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002547 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002548
Richard Trieude5e75c2012-06-14 23:11:34 +00002549 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2550 != DiagnosticsEngine::Ignored)
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002551 for (unsigned i = 0, e = Args.size(); i != e; ++i)
Richard Trieude5e75c2012-06-14 23:11:34 +00002552 // FIXME: Warn about the case when other fields are used before being
Hans Wennborg471f9852012-09-18 15:58:06 +00002553 // initialized. For example, let this field be the i'th field. When
John McCallb4190042009-11-04 23:02:40 +00002554 // initializing the i'th field, throw a warning if any of the >= i'th
2555 // fields are used, as they are not yet initialized.
2556 // Right now we are only handling the case where the i'th field uses
2557 // itself in its initializer.
Hans Wennborg471f9852012-09-18 15:58:06 +00002558 // Also need to take into account that some fields may be initialized by
2559 // in-class initializers, see C++11 [class.base.init]p9.
Richard Trieude5e75c2012-06-14 23:11:34 +00002560 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002561
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002562 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002563
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002564 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002565 // Can't check initialization for a member of dependent type or when
2566 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002567 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002568 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002569 bool InitList = false;
2570 if (isa<InitListExpr>(Init)) {
2571 InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002572 Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002573 }
2574
Chandler Carruth894aed92010-12-06 09:23:57 +00002575 // Initialize the member.
2576 InitializedEntity MemberEntity =
2577 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2578 : InitializedEntity::InitializeMember(IndirectMember, 0);
2579 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002580 InitList ? InitializationKind::CreateDirectList(IdLoc)
2581 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2582 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002583
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002584 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2585 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002586 if (MemberInit.isInvalid())
2587 return true;
2588
Richard Smith8a07cd32013-06-12 20:42:33 +00002589 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2590
Richard Smith41956372013-01-14 22:39:08 +00002591 // C++11 [class.base.init]p7:
Chandler Carruth894aed92010-12-06 09:23:57 +00002592 // The initialization of each base and member constitutes a
2593 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002594 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002595 if (MemberInit.isInvalid())
2596 return true;
2597
Richard Smithc83c2302012-12-19 01:39:02 +00002598 Init = MemberInit.get();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002599 }
2600
Chandler Carruth894aed92010-12-06 09:23:57 +00002601 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002602 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2603 InitRange.getBegin(), Init,
2604 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002605 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002606 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2607 InitRange.getBegin(), Init,
2608 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002609 }
Eli Friedman59c04372009-07-29 19:44:27 +00002610}
2611
John McCallf312b1e2010-08-26 23:41:50 +00002612MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002613Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002614 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002615 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Richard Smith80ad52f2013-01-02 11:42:31 +00002616 if (!LangOpts.CPlusPlus11)
Douglas Gregor76852c22011-11-01 01:16:03 +00002617 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002618 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002619 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002620
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002621 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002622 MultiExprArg Args = Init;
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002623 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2624 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002625 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002626 }
2627
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002628 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002629 // Initialize the object.
2630 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2631 QualType(ClassDecl->getTypeForDecl(), 0));
2632 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002633 InitList ? InitializationKind::CreateDirectList(NameLoc)
2634 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2635 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002636 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002637 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002638 Args, 0);
Sean Hunt41717662011-02-26 19:13:13 +00002639 if (DelegationInit.isInvalid())
2640 return true;
2641
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002642 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2643 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002644
Richard Smith41956372013-01-14 22:39:08 +00002645 // C++11 [class.base.init]p7:
Sean Hunt41717662011-02-26 19:13:13 +00002646 // The initialization of each base and member constitutes a
2647 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002648 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2649 InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002650 if (DelegationInit.isInvalid())
2651 return true;
2652
Eli Friedmand21016f2012-05-19 23:35:23 +00002653 // If we are in a dependent context, template instantiation will
2654 // perform this type-checking again. Just save the arguments that we
2655 // received in a ParenListExpr.
2656 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2657 // of the information that we have about the base
2658 // initializer. However, deconstructing the ASTs is a dicey process,
2659 // and this approach is far more likely to get the corner cases right.
2660 if (CurContext->isDependentContext())
2661 DelegationInit = Owned(Init);
2662
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002663 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002664 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002665 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002666}
2667
2668MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002669Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002670 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002671 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002672 SourceLocation BaseLoc
2673 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002674
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002675 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2676 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2677 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2678
2679 // C++ [class.base.init]p2:
2680 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002681 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002682 // of that class, the mem-initializer is ill-formed. A
2683 // mem-initializer-list can initialize a base class using any
2684 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002685 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002686
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002687 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002688 if (EllipsisLoc.isValid()) {
2689 // This is a pack expansion.
2690 if (!BaseType->containsUnexpandedParameterPack()) {
2691 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002692 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002693
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002694 EllipsisLoc = SourceLocation();
2695 }
2696 } else {
2697 // Check for any unexpanded parameter packs.
2698 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2699 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002700
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002701 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002702 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002703 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002704
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002705 // Check for direct and virtual base classes.
2706 const CXXBaseSpecifier *DirectBaseSpec = 0;
2707 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2708 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002709 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2710 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002711 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002712
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002713 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2714 VirtualBaseSpec);
2715
2716 // C++ [base.class.init]p2:
2717 // Unless the mem-initializer-id names a nonstatic data member of the
2718 // constructor's class or a direct or virtual base of that class, the
2719 // mem-initializer is ill-formed.
2720 if (!DirectBaseSpec && !VirtualBaseSpec) {
2721 // If the class has any dependent bases, then it's possible that
2722 // one of those types will resolve to the same type as
2723 // BaseType. Therefore, just treat this as a dependent base
2724 // class initialization. FIXME: Should we try to check the
2725 // initialization anyway? It seems odd.
2726 if (ClassDecl->hasAnyDependentBases())
2727 Dependent = true;
2728 else
2729 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2730 << BaseType << Context.getTypeDeclType(ClassDecl)
2731 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2732 }
2733 }
2734
2735 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002736 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002737
Sebastian Redl6df65482011-09-24 17:48:25 +00002738 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2739 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002740 InitRange.getBegin(), Init,
2741 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002742 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002743
2744 // C++ [base.class.init]p2:
2745 // If a mem-initializer-id is ambiguous because it designates both
2746 // a direct non-virtual base class and an inherited virtual base
2747 // class, the mem-initializer is ill-formed.
2748 if (DirectBaseSpec && VirtualBaseSpec)
2749 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002750 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002751
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002752 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002753 if (!BaseSpec)
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00002754 BaseSpec = VirtualBaseSpec;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002755
2756 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002757 bool InitList = true;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002758 MultiExprArg Args = Init;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002759 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002760 InitList = false;
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002761 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002762 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002763
2764 InitializedEntity BaseEntity =
2765 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2766 InitializationKind Kind =
2767 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2768 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2769 InitRange.getEnd());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002770 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2771 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002772 if (BaseInit.isInvalid())
2773 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002774
Richard Smith41956372013-01-14 22:39:08 +00002775 // C++11 [class.base.init]p7:
2776 // The initialization of each base and member constitutes a
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002777 // full-expression.
Richard Smith41956372013-01-14 22:39:08 +00002778 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002779 if (BaseInit.isInvalid())
2780 return true;
2781
2782 // If we are in a dependent context, template instantiation will
2783 // perform this type-checking again. Just save the arguments that we
2784 // received in a ParenListExpr.
2785 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2786 // of the information that we have about the base
2787 // initializer. However, deconstructing the ASTs is a dicey process,
2788 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002789 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002790 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002791
Sean Huntcbb67482011-01-08 20:30:50 +00002792 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002793 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002794 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002795 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002796 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002797}
2798
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002799// Create a static_cast\<T&&>(expr).
Richard Smith07b0fdc2013-03-18 21:12:30 +00002800static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2801 if (T.isNull()) T = E->getType();
2802 QualType TargetType = SemaRef.BuildReferenceType(
2803 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002804 SourceLocation ExprLoc = E->getLocStart();
2805 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2806 TargetType, ExprLoc);
2807
2808 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2809 SourceRange(ExprLoc, ExprLoc),
2810 E->getSourceRange()).take();
2811}
2812
Anders Carlssone5ef7402010-04-23 03:10:23 +00002813/// ImplicitInitializerKind - How an implicit base or member initializer should
2814/// initialize its base or member.
2815enum ImplicitInitializerKind {
2816 IIK_Default,
2817 IIK_Copy,
Richard Smith07b0fdc2013-03-18 21:12:30 +00002818 IIK_Move,
2819 IIK_Inherit
Anders Carlssone5ef7402010-04-23 03:10:23 +00002820};
2821
Anders Carlssondefefd22010-04-23 02:00:02 +00002822static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002823BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002824 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002825 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002826 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002827 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002828 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002829 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2830 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002831
John McCall60d7b3a2010-08-24 06:29:42 +00002832 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002833
2834 switch (ImplicitInitKind) {
Richard Smith07b0fdc2013-03-18 21:12:30 +00002835 case IIK_Inherit: {
2836 const CXXRecordDecl *Inherited =
2837 Constructor->getInheritedConstructor()->getParent();
2838 const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2839 if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2840 // C++11 [class.inhctor]p8:
2841 // Each expression in the expression-list is of the form
2842 // static_cast<T&&>(p), where p is the name of the corresponding
2843 // constructor parameter and T is the declared type of p.
2844 SmallVector<Expr*, 16> Args;
2845 for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2846 ParmVarDecl *PD = Constructor->getParamDecl(I);
2847 ExprResult ArgExpr =
2848 SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2849 VK_LValue, SourceLocation());
2850 if (ArgExpr.isInvalid())
2851 return true;
2852 Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2853 }
2854
2855 InitializationKind InitKind = InitializationKind::CreateDirect(
2856 Constructor->getLocation(), SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002857 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
Richard Smith07b0fdc2013-03-18 21:12:30 +00002858 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2859 break;
2860 }
2861 }
2862 // Fall through.
Anders Carlssone5ef7402010-04-23 03:10:23 +00002863 case IIK_Default: {
2864 InitializationKind InitKind
2865 = InitializationKind::CreateDefault(Constructor->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00002866 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2867 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002868 break;
2869 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002870
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002871 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002872 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002873 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002874 ParmVarDecl *Param = Constructor->getParamDecl(0);
2875 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002876
Anders Carlssone5ef7402010-04-23 03:10:23 +00002877 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002878 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002879 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002880 Constructor->getLocation(), ParamType,
2881 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002882
Eli Friedman5f2987c2012-02-02 03:46:19 +00002883 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2884
Anders Carlssonc7957502010-04-24 22:02:54 +00002885 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002886 QualType ArgTy =
2887 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2888 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002889
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002890 if (Moving) {
2891 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2892 }
2893
John McCallf871d0c2010-08-07 06:22:56 +00002894 CXXCastPath BasePath;
2895 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002896 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2897 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002898 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002899 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002900
Anders Carlssone5ef7402010-04-23 03:10:23 +00002901 InitializationKind InitKind
2902 = InitializationKind::CreateDirect(Constructor->getLocation(),
2903 SourceLocation(), SourceLocation());
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00002904 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2905 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002906 break;
2907 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002908 }
John McCall9ae2f072010-08-23 23:25:46 +00002909
Douglas Gregor53c374f2010-12-07 00:41:46 +00002910 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002911 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002912 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002913
Anders Carlssondefefd22010-04-23 02:00:02 +00002914 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002915 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002916 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2917 SourceLocation()),
2918 BaseSpec->isVirtual(),
2919 SourceLocation(),
2920 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002921 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002922 SourceLocation());
2923
Anders Carlssondefefd22010-04-23 02:00:02 +00002924 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002925}
2926
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002927static bool RefersToRValueRef(Expr *MemRef) {
2928 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2929 return Referenced->getType()->isRValueReferenceType();
2930}
2931
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002932static bool
2933BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002934 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002935 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002936 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002937 if (Field->isInvalidDecl())
2938 return true;
2939
Chandler Carruthf186b542010-06-29 23:50:44 +00002940 SourceLocation Loc = Constructor->getLocation();
2941
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002942 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2943 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002944 ParmVarDecl *Param = Constructor->getParamDecl(0);
2945 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002946
2947 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002948 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2949 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002950
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002951 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002952 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002953 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002954 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002955
Eli Friedman5f2987c2012-02-02 03:46:19 +00002956 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2957
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002958 if (Moving) {
2959 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2960 }
2961
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002962 // Build a reference to this field within the parameter.
2963 CXXScopeSpec SS;
2964 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2965 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002966 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2967 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002968 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002969 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002970 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002971 ParamType, Loc,
2972 /*IsArrow=*/false,
2973 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002974 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002975 /*FirstQualifierInScope=*/0,
2976 MemberLookup,
2977 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002978 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002979 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002980
2981 // C++11 [class.copy]p15:
2982 // - if a member m has rvalue reference type T&&, it is direct-initialized
2983 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002984 if (RefersToRValueRef(CtorArg.get())) {
2985 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002986 }
2987
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002988 // When the field we are copying is an array, create index variables for
2989 // each dimension of the array. We use these index variables to subscript
2990 // the source array, and other clients (e.g., CodeGen) will perform the
2991 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002992 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002993 QualType BaseType = Field->getType();
2994 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002995 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002996 while (const ConstantArrayType *Array
2997 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002998 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002999 // Create the iteration variable for this array index.
3000 IdentifierInfo *IterationVarName = 0;
3001 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003002 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003003 llvm::raw_svector_ostream OS(Str);
3004 OS << "__i" << IndexVariables.size();
3005 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3006 }
3007 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003008 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003009 IterationVarName, SizeType,
3010 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003011 SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003012 IndexVariables.push_back(IterationVar);
3013
3014 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00003015 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00003016 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003017 assert(!IterationVarRef.isInvalid() &&
3018 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00003019 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3020 assert(!IterationVarRef.isInvalid() &&
3021 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00003022
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003023 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00003024 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00003025 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00003026 Loc);
3027 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003028 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003029
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003030 BaseType = Array->getElementType();
3031 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003032
3033 // The array subscript expression is an lvalue, which is wrong for moving.
3034 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00003035 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003036
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003037 // Construct the entity that we will be initializing. For an array, this
3038 // will be first element in the array, which may require several levels
3039 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003040 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003041 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003042 if (Indirect)
3043 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3044 else
3045 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003046 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3047 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3048 0,
3049 Entities.back()));
3050
3051 // Direct-initialize to use the copy constructor.
3052 InitializationKind InitKind =
3053 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3054
Sebastian Redl74e611a2011-09-04 18:14:28 +00003055 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00003056 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003057
John McCall60d7b3a2010-08-24 06:29:42 +00003058 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003059 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00003060 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00003061 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00003062 if (MemberInit.isInvalid())
3063 return true;
3064
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003065 if (Indirect) {
3066 assert(IndexVariables.size() == 0 &&
3067 "Indirect field improperly initialized");
3068 CXXMemberInit
3069 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3070 Loc, Loc,
3071 MemberInit.takeAs<Expr>(),
3072 Loc);
3073 } else
3074 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3075 Loc, MemberInit.takeAs<Expr>(),
3076 Loc,
3077 IndexVariables.data(),
3078 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00003079 return false;
3080 }
3081
Richard Smith07b0fdc2013-03-18 21:12:30 +00003082 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3083 "Unhandled implicit init kind!");
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003084
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003085 QualType FieldBaseElementType =
3086 SemaRef.Context.getBaseElementType(Field->getType());
3087
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003088 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003089 InitializedEntity InitEntity
3090 = Indirect? InitializedEntity::InitializeMember(Indirect)
3091 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00003092 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00003093 InitializationKind::CreateDefault(Loc);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00003094
3095 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3096 ExprResult MemberInit =
3097 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
John McCall9ae2f072010-08-23 23:25:46 +00003098
Douglas Gregor53c374f2010-12-07 00:41:46 +00003099 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003100 if (MemberInit.isInvalid())
3101 return true;
3102
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003103 if (Indirect)
3104 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3105 Indirect, Loc,
3106 Loc,
3107 MemberInit.get(),
3108 Loc);
3109 else
3110 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3111 Field, Loc, Loc,
3112 MemberInit.get(),
3113 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003114 return false;
3115 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003116
Sean Hunt1f2f3842011-05-17 00:19:05 +00003117 if (!Field->getParent()->isUnion()) {
3118 if (FieldBaseElementType->isReferenceType()) {
3119 SemaRef.Diag(Constructor->getLocation(),
3120 diag::err_uninitialized_member_in_ctor)
3121 << (int)Constructor->isImplicit()
3122 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3123 << 0 << Field->getDeclName();
3124 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3125 return true;
3126 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003127
Sean Hunt1f2f3842011-05-17 00:19:05 +00003128 if (FieldBaseElementType.isConstQualified()) {
3129 SemaRef.Diag(Constructor->getLocation(),
3130 diag::err_uninitialized_member_in_ctor)
3131 << (int)Constructor->isImplicit()
3132 << SemaRef.Context.getTagDeclType(Constructor->getParent())
3133 << 1 << Field->getDeclName();
3134 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3135 return true;
3136 }
Anders Carlsson114a2972010-04-23 03:07:47 +00003137 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003138
David Blaikie4e4d0842012-03-11 07:00:24 +00003139 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00003140 FieldBaseElementType->isObjCRetainableType() &&
3141 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3142 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00003143 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00003144 // Default-initialize Objective-C pointers to NULL.
3145 CXXMemberInit
3146 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3147 Loc, Loc,
3148 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3149 Loc);
3150 return false;
3151 }
3152
Anders Carlssonddfb75f2010-04-23 02:15:47 +00003153 // Nothing to initialize.
3154 CXXMemberInit = 0;
3155 return false;
3156}
John McCallf1860e52010-05-20 23:23:51 +00003157
3158namespace {
3159struct BaseAndFieldInfo {
3160 Sema &S;
3161 CXXConstructorDecl *Ctor;
3162 bool AnyErrorsInInits;
3163 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00003164 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003165 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00003166
3167 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3168 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003169 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3170 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00003171 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003172 else if (Generated && Ctor->isMoveConstructor())
3173 IIK = IIK_Move;
Richard Smith07b0fdc2013-03-18 21:12:30 +00003174 else if (Ctor->getInheritedConstructor())
3175 IIK = IIK_Inherit;
John McCallf1860e52010-05-20 23:23:51 +00003176 else
3177 IIK = IIK_Default;
3178 }
Douglas Gregorf4853882011-11-28 20:03:15 +00003179
3180 bool isImplicitCopyOrMove() const {
3181 switch (IIK) {
3182 case IIK_Copy:
3183 case IIK_Move:
3184 return true;
3185
3186 case IIK_Default:
Richard Smith07b0fdc2013-03-18 21:12:30 +00003187 case IIK_Inherit:
Douglas Gregorf4853882011-11-28 20:03:15 +00003188 return false;
3189 }
David Blaikie30263482012-01-20 21:50:17 +00003190
3191 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00003192 }
Richard Smith0b8220a2012-08-07 21:30:42 +00003193
3194 bool addFieldInitializer(CXXCtorInitializer *Init) {
3195 AllToInit.push_back(Init);
3196
3197 // Check whether this initializer makes the field "used".
Richard Smithc3bf52c2013-04-20 22:23:05 +00003198 if (Init->getInit()->HasSideEffects(S.Context))
Richard Smith0b8220a2012-08-07 21:30:42 +00003199 S.UnusedPrivateFields.remove(Init->getAnyMember());
3200
3201 return false;
3202 }
John McCallf1860e52010-05-20 23:23:51 +00003203};
3204}
3205
Richard Smitha4950662011-09-19 13:34:43 +00003206/// \brief Determine whether the given indirect field declaration is somewhere
3207/// within an anonymous union.
3208static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3209 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3210 CEnd = F->chain_end();
3211 C != CEnd; ++C)
3212 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3213 if (Record->isUnion())
3214 return true;
3215
3216 return false;
3217}
3218
Douglas Gregorddb21472011-11-02 23:04:16 +00003219/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3220/// array type.
3221static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3222 if (T->isIncompleteArrayType())
3223 return true;
3224
3225 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3226 if (!ArrayT->getSize())
3227 return true;
3228
3229 T = ArrayT->getElementType();
3230 }
3231
3232 return false;
3233}
3234
Richard Smith7a614d82011-06-11 17:19:42 +00003235static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003236 FieldDecl *Field,
3237 IndirectFieldDecl *Indirect = 0) {
Eli Friedman5fb478b2013-06-28 21:07:41 +00003238 if (Field->isInvalidDecl())
3239 return false;
John McCallf1860e52010-05-20 23:23:51 +00003240
Chandler Carruthe861c602010-06-30 02:59:29 +00003241 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00003242 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3243 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003244
Richard Smith0b8220a2012-08-07 21:30:42 +00003245 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00003246 // has a brace-or-equal-initializer, the entity is initialized as specified
3247 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00003248 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Richard Smithc3bf52c2013-04-20 22:23:05 +00003249 Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3250 Info.Ctor->getLocation(), Field);
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003251 CXXCtorInitializer *Init;
3252 if (Indirect)
3253 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3254 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003255 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003256 SourceLocation());
3257 else
3258 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3259 SourceLocation(),
Richard Smithc3bf52c2013-04-20 22:23:05 +00003260 SourceLocation(), DIE,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003261 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00003262 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00003263 }
3264
Richard Smithc115f632011-09-18 11:14:50 +00003265 // Don't build an implicit initializer for union members if none was
3266 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00003267 if (Field->getParent()->isUnion() ||
3268 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00003269 return false;
3270
Douglas Gregorddb21472011-11-02 23:04:16 +00003271 // Don't initialize incomplete or zero-length arrays.
3272 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3273 return false;
3274
John McCallf1860e52010-05-20 23:23:51 +00003275 // Don't try to build an implicit initializer if there were semantic
3276 // errors in any of the initializers (and therefore we might be
3277 // missing some that the user actually wrote).
Eli Friedman5fb478b2013-06-28 21:07:41 +00003278 if (Info.AnyErrorsInInits)
John McCallf1860e52010-05-20 23:23:51 +00003279 return false;
3280
Sean Huntcbb67482011-01-08 20:30:50 +00003281 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003282 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3283 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00003284 return true;
John McCallf1860e52010-05-20 23:23:51 +00003285
Richard Smith0b8220a2012-08-07 21:30:42 +00003286 if (!Init)
3287 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00003288
Richard Smith0b8220a2012-08-07 21:30:42 +00003289 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00003290}
Sean Hunt059ce0d2011-05-01 07:04:31 +00003291
3292bool
3293Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3294 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00003295 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00003296 Constructor->setNumCtorInitializers(1);
3297 CXXCtorInitializer **initializer =
3298 new (Context) CXXCtorInitializer*[1];
3299 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3300 Constructor->setCtorInitializers(initializer);
3301
Sean Huntb76af9c2011-05-03 23:05:34 +00003302 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003303 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00003304 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3305 }
3306
Sean Huntc1598702011-05-05 00:05:47 +00003307 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00003308
Sean Hunt059ce0d2011-05-01 07:04:31 +00003309 return false;
3310}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003311
David Blaikie93c86172013-01-17 05:26:25 +00003312bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3313 ArrayRef<CXXCtorInitializer *> Initializers) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00003314 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003315 // Just store the initializers as written, they will be checked during
3316 // instantiation.
David Blaikie93c86172013-01-17 05:26:25 +00003317 if (!Initializers.empty()) {
3318 Constructor->setNumCtorInitializers(Initializers.size());
Sean Huntcbb67482011-01-08 20:30:50 +00003319 CXXCtorInitializer **baseOrMemberInitializers =
David Blaikie93c86172013-01-17 05:26:25 +00003320 new (Context) CXXCtorInitializer*[Initializers.size()];
3321 memcpy(baseOrMemberInitializers, Initializers.data(),
3322 Initializers.size() * sizeof(CXXCtorInitializer*));
Sean Huntcbb67482011-01-08 20:30:50 +00003323 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003324 }
Richard Smith54b3ba82012-09-25 00:23:05 +00003325
3326 // Let template instantiation know whether we had errors.
3327 if (AnyErrors)
3328 Constructor->setInvalidDecl();
3329
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003330 return false;
3331 }
3332
John McCallf1860e52010-05-20 23:23:51 +00003333 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00003334
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003335 // We need to build the initializer AST according to order of construction
3336 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00003337 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00003338 if (!ClassDecl)
3339 return true;
3340
Eli Friedman80c30da2009-11-09 19:20:36 +00003341 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003342
David Blaikie93c86172013-01-17 05:26:25 +00003343 for (unsigned i = 0; i < Initializers.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003344 CXXCtorInitializer *Member = Initializers[i];
Richard Smithcbc820a2013-07-22 02:56:56 +00003345
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003346 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00003347 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003348 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00003349 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003350 }
3351
Anders Carlsson711f34a2010-04-21 19:52:01 +00003352 // Keep track of the direct virtual bases.
3353 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3354 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3355 E = ClassDecl->bases_end(); I != E; ++I) {
3356 if (I->isVirtual())
3357 DirectVBases.insert(I);
3358 }
3359
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003360 // Push virtual bases before others.
3361 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3362 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3363
Sean Huntcbb67482011-01-08 20:30:50 +00003364 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003365 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
Richard Smithcbc820a2013-07-22 02:56:56 +00003366 // [class.base.init]p7, per DR257:
3367 // A mem-initializer where the mem-initializer-id names a virtual base
3368 // class is ignored during execution of a constructor of any class that
3369 // is not the most derived class.
3370 if (ClassDecl->isAbstract()) {
3371 // FIXME: Provide a fixit to remove the base specifier. This requires
3372 // tracking the location of the associated comma for a base specifier.
3373 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3374 << VBase->getType() << ClassDecl;
3375 DiagnoseAbstractType(ClassDecl);
3376 }
3377
John McCallf1860e52010-05-20 23:23:51 +00003378 Info.AllToInit.push_back(Value);
Richard Smithcbc820a2013-07-22 02:56:56 +00003379 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3380 // [class.base.init]p8, per DR257:
3381 // If a given [...] base class is not named by a mem-initializer-id
3382 // [...] and the entity is not a virtual base class of an abstract
3383 // class, then [...] the entity is default-initialized.
Anders Carlsson711f34a2010-04-21 19:52:01 +00003384 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003385 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003386 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Richard Smithcbc820a2013-07-22 02:56:56 +00003387 VBase, IsInheritedVirtualBase,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003388 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003389 HadError = true;
3390 continue;
3391 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003392
John McCallf1860e52010-05-20 23:23:51 +00003393 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003394 }
3395 }
Mike Stump1eb44332009-09-09 15:08:12 +00003396
John McCallf1860e52010-05-20 23:23:51 +00003397 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003398 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3399 E = ClassDecl->bases_end(); Base != E; ++Base) {
3400 // Virtuals are in the virtual base list and already constructed.
3401 if (Base->isVirtual())
3402 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003403
Sean Huntcbb67482011-01-08 20:30:50 +00003404 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003405 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3406 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003407 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003408 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003409 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003410 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003411 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003412 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003413 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003414 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003415
John McCallf1860e52010-05-20 23:23:51 +00003416 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003417 }
3418 }
Mike Stump1eb44332009-09-09 15:08:12 +00003419
John McCallf1860e52010-05-20 23:23:51 +00003420 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003421 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3422 MemEnd = ClassDecl->decls_end();
3423 Mem != MemEnd; ++Mem) {
3424 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003425 // C++ [class.bit]p2:
3426 // A declaration for a bit-field that omits the identifier declares an
3427 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3428 // initialized.
3429 if (F->isUnnamedBitfield())
3430 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003431
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003432 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003433 // handle anonymous struct/union fields based on their individual
3434 // indirect fields.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003435 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003436 continue;
3437
3438 if (CollectFieldInitializer(*this, Info, F))
3439 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003440 continue;
3441 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003442
3443 // Beyond this point, we only consider default initialization.
Richard Smith07b0fdc2013-03-18 21:12:30 +00003444 if (Info.isImplicitCopyOrMove())
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003445 continue;
3446
3447 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3448 if (F->getType()->isIncompleteArrayType()) {
3449 assert(ClassDecl->hasFlexibleArrayMember() &&
3450 "Incomplete array type is not valid");
3451 continue;
3452 }
3453
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003454 // Initialize each field of an anonymous struct individually.
3455 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3456 HadError = true;
3457
3458 continue;
3459 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003460 }
Mike Stump1eb44332009-09-09 15:08:12 +00003461
David Blaikie93c86172013-01-17 05:26:25 +00003462 unsigned NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003463 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003464 Constructor->setNumCtorInitializers(NumInitializers);
3465 CXXCtorInitializer **baseOrMemberInitializers =
3466 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003467 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003468 NumInitializers * sizeof(CXXCtorInitializer*));
3469 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003470
John McCallef027fe2010-03-16 21:39:52 +00003471 // Constructors implicitly reference the base and member
3472 // destructors.
3473 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3474 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003475 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003476
3477 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003478}
3479
David Blaikieee000bb2013-01-17 08:49:22 +00003480static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003481 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
David Blaikieee000bb2013-01-17 08:49:22 +00003482 const RecordDecl *RD = RT->getDecl();
3483 if (RD->isAnonymousStructOrUnion()) {
3484 for (RecordDecl::field_iterator Field = RD->field_begin(),
3485 E = RD->field_end(); Field != E; ++Field)
3486 PopulateKeysForFields(*Field, IdealInits);
3487 return;
3488 }
Eli Friedman6347f422009-07-21 19:28:10 +00003489 }
David Blaikieee000bb2013-01-17 08:49:22 +00003490 IdealInits.push_back(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003491}
3492
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003493static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3494 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003495}
3496
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003497static const void *GetKeyForMember(ASTContext &Context,
3498 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003499 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003500 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003501
David Blaikieee000bb2013-01-17 08:49:22 +00003502 return Member->getAnyMember();
Eli Friedman6347f422009-07-21 19:28:10 +00003503}
3504
David Blaikie93c86172013-01-17 05:26:25 +00003505static void DiagnoseBaseOrMemInitializerOrder(
3506 Sema &SemaRef, const CXXConstructorDecl *Constructor,
3507 ArrayRef<CXXCtorInitializer *> Inits) {
John McCalld6ca8da2010-04-10 07:37:23 +00003508 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003509 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003510
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003511 // Don't check initializers order unless the warning is enabled at the
3512 // location of at least one initializer.
3513 bool ShouldCheckOrder = false;
David Blaikie93c86172013-01-17 05:26:25 +00003514 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003515 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003516 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3517 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003518 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003519 ShouldCheckOrder = true;
3520 break;
3521 }
3522 }
3523 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003524 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003525
John McCalld6ca8da2010-04-10 07:37:23 +00003526 // Build the list of bases and members in the order that they'll
3527 // actually be initialized. The explicit initializers should be in
3528 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003529 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003530
Anders Carlsson071d6102010-04-02 03:38:04 +00003531 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3532
John McCalld6ca8da2010-04-10 07:37:23 +00003533 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003534 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003535 ClassDecl->vbases_begin(),
3536 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003537 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003538
John McCalld6ca8da2010-04-10 07:37:23 +00003539 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003540 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003541 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003542 if (Base->isVirtual())
3543 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003544 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003545 }
Mike Stump1eb44332009-09-09 15:08:12 +00003546
John McCalld6ca8da2010-04-10 07:37:23 +00003547 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003548 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003549 E = ClassDecl->field_end(); Field != E; ++Field) {
3550 if (Field->isUnnamedBitfield())
3551 continue;
3552
David Blaikieee000bb2013-01-17 08:49:22 +00003553 PopulateKeysForFields(*Field, IdealInitKeys);
Douglas Gregord61db332011-10-10 17:22:13 +00003554 }
3555
John McCalld6ca8da2010-04-10 07:37:23 +00003556 unsigned NumIdealInits = IdealInitKeys.size();
3557 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003558
Sean Huntcbb67482011-01-08 20:30:50 +00003559 CXXCtorInitializer *PrevInit = 0;
David Blaikie93c86172013-01-17 05:26:25 +00003560 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003561 CXXCtorInitializer *Init = Inits[InitIndex];
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003562 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003563
3564 // Scan forward to try to find this initializer in the idealized
3565 // initializers list.
3566 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3567 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003568 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003569
3570 // If we didn't find this initializer, it must be because we
3571 // scanned past it on a previous iteration. That can only
3572 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003573 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003574 Sema::SemaDiagnosticBuilder D =
3575 SemaRef.Diag(PrevInit->getSourceLocation(),
3576 diag::warn_initializer_out_of_order);
3577
Francois Pichet00eb3f92010-12-04 09:14:42 +00003578 if (PrevInit->isAnyMemberInitializer())
3579 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003580 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003581 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003582
Francois Pichet00eb3f92010-12-04 09:14:42 +00003583 if (Init->isAnyMemberInitializer())
3584 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003585 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003586 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003587
3588 // Move back to the initializer's location in the ideal list.
3589 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3590 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003591 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003592
3593 assert(IdealIndex != NumIdealInits &&
3594 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003595 }
John McCalld6ca8da2010-04-10 07:37:23 +00003596
3597 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003598 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003599}
3600
John McCall3c3ccdb2010-04-10 09:28:51 +00003601namespace {
3602bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003603 CXXCtorInitializer *Init,
3604 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003605 if (!PrevInit) {
3606 PrevInit = Init;
3607 return false;
3608 }
3609
Douglas Gregordc392c12013-03-25 23:28:23 +00003610 if (FieldDecl *Field = Init->getAnyMember())
John McCall3c3ccdb2010-04-10 09:28:51 +00003611 S.Diag(Init->getSourceLocation(),
3612 diag::err_multiple_mem_initialization)
3613 << Field->getDeclName()
3614 << Init->getSourceRange();
3615 else {
John McCallf4c73712011-01-19 06:33:43 +00003616 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003617 assert(BaseClass && "neither field nor base");
3618 S.Diag(Init->getSourceLocation(),
3619 diag::err_multiple_base_initialization)
3620 << QualType(BaseClass, 0)
3621 << Init->getSourceRange();
3622 }
3623 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3624 << 0 << PrevInit->getSourceRange();
3625
3626 return true;
3627}
3628
Sean Huntcbb67482011-01-08 20:30:50 +00003629typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003630typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3631
3632bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003633 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003634 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003635 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003636 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003637 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003638
3639 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003640 if (Parent->isUnion()) {
3641 UnionEntry &En = Unions[Parent];
3642 if (En.first && En.first != Child) {
3643 S.Diag(Init->getSourceLocation(),
3644 diag::err_multiple_mem_union_initialization)
3645 << Field->getDeclName()
3646 << Init->getSourceRange();
3647 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3648 << 0 << En.second->getSourceRange();
3649 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003650 }
3651 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003652 En.first = Child;
3653 En.second = Init;
3654 }
David Blaikie6fe29652011-11-17 06:01:57 +00003655 if (!Parent->isAnonymousStructOrUnion())
3656 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003657 }
3658
3659 Child = Parent;
3660 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003661 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003662
3663 return false;
3664}
3665}
3666
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003667/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003668void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003669 SourceLocation ColonLoc,
David Blaikie93c86172013-01-17 05:26:25 +00003670 ArrayRef<CXXCtorInitializer*> MemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003671 bool AnyErrors) {
3672 if (!ConstructorDecl)
3673 return;
3674
3675 AdjustDeclIfTemplate(ConstructorDecl);
3676
3677 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003678 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003679
3680 if (!Constructor) {
3681 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3682 return;
3683 }
3684
John McCall3c3ccdb2010-04-10 09:28:51 +00003685 // Mapping for the duplicate initializers check.
3686 // For member initializers, this is keyed with a FieldDecl*.
3687 // For base initializers, this is keyed with a Type*.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003688 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003689
3690 // Mapping for the inconsistent anonymous-union initializers check.
3691 RedundantUnionMap MemberUnions;
3692
Anders Carlssonea356fb2010-04-02 05:42:15 +00003693 bool HadError = false;
David Blaikie93c86172013-01-17 05:26:25 +00003694 for (unsigned i = 0; i < MemInits.size(); i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003695 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003696
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003697 // Set the source order index.
3698 Init->setSourceOrder(i);
3699
Francois Pichet00eb3f92010-12-04 09:14:42 +00003700 if (Init->isAnyMemberInitializer()) {
3701 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003702 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3703 CheckRedundantUnionInit(*this, Init, MemberUnions))
3704 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003705 } else if (Init->isBaseInitializer()) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003706 const void *Key =
3707 GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
John McCall3c3ccdb2010-04-10 09:28:51 +00003708 if (CheckRedundantInit(*this, Init, Members[Key]))
3709 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003710 } else {
3711 assert(Init->isDelegatingInitializer());
3712 // This must be the only initializer
David Blaikie93c86172013-01-17 05:26:25 +00003713 if (MemInits.size() != 1) {
Richard Smitha6ddea62012-09-14 18:21:10 +00003714 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003715 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003716 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003717 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003718 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003719 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003720 // Return immediately as the initializer is set.
3721 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003722 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003723 }
3724
Anders Carlssonea356fb2010-04-02 05:42:15 +00003725 if (HadError)
3726 return;
3727
David Blaikie93c86172013-01-17 05:26:25 +00003728 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003729
David Blaikie93c86172013-01-17 05:26:25 +00003730 SetCtorInitializers(Constructor, AnyErrors, MemInits);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003731}
3732
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003733void
John McCallef027fe2010-03-16 21:39:52 +00003734Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3735 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003736 // Ignore dependent contexts. Also ignore unions, since their members never
3737 // have destructors implicitly called.
3738 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003739 return;
John McCall58e6f342010-03-16 05:22:47 +00003740
3741 // FIXME: all the access-control diagnostics are positioned on the
3742 // field/base declaration. That's probably good; that said, the
3743 // user might reasonably want to know why the destructor is being
3744 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003745
Anders Carlsson9f853df2009-11-17 04:44:12 +00003746 // Non-static data members.
3747 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3748 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003749 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003750 if (Field->isInvalidDecl())
3751 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003752
3753 // Don't destroy incomplete or zero-length arrays.
3754 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3755 continue;
3756
Anders Carlsson9f853df2009-11-17 04:44:12 +00003757 QualType FieldType = Context.getBaseElementType(Field->getType());
3758
3759 const RecordType* RT = FieldType->getAs<RecordType>();
3760 if (!RT)
3761 continue;
3762
3763 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003764 if (FieldClassDecl->isInvalidDecl())
3765 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003766 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003767 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003768 // The destructor for an implicit anonymous union member is never invoked.
3769 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3770 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003771
Douglas Gregordb89f282010-07-01 22:47:18 +00003772 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003773 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003774 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003775 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003776 << Field->getDeclName()
3777 << FieldType);
3778
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003779 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003780 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003781 }
3782
John McCall58e6f342010-03-16 05:22:47 +00003783 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3784
Anders Carlsson9f853df2009-11-17 04:44:12 +00003785 // Bases.
3786 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3787 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003788 // Bases are always records in a well-formed non-dependent class.
3789 const RecordType *RT = Base->getType()->getAs<RecordType>();
3790
3791 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003792 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003793 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003794
John McCall58e6f342010-03-16 05:22:47 +00003795 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003796 // If our base class is invalid, we probably can't get its dtor anyway.
3797 if (BaseClassDecl->isInvalidDecl())
3798 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003799 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003800 continue;
John McCall58e6f342010-03-16 05:22:47 +00003801
Douglas Gregordb89f282010-07-01 22:47:18 +00003802 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003803 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003804
3805 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003806 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003807 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003808 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003809 << Base->getSourceRange(),
3810 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003811
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003812 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003813 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003814 }
3815
3816 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003817 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3818 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003819
3820 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003821 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003822
3823 // Ignore direct virtual bases.
3824 if (DirectVirtualBases.count(RT))
3825 continue;
3826
John McCall58e6f342010-03-16 05:22:47 +00003827 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003828 // If our base class is invalid, we probably can't get its dtor anyway.
3829 if (BaseClassDecl->isInvalidDecl())
3830 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003831 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003832 continue;
John McCall58e6f342010-03-16 05:22:47 +00003833
Douglas Gregordb89f282010-07-01 22:47:18 +00003834 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003835 assert(Dtor && "No dtor found for BaseClassDecl!");
David Majnemer2f686692013-06-22 06:43:58 +00003836 if (CheckDestructorAccess(
3837 ClassDecl->getLocation(), Dtor,
3838 PDiag(diag::err_access_dtor_vbase)
3839 << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3840 Context.getTypeDeclType(ClassDecl)) ==
3841 AR_accessible) {
3842 CheckDerivedToBaseConversion(
3843 Context.getTypeDeclType(ClassDecl), VBase->getType(),
3844 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3845 SourceRange(), DeclarationName(), 0);
3846 }
John McCall58e6f342010-03-16 05:22:47 +00003847
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003848 MarkFunctionReferenced(Location, Dtor);
Richard Smith213d70b2012-02-18 04:13:32 +00003849 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003850 }
3851}
3852
John McCalld226f652010-08-21 09:40:31 +00003853void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003854 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003855 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Mike Stump1eb44332009-09-09 15:08:12 +00003857 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003858 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
David Blaikie93c86172013-01-17 05:26:25 +00003859 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003860}
3861
Mike Stump1eb44332009-09-09 15:08:12 +00003862bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003863 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003864 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3865 unsigned DiagID;
3866 AbstractDiagSelID SelID;
3867
3868 public:
3869 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3870 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00003871
3872 void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
Eli Friedman2217f852012-08-14 02:06:07 +00003873 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003874 if (SelID == -1)
3875 S.Diag(Loc, DiagID) << T;
3876 else
3877 S.Diag(Loc, DiagID) << SelID << T;
3878 }
3879 } Diagnoser(DiagID, SelID);
3880
3881 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003882}
3883
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003884bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003885 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003886 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003887 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003888
Anders Carlsson11f21a02009-03-23 19:10:31 +00003889 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003890 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003891
Ted Kremenek6217b802009-07-29 21:53:49 +00003892 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003893 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003894 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003895 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003896
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003897 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003898 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003899 }
Mike Stump1eb44332009-09-09 15:08:12 +00003900
Ted Kremenek6217b802009-07-29 21:53:49 +00003901 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003902 if (!RT)
3903 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003904
John McCall86ff3082010-02-04 22:26:26 +00003905 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003906
John McCall94c3b562010-08-18 09:41:07 +00003907 // We can't answer whether something is abstract until it has a
3908 // definition. If it's currently being defined, we'll walk back
3909 // over all the declarations when we have a full definition.
3910 const CXXRecordDecl *Def = RD->getDefinition();
3911 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003912 return false;
3913
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003914 if (!RD->isAbstract())
3915 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003916
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003917 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003918 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003919
John McCall94c3b562010-08-18 09:41:07 +00003920 return true;
3921}
3922
3923void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3924 // Check if we've already emitted the list of pure virtual functions
3925 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003926 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003927 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003928
Richard Smithcbc820a2013-07-22 02:56:56 +00003929 // If the diagnostic is suppressed, don't emit the notes. We're only
3930 // going to emit them once, so try to attach them to a diagnostic we're
3931 // actually going to show.
3932 if (Diags.isLastDiagnosticIgnored())
3933 return;
3934
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003935 CXXFinalOverriderMap FinalOverriders;
3936 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003937
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003938 // Keep a set of seen pure methods so we won't diagnose the same method
3939 // more than once.
3940 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3941
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003942 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3943 MEnd = FinalOverriders.end();
3944 M != MEnd;
3945 ++M) {
3946 for (OverridingMethods::iterator SO = M->second.begin(),
3947 SOEnd = M->second.end();
3948 SO != SOEnd; ++SO) {
3949 // C++ [class.abstract]p4:
3950 // A class is abstract if it contains or inherits at least one
3951 // pure virtual function for which the final overrider is pure
3952 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003953
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003954 //
3955 if (SO->second.size() != 1)
3956 continue;
3957
3958 if (!SO->second.front().Method->isPure())
3959 continue;
3960
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003961 if (!SeenPureMethods.insert(SO->second.front().Method))
3962 continue;
3963
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003964 Diag(SO->second.front().Method->getLocation(),
3965 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003966 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003967 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003968 }
3969
3970 if (!PureVirtualClassDiagSet)
3971 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3972 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003973}
3974
Anders Carlsson8211eff2009-03-24 01:19:16 +00003975namespace {
John McCall94c3b562010-08-18 09:41:07 +00003976struct AbstractUsageInfo {
3977 Sema &S;
3978 CXXRecordDecl *Record;
3979 CanQualType AbstractType;
3980 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003981
John McCall94c3b562010-08-18 09:41:07 +00003982 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3983 : S(S), Record(Record),
3984 AbstractType(S.Context.getCanonicalType(
3985 S.Context.getTypeDeclType(Record))),
3986 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003987
John McCall94c3b562010-08-18 09:41:07 +00003988 void DiagnoseAbstractType() {
3989 if (Invalid) return;
3990 S.DiagnoseAbstractType(Record);
3991 Invalid = true;
3992 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003993
John McCall94c3b562010-08-18 09:41:07 +00003994 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3995};
3996
3997struct CheckAbstractUsage {
3998 AbstractUsageInfo &Info;
3999 const NamedDecl *Ctx;
4000
4001 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4002 : Info(Info), Ctx(Ctx) {}
4003
4004 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4005 switch (TL.getTypeLocClass()) {
4006#define ABSTRACT_TYPELOC(CLASS, PARENT)
4007#define TYPELOC(CLASS, PARENT) \
David Blaikie39e6ab42013-02-18 22:06:02 +00004008 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
John McCall94c3b562010-08-18 09:41:07 +00004009#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00004010 }
John McCall94c3b562010-08-18 09:41:07 +00004011 }
Mike Stump1eb44332009-09-09 15:08:12 +00004012
John McCall94c3b562010-08-18 09:41:07 +00004013 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4014 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4015 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00004016 if (!TL.getArg(I))
4017 continue;
4018
John McCall94c3b562010-08-18 09:41:07 +00004019 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4020 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004021 }
John McCall94c3b562010-08-18 09:41:07 +00004022 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004023
John McCall94c3b562010-08-18 09:41:07 +00004024 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4025 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4026 }
Mike Stump1eb44332009-09-09 15:08:12 +00004027
John McCall94c3b562010-08-18 09:41:07 +00004028 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4029 // Visit the type parameters from a permissive context.
4030 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4031 TemplateArgumentLoc TAL = TL.getArgLoc(I);
4032 if (TAL.getArgument().getKind() == TemplateArgument::Type)
4033 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4034 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4035 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00004036 }
John McCall94c3b562010-08-18 09:41:07 +00004037 }
Mike Stump1eb44332009-09-09 15:08:12 +00004038
John McCall94c3b562010-08-18 09:41:07 +00004039 // Visit pointee types from a permissive context.
4040#define CheckPolymorphic(Type) \
4041 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4042 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4043 }
4044 CheckPolymorphic(PointerTypeLoc)
4045 CheckPolymorphic(ReferenceTypeLoc)
4046 CheckPolymorphic(MemberPointerTypeLoc)
4047 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00004048 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00004049
John McCall94c3b562010-08-18 09:41:07 +00004050 /// Handle all the types we haven't given a more specific
4051 /// implementation for above.
4052 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4053 // Every other kind of type that we haven't called out already
4054 // that has an inner type is either (1) sugar or (2) contains that
4055 // inner type in some way as a subobject.
4056 if (TypeLoc Next = TL.getNextTypeLoc())
4057 return Visit(Next, Sel);
4058
4059 // If there's no inner type and we're in a permissive context,
4060 // don't diagnose.
4061 if (Sel == Sema::AbstractNone) return;
4062
4063 // Check whether the type matches the abstract type.
4064 QualType T = TL.getType();
4065 if (T->isArrayType()) {
4066 Sel = Sema::AbstractArrayType;
4067 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00004068 }
John McCall94c3b562010-08-18 09:41:07 +00004069 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4070 if (CT != Info.AbstractType) return;
4071
4072 // It matched; do some magic.
4073 if (Sel == Sema::AbstractArrayType) {
4074 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4075 << T << TL.getSourceRange();
4076 } else {
4077 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4078 << Sel << T << TL.getSourceRange();
4079 }
4080 Info.DiagnoseAbstractType();
4081 }
4082};
4083
4084void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4085 Sema::AbstractDiagSelID Sel) {
4086 CheckAbstractUsage(*this, D).Visit(TL, Sel);
4087}
4088
4089}
4090
4091/// Check for invalid uses of an abstract type in a method declaration.
4092static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4093 CXXMethodDecl *MD) {
4094 // No need to do the check on definitions, which require that
4095 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00004096 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00004097 return;
4098
4099 // For safety's sake, just ignore it if we don't have type source
4100 // information. This should never happen for non-implicit methods,
4101 // but...
4102 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4103 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4104}
4105
4106/// Check for invalid uses of an abstract type within a class definition.
4107static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4108 CXXRecordDecl *RD) {
4109 for (CXXRecordDecl::decl_iterator
4110 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4111 Decl *D = *I;
4112 if (D->isImplicit()) continue;
4113
4114 // Methods and method templates.
4115 if (isa<CXXMethodDecl>(D)) {
4116 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4117 } else if (isa<FunctionTemplateDecl>(D)) {
4118 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4119 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4120
4121 // Fields and static variables.
4122 } else if (isa<FieldDecl>(D)) {
4123 FieldDecl *FD = cast<FieldDecl>(D);
4124 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4125 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4126 } else if (isa<VarDecl>(D)) {
4127 VarDecl *VD = cast<VarDecl>(D);
4128 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4129 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4130
4131 // Nested classes and class templates.
4132 } else if (isa<CXXRecordDecl>(D)) {
4133 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4134 } else if (isa<ClassTemplateDecl>(D)) {
4135 CheckAbstractClassUsage(Info,
4136 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4137 }
4138 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00004139}
4140
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004141/// \brief Perform semantic checks on a class definition that has been
4142/// completing, introducing implicitly-declared members, checking for
4143/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004144void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00004145 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004146 return;
4147
John McCall94c3b562010-08-18 09:41:07 +00004148 if (Record->isAbstract() && !Record->isInvalidDecl()) {
4149 AbstractUsageInfo Info(*this, Record);
4150 CheckAbstractClassUsage(Info, Record);
4151 }
Douglas Gregor325e5932010-04-15 00:00:53 +00004152
4153 // If this is not an aggregate type and has no user-declared constructor,
4154 // complain about any non-static data members of reference or const scalar
4155 // type, since they will never get initializers.
4156 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00004157 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4158 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004159 bool Complained = false;
4160 for (RecordDecl::field_iterator F = Record->field_begin(),
4161 FEnd = Record->field_end();
4162 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00004163 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004164 continue;
4165
Douglas Gregor325e5932010-04-15 00:00:53 +00004166 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00004167 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00004168 if (!Complained) {
4169 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4170 << Record->getTagKind() << Record;
4171 Complained = true;
4172 }
4173
4174 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4175 << F->getType()->isReferenceType()
4176 << F->getDeclName();
4177 }
4178 }
4179 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004180
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00004181 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004182 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00004183
4184 if (Record->getIdentifier()) {
4185 // C++ [class.mem]p13:
4186 // If T is the name of a class, then each of the following shall have a
4187 // name different from T:
4188 // - every member of every anonymous union that is a member of class T.
4189 //
4190 // C++ [class.mem]p14:
4191 // In addition, if class T has a user-declared constructor (12.1), every
4192 // non-static data member of class T shall have a name different from T.
David Blaikie3bc93e32012-12-19 00:45:41 +00004193 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4194 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4195 ++I) {
4196 NamedDecl *D = *I;
Francois Pichet87c2e122010-11-21 06:08:52 +00004197 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4198 isa<IndirectFieldDecl>(D)) {
4199 Diag(D->getLocation(), diag::err_member_name_of_class)
4200 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00004201 break;
4202 }
Francois Pichet87c2e122010-11-21 06:08:52 +00004203 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00004204 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004205
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004206 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00004207 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004208 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00004209 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00004210 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4211 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4212 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004213
David Blaikieb6b5b972012-09-21 03:21:07 +00004214 if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4215 Diag(Record->getLocation(), diag::warn_abstract_final_class);
4216 DiagnoseAbstractType(Record);
4217 }
4218
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004219 if (!Record->isDependentType()) {
4220 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4221 MEnd = Record->method_end();
4222 M != MEnd; ++M) {
Richard Smith1d28caf2012-12-11 01:14:52 +00004223 // See if a method overloads virtual methods in a base
4224 // class without overriding any.
David Blaikie262bc182012-04-30 02:36:29 +00004225 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00004226 DiagnoseHiddenVirtualMethods(Record, *M);
Richard Smith1d28caf2012-12-11 01:14:52 +00004227
4228 // Check whether the explicitly-defaulted special members are valid.
4229 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4230 CheckExplicitlyDefaultedSpecialMember(*M);
4231
4232 // For an explicitly defaulted or deleted special member, we defer
4233 // determining triviality until the class is complete. That time is now!
4234 if (!M->isImplicit() && !M->isUserProvided()) {
4235 CXXSpecialMember CSM = getSpecialMember(*M);
4236 if (CSM != CXXInvalid) {
4237 M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4238
4239 // Inform the class that we've finished declaring this member.
4240 Record->finishedDefaultedOrDeletedMember(*M);
4241 }
4242 }
4243 }
4244 }
4245
4246 // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4247 // function that is not a constructor declares that member function to be
4248 // const. [...] The class of which that function is a member shall be
4249 // a literal type.
4250 //
4251 // If the class has virtual bases, any constexpr members will already have
4252 // been diagnosed by the checks performed on the member declaration, so
4253 // suppress this (less useful) diagnostic.
4254 //
4255 // We delay this until we know whether an explicitly-defaulted (or deleted)
4256 // destructor for the class is trivial.
Richard Smith80ad52f2013-01-02 11:42:31 +00004257 if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
Richard Smith1d28caf2012-12-11 01:14:52 +00004258 !Record->isLiteral() && !Record->getNumVBases()) {
4259 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4260 MEnd = Record->method_end();
4261 M != MEnd; ++M) {
4262 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4263 switch (Record->getTemplateSpecializationKind()) {
4264 case TSK_ImplicitInstantiation:
4265 case TSK_ExplicitInstantiationDeclaration:
4266 case TSK_ExplicitInstantiationDefinition:
4267 // If a template instantiates to a non-literal type, but its members
4268 // instantiate to constexpr functions, the template is technically
4269 // ill-formed, but we allow it for sanity.
4270 continue;
4271
4272 case TSK_Undeclared:
4273 case TSK_ExplicitSpecialization:
4274 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4275 diag::err_constexpr_method_non_literal);
4276 break;
4277 }
4278
4279 // Only produce one error per class.
4280 break;
4281 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004282 }
4283 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00004284
Richard Smith07b0fdc2013-03-18 21:12:30 +00004285 // Declare inheriting constructors. We do this eagerly here because:
4286 // - The standard requires an eager diagnostic for conflicting inheriting
Sebastian Redlf677ea32011-02-05 19:23:19 +00004287 // constructors from different classes.
4288 // - The lazy declaration of the other implicit constructors is so as to not
4289 // waste space and performance on classes that are not meant to be
4290 // instantiated (e.g. meta-functions). This doesn't apply to classes that
Richard Smith07b0fdc2013-03-18 21:12:30 +00004291 // have inheriting constructors.
4292 DeclareInheritingConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00004293}
4294
Richard Smith7756afa2012-06-10 05:43:50 +00004295/// Is the special member function which would be selected to perform the
4296/// specified operation on the specified class type a constexpr constructor?
4297static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4298 Sema::CXXSpecialMember CSM,
4299 bool ConstArg) {
4300 Sema::SpecialMemberOverloadResult *SMOR =
4301 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4302 false, false, false, false);
4303 if (!SMOR || !SMOR->getMethod())
4304 // A constructor we wouldn't select can't be "involved in initializing"
4305 // anything.
4306 return true;
4307 return SMOR->getMethod()->isConstexpr();
4308}
4309
4310/// Determine whether the specified special member function would be constexpr
4311/// if it were implicitly defined.
4312static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4313 Sema::CXXSpecialMember CSM,
4314 bool ConstArg) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004315 if (!S.getLangOpts().CPlusPlus11)
Richard Smith7756afa2012-06-10 05:43:50 +00004316 return false;
4317
4318 // C++11 [dcl.constexpr]p4:
4319 // In the definition of a constexpr constructor [...]
Richard Smitha8942d72013-05-07 03:19:20 +00004320 bool Ctor = true;
Richard Smith7756afa2012-06-10 05:43:50 +00004321 switch (CSM) {
4322 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004323 // Since default constructor lookup is essentially trivial (and cannot
4324 // involve, for instance, template instantiation), we compute whether a
4325 // defaulted default constructor is constexpr directly within CXXRecordDecl.
4326 //
4327 // This is important for performance; we need to know whether the default
4328 // constructor is constexpr to determine whether the type is a literal type.
4329 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4330
Richard Smith7756afa2012-06-10 05:43:50 +00004331 case Sema::CXXCopyConstructor:
4332 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00004333 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00004334 break;
4335
4336 case Sema::CXXCopyAssignment:
4337 case Sema::CXXMoveAssignment:
Richard Smitha8942d72013-05-07 03:19:20 +00004338 if (!S.getLangOpts().CPlusPlus1y)
4339 return false;
4340 // In C++1y, we need to perform overload resolution.
4341 Ctor = false;
4342 break;
4343
Richard Smith7756afa2012-06-10 05:43:50 +00004344 case Sema::CXXDestructor:
4345 case Sema::CXXInvalid:
4346 return false;
4347 }
4348
4349 // -- if the class is a non-empty union, or for each non-empty anonymous
4350 // union member of a non-union class, exactly one non-static data member
4351 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00004352 //
4353 // If we squint, this is guaranteed, since exactly one non-static data member
4354 // will be initialized (if the constructor isn't deleted), we just don't know
4355 // which one.
Richard Smitha8942d72013-05-07 03:19:20 +00004356 if (Ctor && ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00004357 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00004358
4359 // -- the class shall not have any virtual base classes;
Richard Smitha8942d72013-05-07 03:19:20 +00004360 if (Ctor && ClassDecl->getNumVBases())
4361 return false;
4362
4363 // C++1y [class.copy]p26:
4364 // -- [the class] is a literal type, and
4365 if (!Ctor && !ClassDecl->isLiteral())
Richard Smith7756afa2012-06-10 05:43:50 +00004366 return false;
4367
4368 // -- every constructor involved in initializing [...] base class
4369 // sub-objects shall be a constexpr constructor;
Richard Smitha8942d72013-05-07 03:19:20 +00004370 // -- the assignment operator selected to copy/move each direct base
4371 // class is a constexpr function, and
Richard Smith7756afa2012-06-10 05:43:50 +00004372 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4373 BEnd = ClassDecl->bases_end();
4374 B != BEnd; ++B) {
4375 const RecordType *BaseType = B->getType()->getAs<RecordType>();
4376 if (!BaseType) continue;
4377
4378 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4379 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4380 return false;
4381 }
4382
4383 // -- every constructor involved in initializing non-static data members
4384 // [...] shall be a constexpr constructor;
4385 // -- every non-static data member and base class sub-object shall be
4386 // initialized
Richard Smitha8942d72013-05-07 03:19:20 +00004387 // -- for each non-stastic data member of X that is of class type (or array
4388 // thereof), the assignment operator selected to copy/move that member is
4389 // a constexpr function
Richard Smith7756afa2012-06-10 05:43:50 +00004390 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4391 FEnd = ClassDecl->field_end();
4392 F != FEnd; ++F) {
4393 if (F->isInvalidDecl())
4394 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00004395 if (const RecordType *RecordTy =
4396 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00004397 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4398 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4399 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00004400 }
4401 }
4402
4403 // All OK, it's constexpr!
4404 return true;
4405}
4406
Richard Smithb9d0b762012-07-27 04:22:15 +00004407static Sema::ImplicitExceptionSpecification
4408computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4409 switch (S.getSpecialMember(MD)) {
4410 case Sema::CXXDefaultConstructor:
4411 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4412 case Sema::CXXCopyConstructor:
4413 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4414 case Sema::CXXCopyAssignment:
4415 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4416 case Sema::CXXMoveConstructor:
4417 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4418 case Sema::CXXMoveAssignment:
4419 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4420 case Sema::CXXDestructor:
4421 return S.ComputeDefaultedDtorExceptionSpec(MD);
4422 case Sema::CXXInvalid:
4423 break;
4424 }
Richard Smith07b0fdc2013-03-18 21:12:30 +00004425 assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4426 "only special members have implicit exception specs");
4427 return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
Richard Smithb9d0b762012-07-27 04:22:15 +00004428}
4429
Richard Smithdd25e802012-07-30 23:48:14 +00004430static void
4431updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4432 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4433 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4434 ExceptSpec.getEPI(EPI);
Richard Smith4841ca52013-04-10 05:48:59 +00004435 FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4436 FPT->getArgTypes(), EPI));
Richard Smithdd25e802012-07-30 23:48:14 +00004437}
4438
Richard Smithb9d0b762012-07-27 04:22:15 +00004439void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4440 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4441 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4442 return;
4443
Richard Smithdd25e802012-07-30 23:48:14 +00004444 // Evaluate the exception specification.
4445 ImplicitExceptionSpecification ExceptSpec =
4446 computeImplicitExceptionSpec(*this, Loc, MD);
4447
4448 // Update the type of the special member to use it.
4449 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4450
4451 // A user-provided destructor can be defined outside the class. When that
4452 // happens, be sure to update the exception specification on both
4453 // declarations.
4454 const FunctionProtoType *CanonicalFPT =
4455 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4456 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4457 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4458 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004459}
4460
Richard Smith3003e1d2012-05-15 04:39:51 +00004461void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4462 CXXRecordDecl *RD = MD->getParent();
4463 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004464
Richard Smith3003e1d2012-05-15 04:39:51 +00004465 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4466 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004467
4468 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004469 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004470 bool First = MD == MD->getCanonicalDecl();
4471
4472 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004473
4474 // C++11 [dcl.fct.def.default]p1:
4475 // A function that is explicitly defaulted shall
4476 // -- be a special member function (checked elsewhere),
4477 // -- have the same type (except for ref-qualifiers, and except that a
4478 // copy operation can take a non-const reference) as an implicit
4479 // declaration, and
4480 // -- not have default arguments.
4481 unsigned ExpectedParams = 1;
4482 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4483 ExpectedParams = 0;
4484 if (MD->getNumParams() != ExpectedParams) {
4485 // This also checks for default arguments: a copy or move constructor with a
4486 // default argument is classified as a default constructor, and assignment
4487 // operations and destructors can't have default arguments.
4488 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4489 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004490 HadError = true;
Richard Smith50464392012-12-07 02:10:28 +00004491 } else if (MD->isVariadic()) {
4492 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4493 << CSM << MD->getSourceRange();
4494 HadError = true;
Sean Hunt2b188082011-05-14 05:23:28 +00004495 }
4496
Richard Smith3003e1d2012-05-15 04:39:51 +00004497 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004498
Richard Smith7756afa2012-06-10 05:43:50 +00004499 bool CanHaveConstParam = false;
Richard Smithac713512012-12-08 02:53:02 +00004500 if (CSM == CXXCopyConstructor)
Richard Smithacf796b2012-11-28 06:23:12 +00004501 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
Richard Smithac713512012-12-08 02:53:02 +00004502 else if (CSM == CXXCopyAssignment)
Richard Smithacf796b2012-11-28 06:23:12 +00004503 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
Sean Hunt2b188082011-05-14 05:23:28 +00004504
Richard Smith3003e1d2012-05-15 04:39:51 +00004505 QualType ReturnType = Context.VoidTy;
4506 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4507 // Check for return type matching.
4508 ReturnType = Type->getResultType();
4509 QualType ExpectedReturnType =
4510 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4511 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4512 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4513 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4514 HadError = true;
4515 }
4516
4517 // A defaulted special member cannot have cv-qualifiers.
4518 if (Type->getTypeQuals()) {
4519 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
Richard Smitha8942d72013-05-07 03:19:20 +00004520 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
Richard Smith3003e1d2012-05-15 04:39:51 +00004521 HadError = true;
4522 }
4523 }
4524
4525 // Check for parameter type matching.
4526 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004527 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004528 if (ExpectedParams && ArgType->isReferenceType()) {
4529 // Argument must be reference to possibly-const T.
4530 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004531 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004532
4533 if (ReferentType.isVolatileQualified()) {
4534 Diag(MD->getLocation(),
4535 diag::err_defaulted_special_member_volatile_param) << CSM;
4536 HadError = true;
4537 }
4538
Richard Smith7756afa2012-06-10 05:43:50 +00004539 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004540 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4541 Diag(MD->getLocation(),
4542 diag::err_defaulted_special_member_copy_const_param)
4543 << (CSM == CXXCopyAssignment);
4544 // FIXME: Explain why this special member can't be const.
4545 } else {
4546 Diag(MD->getLocation(),
4547 diag::err_defaulted_special_member_move_const_param)
4548 << (CSM == CXXMoveAssignment);
4549 }
4550 HadError = true;
4551 }
Richard Smith3003e1d2012-05-15 04:39:51 +00004552 } else if (ExpectedParams) {
4553 // A copy assignment operator can take its argument by value, but a
4554 // defaulted one cannot.
4555 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004556 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004557 HadError = true;
4558 }
Sean Huntbe631222011-05-17 20:44:43 +00004559
Richard Smith61802452011-12-22 02:22:31 +00004560 // C++11 [dcl.fct.def.default]p2:
4561 // An explicitly-defaulted function may be declared constexpr only if it
4562 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004563 // Do not apply this rule to members of class templates, since core issue 1358
4564 // makes such functions always instantiate to constexpr functions. For
Richard Smitha8942d72013-05-07 03:19:20 +00004565 // functions which cannot be constexpr (for non-constructors in C++11 and for
4566 // destructors in C++1y), this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004567 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4568 HasConstParam);
Richard Smitha8942d72013-05-07 03:19:20 +00004569 if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4570 : isa<CXXConstructorDecl>(MD)) &&
4571 MD->isConstexpr() && !Constexpr &&
Richard Smith3003e1d2012-05-15 04:39:51 +00004572 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4573 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smitha8942d72013-05-07 03:19:20 +00004574 // FIXME: Explain why the special member can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004575 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004576 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004577
Richard Smith61802452011-12-22 02:22:31 +00004578 // and may have an explicit exception-specification only if it is compatible
4579 // with the exception-specification on the implicit declaration.
Richard Smith1d28caf2012-12-11 01:14:52 +00004580 if (Type->hasExceptionSpec()) {
4581 // Delay the check if this is the first declaration of the special member,
4582 // since we may not have parsed some necessary in-class initializers yet.
Richard Smith12fef492013-03-27 00:22:47 +00004583 if (First) {
4584 // If the exception specification needs to be instantiated, do so now,
4585 // before we clobber it with an EST_Unevaluated specification below.
4586 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4587 InstantiateExceptionSpec(MD->getLocStart(), MD);
4588 Type = MD->getType()->getAs<FunctionProtoType>();
4589 }
Richard Smith1d28caf2012-12-11 01:14:52 +00004590 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
Richard Smith12fef492013-03-27 00:22:47 +00004591 } else
Richard Smith1d28caf2012-12-11 01:14:52 +00004592 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4593 }
Richard Smith61802452011-12-22 02:22:31 +00004594
4595 // If a function is explicitly defaulted on its first declaration,
4596 if (First) {
4597 // -- it is implicitly considered to be constexpr if the implicit
4598 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004599 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004600
Richard Smith3003e1d2012-05-15 04:39:51 +00004601 // -- it is implicitly considered to have the same exception-specification
4602 // as if it had been implicitly declared,
Richard Smith1d28caf2012-12-11 01:14:52 +00004603 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4604 EPI.ExceptionSpecType = EST_Unevaluated;
4605 EPI.ExceptionSpecDecl = MD;
Jordan Rosebea522f2013-03-08 21:51:21 +00004606 MD->setType(Context.getFunctionType(ReturnType,
4607 ArrayRef<QualType>(&ArgType,
4608 ExpectedParams),
4609 EPI));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004610 }
4611
Richard Smith3003e1d2012-05-15 04:39:51 +00004612 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004613 if (First) {
Richard Smith0ab5b4c2013-04-02 19:38:47 +00004614 SetDeclDeleted(MD, MD->getLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004615 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004616 // C++11 [dcl.fct.def.default]p4:
4617 // [For a] user-provided explicitly-defaulted function [...] if such a
4618 // function is implicitly defined as deleted, the program is ill-formed.
4619 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4620 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004621 }
4622 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004623
Richard Smith3003e1d2012-05-15 04:39:51 +00004624 if (HadError)
4625 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004626}
4627
Richard Smith1d28caf2012-12-11 01:14:52 +00004628/// Check whether the exception specification provided for an
4629/// explicitly-defaulted special member matches the exception specification
4630/// that would have been generated for an implicit special member, per
4631/// C++11 [dcl.fct.def.default]p2.
4632void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4633 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4634 // Compute the implicit exception specification.
4635 FunctionProtoType::ExtProtoInfo EPI;
4636 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4637 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
Dmitri Gribenko55431692013-05-05 00:41:58 +00004638 Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smith1d28caf2012-12-11 01:14:52 +00004639
4640 // Ensure that it matches.
4641 CheckEquivalentExceptionSpec(
4642 PDiag(diag::err_incorrect_defaulted_exception_spec)
4643 << getSpecialMember(MD), PDiag(),
4644 ImplicitType, SourceLocation(),
4645 SpecifiedType, MD->getLocation());
4646}
4647
4648void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4649 for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4650 I != N; ++I)
4651 CheckExplicitlyDefaultedMemberExceptionSpec(
4652 DelayedDefaultedMemberExceptionSpecs[I].first,
4653 DelayedDefaultedMemberExceptionSpecs[I].second);
4654
4655 DelayedDefaultedMemberExceptionSpecs.clear();
4656}
4657
Richard Smith7d5088a2012-02-18 02:02:13 +00004658namespace {
4659struct SpecialMemberDeletionInfo {
4660 Sema &S;
4661 CXXMethodDecl *MD;
4662 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004663 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004664
4665 // Properties of the special member, computed for convenience.
4666 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4667 SourceLocation Loc;
4668
4669 bool AllFieldsAreConst;
4670
4671 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004672 Sema::CXXSpecialMember CSM, bool Diagnose)
4673 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004674 IsConstructor(false), IsAssignment(false), IsMove(false),
4675 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4676 AllFieldsAreConst(true) {
4677 switch (CSM) {
4678 case Sema::CXXDefaultConstructor:
4679 case Sema::CXXCopyConstructor:
4680 IsConstructor = true;
4681 break;
4682 case Sema::CXXMoveConstructor:
4683 IsConstructor = true;
4684 IsMove = true;
4685 break;
4686 case Sema::CXXCopyAssignment:
4687 IsAssignment = true;
4688 break;
4689 case Sema::CXXMoveAssignment:
4690 IsAssignment = true;
4691 IsMove = true;
4692 break;
4693 case Sema::CXXDestructor:
4694 break;
4695 case Sema::CXXInvalid:
4696 llvm_unreachable("invalid special member kind");
4697 }
4698
4699 if (MD->getNumParams()) {
4700 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4701 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4702 }
4703 }
4704
4705 bool inUnion() const { return MD->getParent()->isUnion(); }
4706
4707 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004708 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4709 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004710 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004711 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4712 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4713 Quals = 0;
4714 return S.LookupSpecialMember(Class, CSM,
4715 ConstArg || (Quals & Qualifiers::Const),
4716 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004717 MD->getRefQualifier() == RQ_RValue,
4718 TQ & Qualifiers::Const,
4719 TQ & Qualifiers::Volatile);
4720 }
4721
Richard Smith6c4c36c2012-03-30 20:53:28 +00004722 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004723
Richard Smith6c4c36c2012-03-30 20:53:28 +00004724 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004725 bool shouldDeleteForField(FieldDecl *FD);
4726 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004727
Richard Smith517bb842012-07-18 03:51:16 +00004728 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4729 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004730 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4731 Sema::SpecialMemberOverloadResult *SMOR,
4732 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004733
4734 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004735};
4736}
4737
John McCall12d8d802012-04-09 20:53:23 +00004738/// Is the given special member inaccessible when used on the given
4739/// sub-object.
4740bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4741 CXXMethodDecl *target) {
4742 /// If we're operating on a base class, the object type is the
4743 /// type of this special member.
4744 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004745 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004746 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4747 objectTy = S.Context.getTypeDeclType(MD->getParent());
4748 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4749
4750 // If we're operating on a field, the object type is the type of the field.
4751 } else {
4752 objectTy = S.Context.getTypeDeclType(target->getParent());
4753 }
4754
4755 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4756}
4757
Richard Smith6c4c36c2012-03-30 20:53:28 +00004758/// Check whether we should delete a special member due to the implicit
4759/// definition containing a call to a special member of a subobject.
4760bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4761 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4762 bool IsDtorCallInCtor) {
4763 CXXMethodDecl *Decl = SMOR->getMethod();
4764 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4765
4766 int DiagKind = -1;
4767
4768 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4769 DiagKind = !Decl ? 0 : 1;
4770 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4771 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004772 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004773 DiagKind = 3;
4774 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4775 !Decl->isTrivial()) {
4776 // A member of a union must have a trivial corresponding special member.
4777 // As a weird special case, a destructor call from a union's constructor
4778 // must be accessible and non-deleted, but need not be trivial. Such a
4779 // destructor is never actually called, but is semantically checked as
4780 // if it were.
4781 DiagKind = 4;
4782 }
4783
4784 if (DiagKind == -1)
4785 return false;
4786
4787 if (Diagnose) {
4788 if (Field) {
4789 S.Diag(Field->getLocation(),
4790 diag::note_deleted_special_member_class_subobject)
4791 << CSM << MD->getParent() << /*IsField*/true
4792 << Field << DiagKind << IsDtorCallInCtor;
4793 } else {
4794 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4795 S.Diag(Base->getLocStart(),
4796 diag::note_deleted_special_member_class_subobject)
4797 << CSM << MD->getParent() << /*IsField*/false
4798 << Base->getType() << DiagKind << IsDtorCallInCtor;
4799 }
4800
4801 if (DiagKind == 1)
4802 S.NoteDeletedFunction(Decl);
4803 // FIXME: Explain inaccessibility if DiagKind == 3.
4804 }
4805
4806 return true;
4807}
4808
Richard Smith9a561d52012-02-26 09:11:52 +00004809/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004810/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004811bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004812 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004813 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004814
4815 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004816 // -- any direct or virtual base class, or non-static data member with no
4817 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004818 // either M has no default constructor or overload resolution as applied
4819 // to M's default constructor results in an ambiguity or in a function
4820 // that is deleted or inaccessible
4821 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4822 // -- a direct or virtual base class B that cannot be copied/moved because
4823 // overload resolution, as applied to B's corresponding special member,
4824 // results in an ambiguity or a function that is deleted or inaccessible
4825 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004826 // C++11 [class.dtor]p5:
4827 // -- any direct or virtual base class [...] has a type with a destructor
4828 // that is deleted or inaccessible
4829 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004830 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004831 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004832 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004833
Richard Smith6c4c36c2012-03-30 20:53:28 +00004834 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4835 // -- any direct or virtual base class or non-static data member has a
4836 // type with a destructor that is deleted or inaccessible
4837 if (IsConstructor) {
4838 Sema::SpecialMemberOverloadResult *SMOR =
4839 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4840 false, false, false, false, false);
4841 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4842 return true;
4843 }
4844
Richard Smith9a561d52012-02-26 09:11:52 +00004845 return false;
4846}
4847
4848/// Check whether we should delete a special member function due to the class
4849/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004850bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004851 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004852 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004853}
4854
4855/// Check whether we should delete a special member function due to the class
4856/// having a particular non-static data member.
4857bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4858 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4859 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4860
4861 if (CSM == Sema::CXXDefaultConstructor) {
4862 // For a default constructor, all references must be initialized in-class
4863 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004864 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4865 if (Diagnose)
4866 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4867 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004868 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004869 }
Richard Smith79363f52012-02-27 06:07:25 +00004870 // C++11 [class.ctor]p5: any non-variant non-static data member of
4871 // const-qualified type (or array thereof) with no
4872 // brace-or-equal-initializer does not have a user-provided default
4873 // constructor.
4874 if (!inUnion() && FieldType.isConstQualified() &&
4875 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004876 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4877 if (Diagnose)
4878 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004879 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004880 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004881 }
4882
4883 if (inUnion() && !FieldType.isConstQualified())
4884 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004885 } else if (CSM == Sema::CXXCopyConstructor) {
4886 // For a copy constructor, data members must not be of rvalue reference
4887 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004888 if (FieldType->isRValueReferenceType()) {
4889 if (Diagnose)
4890 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4891 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004892 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004893 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004894 } else if (IsAssignment) {
4895 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004896 if (FieldType->isReferenceType()) {
4897 if (Diagnose)
4898 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4899 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004900 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004901 }
4902 if (!FieldRecord && FieldType.isConstQualified()) {
4903 // C++11 [class.copy]p23:
4904 // -- a non-static data member of const non-class type (or array thereof)
4905 if (Diagnose)
4906 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004907 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004908 return true;
4909 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004910 }
4911
4912 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004913 // Some additional restrictions exist on the variant members.
4914 if (!inUnion() && FieldRecord->isUnion() &&
4915 FieldRecord->isAnonymousStructOrUnion()) {
4916 bool AllVariantFieldsAreConst = true;
4917
Richard Smithdf8dc862012-03-29 19:00:10 +00004918 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004919 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4920 UE = FieldRecord->field_end();
4921 UI != UE; ++UI) {
4922 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004923
4924 if (!UnionFieldType.isConstQualified())
4925 AllVariantFieldsAreConst = false;
4926
Richard Smith9a561d52012-02-26 09:11:52 +00004927 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4928 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004929 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4930 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004931 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004932 }
4933
4934 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004935 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004936 FieldRecord->field_begin() != FieldRecord->field_end()) {
4937 if (Diagnose)
4938 S.Diag(FieldRecord->getLocation(),
4939 diag::note_deleted_default_ctor_all_const)
4940 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004941 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004942 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004943
Richard Smithdf8dc862012-03-29 19:00:10 +00004944 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004945 // This is technically non-conformant, but sanity demands it.
4946 return false;
4947 }
4948
Richard Smith517bb842012-07-18 03:51:16 +00004949 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4950 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004951 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004952 }
4953
4954 return false;
4955}
4956
4957/// C++11 [class.ctor] p5:
4958/// A defaulted default constructor for a class X is defined as deleted if
4959/// X is a union and all of its variant members are of const-qualified type.
4960bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004961 // This is a silly definition, because it gives an empty union a deleted
4962 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004963 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4964 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4965 if (Diagnose)
4966 S.Diag(MD->getParent()->getLocation(),
4967 diag::note_deleted_default_ctor_all_const)
4968 << MD->getParent() << /*not anonymous union*/0;
4969 return true;
4970 }
4971 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004972}
4973
4974/// Determine whether a defaulted special member function should be defined as
4975/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4976/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004977bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4978 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004979 if (MD->isInvalidDecl())
4980 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004981 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004982 assert(!RD->isDependentType() && "do deletion after instantiation");
Richard Smith80ad52f2013-01-02 11:42:31 +00004983 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004984 return false;
4985
Richard Smith7d5088a2012-02-18 02:02:13 +00004986 // C++11 [expr.lambda.prim]p19:
4987 // The closure type associated with a lambda-expression has a
4988 // deleted (8.4.3) default constructor and a deleted copy
4989 // assignment operator.
4990 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004991 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4992 if (Diagnose)
4993 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004994 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004995 }
4996
Richard Smith5bdaac52012-04-02 20:59:25 +00004997 // For an anonymous struct or union, the copy and assignment special members
4998 // will never be used, so skip the check. For an anonymous union declared at
4999 // namespace scope, the constructor and destructor are used.
5000 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5001 RD->isAnonymousStructOrUnion())
5002 return false;
5003
Richard Smith6c4c36c2012-03-30 20:53:28 +00005004 // C++11 [class.copy]p7, p18:
5005 // If the class definition declares a move constructor or move assignment
5006 // operator, an implicitly declared copy constructor or copy assignment
5007 // operator is defined as deleted.
5008 if (MD->isImplicit() &&
5009 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5010 CXXMethodDecl *UserDeclaredMove = 0;
5011
5012 // In Microsoft mode, a user-declared move only causes the deletion of the
5013 // corresponding copy operation, not both copy operations.
5014 if (RD->hasUserDeclaredMoveConstructor() &&
5015 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5016 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005017
5018 // Find any user-declared move constructor.
5019 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5020 E = RD->ctor_end(); I != E; ++I) {
5021 if (I->isMoveConstructor()) {
5022 UserDeclaredMove = *I;
5023 break;
5024 }
5025 }
Richard Smith1c931be2012-04-02 18:40:40 +00005026 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005027 } else if (RD->hasUserDeclaredMoveAssignment() &&
5028 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5029 if (!Diagnose) return true;
Richard Smith55798652012-12-08 04:10:18 +00005030
5031 // Find any user-declared move assignment operator.
5032 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5033 E = RD->method_end(); I != E; ++I) {
5034 if (I->isMoveAssignmentOperator()) {
5035 UserDeclaredMove = *I;
5036 break;
5037 }
5038 }
Richard Smith1c931be2012-04-02 18:40:40 +00005039 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00005040 }
5041
5042 if (UserDeclaredMove) {
5043 Diag(UserDeclaredMove->getLocation(),
5044 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00005045 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00005046 << UserDeclaredMove->isMoveAssignmentOperator();
5047 return true;
5048 }
5049 }
Sean Hunte16da072011-10-10 06:18:57 +00005050
Richard Smith5bdaac52012-04-02 20:59:25 +00005051 // Do access control from the special member function
5052 ContextRAII MethodContext(*this, MD);
5053
Richard Smith9a561d52012-02-26 09:11:52 +00005054 // C++11 [class.dtor]p5:
5055 // -- for a virtual destructor, lookup of the non-array deallocation function
5056 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00005057 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00005058 FunctionDecl *OperatorDelete = 0;
5059 DeclarationName Name =
5060 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5061 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00005062 OperatorDelete, false)) {
5063 if (Diagnose)
5064 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00005065 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00005066 }
Richard Smith9a561d52012-02-26 09:11:52 +00005067 }
5068
Richard Smith6c4c36c2012-03-30 20:53:28 +00005069 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00005070
Sean Huntcdee3fe2011-05-11 22:34:38 +00005071 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005072 BE = RD->bases_end(); BI != BE; ++BI)
5073 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00005074 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00005075 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005076
Richard Smithe0883602013-07-22 18:06:23 +00005077 // Per DR1611, do not consider virtual bases of constructors of abstract
5078 // classes, since we are not going to construct them.
Richard Smithcbc820a2013-07-22 02:56:56 +00005079 if (!RD->isAbstract() || !SMI.IsConstructor) {
5080 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5081 BE = RD->vbases_end();
5082 BI != BE; ++BI)
5083 if (SMI.shouldDeleteForBase(BI))
5084 return true;
5085 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00005086
5087 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00005088 FE = RD->field_end(); FI != FE; ++FI)
5089 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00005090 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00005091 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00005092
Richard Smith7d5088a2012-02-18 02:02:13 +00005093 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00005094 return true;
5095
5096 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005097}
5098
Richard Smithac713512012-12-08 02:53:02 +00005099/// Perform lookup for a special member of the specified kind, and determine
5100/// whether it is trivial. If the triviality can be determined without the
5101/// lookup, skip it. This is intended for use when determining whether a
5102/// special member of a containing object is trivial, and thus does not ever
5103/// perform overload resolution for default constructors.
5104///
5105/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5106/// member that was most likely to be intended to be trivial, if any.
5107static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5108 Sema::CXXSpecialMember CSM, unsigned Quals,
5109 CXXMethodDecl **Selected) {
5110 if (Selected)
5111 *Selected = 0;
5112
5113 switch (CSM) {
5114 case Sema::CXXInvalid:
5115 llvm_unreachable("not a special member");
5116
5117 case Sema::CXXDefaultConstructor:
5118 // C++11 [class.ctor]p5:
5119 // A default constructor is trivial if:
5120 // - all the [direct subobjects] have trivial default constructors
5121 //
5122 // Note, no overload resolution is performed in this case.
5123 if (RD->hasTrivialDefaultConstructor())
5124 return true;
5125
5126 if (Selected) {
5127 // If there's a default constructor which could have been trivial, dig it
5128 // out. Otherwise, if there's any user-provided default constructor, point
5129 // to that as an example of why there's not a trivial one.
5130 CXXConstructorDecl *DefCtor = 0;
5131 if (RD->needsImplicitDefaultConstructor())
5132 S.DeclareImplicitDefaultConstructor(RD);
5133 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5134 CE = RD->ctor_end(); CI != CE; ++CI) {
5135 if (!CI->isDefaultConstructor())
5136 continue;
5137 DefCtor = *CI;
5138 if (!DefCtor->isUserProvided())
5139 break;
5140 }
5141
5142 *Selected = DefCtor;
5143 }
5144
5145 return false;
5146
5147 case Sema::CXXDestructor:
5148 // C++11 [class.dtor]p5:
5149 // A destructor is trivial if:
5150 // - all the direct [subobjects] have trivial destructors
5151 if (RD->hasTrivialDestructor())
5152 return true;
5153
5154 if (Selected) {
5155 if (RD->needsImplicitDestructor())
5156 S.DeclareImplicitDestructor(RD);
5157 *Selected = RD->getDestructor();
5158 }
5159
5160 return false;
5161
5162 case Sema::CXXCopyConstructor:
5163 // C++11 [class.copy]p12:
5164 // A copy constructor is trivial if:
5165 // - the constructor selected to copy each direct [subobject] is trivial
5166 if (RD->hasTrivialCopyConstructor()) {
5167 if (Quals == Qualifiers::Const)
5168 // We must either select the trivial copy constructor or reach an
5169 // ambiguity; no need to actually perform overload resolution.
5170 return true;
5171 } else if (!Selected) {
5172 return false;
5173 }
5174 // In C++98, we are not supposed to perform overload resolution here, but we
5175 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5176 // cases like B as having a non-trivial copy constructor:
5177 // struct A { template<typename T> A(T&); };
5178 // struct B { mutable A a; };
5179 goto NeedOverloadResolution;
5180
5181 case Sema::CXXCopyAssignment:
5182 // C++11 [class.copy]p25:
5183 // A copy assignment operator is trivial if:
5184 // - the assignment operator selected to copy each direct [subobject] is
5185 // trivial
5186 if (RD->hasTrivialCopyAssignment()) {
5187 if (Quals == Qualifiers::Const)
5188 return true;
5189 } else if (!Selected) {
5190 return false;
5191 }
5192 // In C++98, we are not supposed to perform overload resolution here, but we
5193 // treat that as a language defect.
5194 goto NeedOverloadResolution;
5195
5196 case Sema::CXXMoveConstructor:
5197 case Sema::CXXMoveAssignment:
5198 NeedOverloadResolution:
5199 Sema::SpecialMemberOverloadResult *SMOR =
5200 S.LookupSpecialMember(RD, CSM,
5201 Quals & Qualifiers::Const,
5202 Quals & Qualifiers::Volatile,
5203 /*RValueThis*/false, /*ConstThis*/false,
5204 /*VolatileThis*/false);
5205
5206 // The standard doesn't describe how to behave if the lookup is ambiguous.
5207 // We treat it as not making the member non-trivial, just like the standard
5208 // mandates for the default constructor. This should rarely matter, because
5209 // the member will also be deleted.
5210 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5211 return true;
5212
5213 if (!SMOR->getMethod()) {
5214 assert(SMOR->getKind() ==
5215 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5216 return false;
5217 }
5218
5219 // We deliberately don't check if we found a deleted special member. We're
5220 // not supposed to!
5221 if (Selected)
5222 *Selected = SMOR->getMethod();
5223 return SMOR->getMethod()->isTrivial();
5224 }
5225
5226 llvm_unreachable("unknown special method kind");
5227}
5228
Benjamin Kramera574c892013-02-15 12:30:38 +00005229static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
Richard Smithac713512012-12-08 02:53:02 +00005230 for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5231 CI != CE; ++CI)
5232 if (!CI->isImplicit())
5233 return *CI;
5234
5235 // Look for constructor templates.
5236 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5237 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5238 if (CXXConstructorDecl *CD =
5239 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5240 return CD;
5241 }
5242
5243 return 0;
5244}
5245
5246/// The kind of subobject we are checking for triviality. The values of this
5247/// enumeration are used in diagnostics.
5248enum TrivialSubobjectKind {
5249 /// The subobject is a base class.
5250 TSK_BaseClass,
5251 /// The subobject is a non-static data member.
5252 TSK_Field,
5253 /// The object is actually the complete object.
5254 TSK_CompleteObject
5255};
5256
5257/// Check whether the special member selected for a given type would be trivial.
5258static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5259 QualType SubType,
5260 Sema::CXXSpecialMember CSM,
5261 TrivialSubobjectKind Kind,
5262 bool Diagnose) {
5263 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5264 if (!SubRD)
5265 return true;
5266
5267 CXXMethodDecl *Selected;
5268 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5269 Diagnose ? &Selected : 0))
5270 return true;
5271
5272 if (Diagnose) {
5273 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5274 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5275 << Kind << SubType.getUnqualifiedType();
5276 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5277 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5278 } else if (!Selected)
5279 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5280 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5281 else if (Selected->isUserProvided()) {
5282 if (Kind == TSK_CompleteObject)
5283 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5284 << Kind << SubType.getUnqualifiedType() << CSM;
5285 else {
5286 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5287 << Kind << SubType.getUnqualifiedType() << CSM;
5288 S.Diag(Selected->getLocation(), diag::note_declared_at);
5289 }
5290 } else {
5291 if (Kind != TSK_CompleteObject)
5292 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5293 << Kind << SubType.getUnqualifiedType() << CSM;
5294
5295 // Explain why the defaulted or deleted special member isn't trivial.
5296 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5297 }
5298 }
5299
5300 return false;
5301}
5302
5303/// Check whether the members of a class type allow a special member to be
5304/// trivial.
5305static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5306 Sema::CXXSpecialMember CSM,
5307 bool ConstArg, bool Diagnose) {
5308 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5309 FE = RD->field_end(); FI != FE; ++FI) {
5310 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5311 continue;
5312
5313 QualType FieldType = S.Context.getBaseElementType(FI->getType());
5314
5315 // Pretend anonymous struct or union members are members of this class.
5316 if (FI->isAnonymousStructOrUnion()) {
5317 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5318 CSM, ConstArg, Diagnose))
5319 return false;
5320 continue;
5321 }
5322
5323 // C++11 [class.ctor]p5:
5324 // A default constructor is trivial if [...]
5325 // -- no non-static data member of its class has a
5326 // brace-or-equal-initializer
5327 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5328 if (Diagnose)
5329 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5330 return false;
5331 }
5332
5333 // Objective C ARC 4.3.5:
5334 // [...] nontrivally ownership-qualified types are [...] not trivially
5335 // default constructible, copy constructible, move constructible, copy
5336 // assignable, move assignable, or destructible [...]
5337 if (S.getLangOpts().ObjCAutoRefCount &&
5338 FieldType.hasNonTrivialObjCLifetime()) {
5339 if (Diagnose)
5340 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5341 << RD << FieldType.getObjCLifetime();
5342 return false;
5343 }
5344
5345 if (ConstArg && !FI->isMutable())
5346 FieldType.addConst();
5347 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5348 TSK_Field, Diagnose))
5349 return false;
5350 }
5351
5352 return true;
5353}
5354
5355/// Diagnose why the specified class does not have a trivial special member of
5356/// the given kind.
5357void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5358 QualType Ty = Context.getRecordType(RD);
5359 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5360 Ty.addConst();
5361
5362 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5363 TSK_CompleteObject, /*Diagnose*/true);
5364}
5365
5366/// Determine whether a defaulted or deleted special member function is trivial,
5367/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5368/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5369bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5370 bool Diagnose) {
Richard Smithac713512012-12-08 02:53:02 +00005371 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5372
5373 CXXRecordDecl *RD = MD->getParent();
5374
5375 bool ConstArg = false;
Richard Smithac713512012-12-08 02:53:02 +00005376
5377 // C++11 [class.copy]p12, p25:
5378 // A [special member] is trivial if its declared parameter type is the same
5379 // as if it had been implicitly declared [...]
5380 switch (CSM) {
5381 case CXXDefaultConstructor:
5382 case CXXDestructor:
5383 // Trivial default constructors and destructors cannot have parameters.
5384 break;
5385
5386 case CXXCopyConstructor:
5387 case CXXCopyAssignment: {
5388 // Trivial copy operations always have const, non-volatile parameter types.
5389 ConstArg = true;
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005390 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005391 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5392 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5393 if (Diagnose)
5394 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5395 << Param0->getSourceRange() << Param0->getType()
5396 << Context.getLValueReferenceType(
5397 Context.getRecordType(RD).withConst());
5398 return false;
5399 }
5400 break;
5401 }
5402
5403 case CXXMoveConstructor:
5404 case CXXMoveAssignment: {
5405 // Trivial move operations always have non-cv-qualified parameters.
Jordan Rose41f3f3a2013-03-05 01:27:54 +00005406 const ParmVarDecl *Param0 = MD->getParamDecl(0);
Richard Smithac713512012-12-08 02:53:02 +00005407 const RValueReferenceType *RT =
5408 Param0->getType()->getAs<RValueReferenceType>();
5409 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5410 if (Diagnose)
5411 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5412 << Param0->getSourceRange() << Param0->getType()
5413 << Context.getRValueReferenceType(Context.getRecordType(RD));
5414 return false;
5415 }
5416 break;
5417 }
5418
5419 case CXXInvalid:
5420 llvm_unreachable("not a special member");
5421 }
5422
5423 // FIXME: We require that the parameter-declaration-clause is equivalent to
5424 // that of an implicit declaration, not just that the declared parameter type
5425 // matches, in order to prevent absuridities like a function simultaneously
5426 // being a trivial copy constructor and a non-trivial default constructor.
5427 // This issue has not yet been assigned a core issue number.
5428 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5429 if (Diagnose)
5430 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5431 diag::note_nontrivial_default_arg)
5432 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5433 return false;
5434 }
5435 if (MD->isVariadic()) {
5436 if (Diagnose)
5437 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5438 return false;
5439 }
5440
5441 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5442 // A copy/move [constructor or assignment operator] is trivial if
5443 // -- the [member] selected to copy/move each direct base class subobject
5444 // is trivial
5445 //
5446 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5447 // A [default constructor or destructor] is trivial if
5448 // -- all the direct base classes have trivial [default constructors or
5449 // destructors]
5450 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5451 BE = RD->bases_end(); BI != BE; ++BI)
5452 if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5453 ConstArg ? BI->getType().withConst()
5454 : BI->getType(),
5455 CSM, TSK_BaseClass, Diagnose))
5456 return false;
5457
5458 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5459 // A copy/move [constructor or assignment operator] for a class X is
5460 // trivial if
5461 // -- for each non-static data member of X that is of class type (or array
5462 // thereof), the constructor selected to copy/move that member is
5463 // trivial
5464 //
5465 // C++11 [class.copy]p12, C++11 [class.copy]p25:
5466 // A [default constructor or destructor] is trivial if
5467 // -- for all of the non-static data members of its class that are of class
5468 // type (or array thereof), each such class has a trivial [default
5469 // constructor or destructor]
5470 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5471 return false;
5472
5473 // C++11 [class.dtor]p5:
5474 // A destructor is trivial if [...]
5475 // -- the destructor is not virtual
5476 if (CSM == CXXDestructor && MD->isVirtual()) {
5477 if (Diagnose)
5478 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5479 return false;
5480 }
5481
5482 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5483 // A [special member] for class X is trivial if [...]
5484 // -- class X has no virtual functions and no virtual base classes
5485 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5486 if (!Diagnose)
5487 return false;
5488
5489 if (RD->getNumVBases()) {
5490 // Check for virtual bases. We already know that the corresponding
5491 // member in all bases is trivial, so vbases must all be direct.
5492 CXXBaseSpecifier &BS = *RD->vbases_begin();
5493 assert(BS.isVirtual());
5494 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5495 return false;
5496 }
5497
5498 // Must have a virtual method.
5499 for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5500 ME = RD->method_end(); MI != ME; ++MI) {
5501 if (MI->isVirtual()) {
5502 SourceLocation MLoc = MI->getLocStart();
5503 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5504 return false;
5505 }
5506 }
5507
5508 llvm_unreachable("dynamic class with no vbases and no virtual functions");
5509 }
5510
5511 // Looks like it's trivial!
5512 return true;
5513}
5514
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005515/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005516namespace {
5517 struct FindHiddenVirtualMethodData {
5518 Sema *S;
5519 CXXMethodDecl *Method;
5520 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005521 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00005522 };
5523}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005524
David Blaikie5f750682012-10-19 00:53:08 +00005525/// \brief Check whether any most overriden method from MD in Methods
5526static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5527 const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5528 if (MD->size_overridden_methods() == 0)
5529 return Methods.count(MD->getCanonicalDecl());
5530 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5531 E = MD->end_overridden_methods();
5532 I != E; ++I)
5533 if (CheckMostOverridenMethods(*I, Methods))
5534 return true;
5535 return false;
5536}
5537
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005538/// \brief Member lookup function that determines whether a given C++
5539/// method overloads virtual methods in a base class without overriding any,
5540/// to be used with CXXRecordDecl::lookupInBases().
5541static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5542 CXXBasePath &Path,
5543 void *UserData) {
5544 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5545
5546 FindHiddenVirtualMethodData &Data
5547 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5548
5549 DeclarationName Name = Data.Method->getDeclName();
5550 assert(Name.getNameKind() == DeclarationName::Identifier);
5551
5552 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005553 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005554 for (Path.Decls = BaseRecord->lookup(Name);
David Blaikie3bc93e32012-12-19 00:45:41 +00005555 !Path.Decls.empty();
5556 Path.Decls = Path.Decls.slice(1)) {
5557 NamedDecl *D = Path.Decls.front();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005558 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005559 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005560 foundSameNameMethod = true;
5561 // Interested only in hidden virtual methods.
5562 if (!MD->isVirtual())
5563 continue;
5564 // If the method we are checking overrides a method from its base
5565 // don't warn about the other overloaded methods.
5566 if (!Data.S->IsOverload(Data.Method, MD, false))
5567 return true;
5568 // Collect the overload only if its hidden.
David Blaikie5f750682012-10-19 00:53:08 +00005569 if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005570 overloadedMethods.push_back(MD);
5571 }
5572 }
5573
5574 if (foundSameNameMethod)
5575 Data.OverloadedMethods.append(overloadedMethods.begin(),
5576 overloadedMethods.end());
5577 return foundSameNameMethod;
5578}
5579
David Blaikie5f750682012-10-19 00:53:08 +00005580/// \brief Add the most overriden methods from MD to Methods
5581static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5582 llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5583 if (MD->size_overridden_methods() == 0)
5584 Methods.insert(MD->getCanonicalDecl());
5585 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5586 E = MD->end_overridden_methods();
5587 I != E; ++I)
5588 AddMostOverridenMethods(*I, Methods);
5589}
5590
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005591/// \brief See if a method overloads virtual methods in a base class without
5592/// overriding any.
5593void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5594 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00005595 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005596 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00005597 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005598 return;
5599
5600 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5601 /*bool RecordPaths=*/false,
5602 /*bool DetectVirtual=*/false);
5603 FindHiddenVirtualMethodData Data;
5604 Data.Method = MD;
5605 Data.S = this;
5606
5607 // Keep the base methods that were overriden or introduced in the subclass
5608 // by 'using' in a set. A base method not in this set is hidden.
David Blaikie3bc93e32012-12-19 00:45:41 +00005609 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5610 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5611 NamedDecl *ND = *I;
5612 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
David Blaikie5f750682012-10-19 00:53:08 +00005613 ND = shad->getTargetDecl();
5614 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5615 AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005616 }
5617
5618 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5619 !Data.OverloadedMethods.empty()) {
5620 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5621 << MD << (Data.OverloadedMethods.size() > 1);
5622
5623 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5624 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
Richard Trieuf608aff2013-04-05 23:02:24 +00005625 PartialDiagnostic PD = PDiag(
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005626 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
Richard Trieuf608aff2013-04-05 23:02:24 +00005627 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5628 Diag(overloadedMD->getLocation(), PD);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005629 }
5630 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005631}
5632
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005633void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005634 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005635 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005636 SourceLocation RBrac,
5637 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005638 if (!TagDecl)
5639 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005640
Douglas Gregor42af25f2009-05-11 19:58:34 +00005641 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005642
Rafael Espindolaf729ce02012-07-12 04:32:30 +00005643 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5644 if (l->getKind() != AttributeList::AT_Visibility)
5645 continue;
5646 l->setInvalid();
5647 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5648 l->getName();
5649 }
5650
David Blaikie77b6de02011-09-22 02:58:26 +00005651 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005652 // strict aliasing violation!
5653 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005654 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005655
Douglas Gregor23c94db2010-07-02 17:43:08 +00005656 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005657 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005658}
5659
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005660/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5661/// special functions, such as the default constructor, copy
5662/// constructor, or destructor, to the given C++ class (C++
5663/// [special]p1). This routine can only be executed just before the
5664/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005665void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005666 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005667 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005668
Richard Smithbc2a35d2012-12-08 08:32:28 +00005669 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
Douglas Gregor22584312010-07-02 23:41:54 +00005670 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005671
Richard Smithbc2a35d2012-12-08 08:32:28 +00005672 // If the properties or semantics of the copy constructor couldn't be
5673 // determined while the class was being declared, force a declaration
5674 // of it now.
5675 if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5676 DeclareImplicitCopyConstructor(ClassDecl);
5677 }
5678
Richard Smith80ad52f2013-01-02 11:42:31 +00005679 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005680 ++ASTContext::NumImplicitMoveConstructors;
5681
Richard Smithbc2a35d2012-12-08 08:32:28 +00005682 if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5683 DeclareImplicitMoveConstructor(ClassDecl);
5684 }
5685
Douglas Gregora376d102010-07-02 21:50:04 +00005686 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5687 ++ASTContext::NumImplicitCopyAssignmentOperators;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005688
5689 // If we have a dynamic class, then the copy assignment operator may be
Douglas Gregora376d102010-07-02 21:50:04 +00005690 // virtual, so we have to declare it immediately. This ensures that, e.g.,
Richard Smithbc2a35d2012-12-08 08:32:28 +00005691 // it shows up in the right place in the vtable and that we diagnose
5692 // problems with the implicit exception specification.
5693 if (ClassDecl->isDynamicClass() ||
5694 ClassDecl->needsOverloadResolutionForCopyAssignment())
Douglas Gregora376d102010-07-02 21:50:04 +00005695 DeclareImplicitCopyAssignment(ClassDecl);
5696 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005697
Richard Smith80ad52f2013-01-02 11:42:31 +00005698 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00005699 ++ASTContext::NumImplicitMoveAssignmentOperators;
5700
5701 // Likewise for the move assignment operator.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005702 if (ClassDecl->isDynamicClass() ||
5703 ClassDecl->needsOverloadResolutionForMoveAssignment())
Richard Smithb701d3d2011-12-24 21:56:24 +00005704 DeclareImplicitMoveAssignment(ClassDecl);
5705 }
5706
Douglas Gregor4923aa22010-07-02 20:37:36 +00005707 if (!ClassDecl->hasUserDeclaredDestructor()) {
5708 ++ASTContext::NumImplicitDestructors;
Richard Smithbc2a35d2012-12-08 08:32:28 +00005709
5710 // If we have a dynamic class, then the destructor may be virtual, so we
Douglas Gregor4923aa22010-07-02 20:37:36 +00005711 // have to declare the destructor immediately. This ensures that, e.g., it
5712 // shows up in the right place in the vtable and that we diagnose problems
5713 // with the implicit exception specification.
Richard Smithbc2a35d2012-12-08 08:32:28 +00005714 if (ClassDecl->isDynamicClass() ||
5715 ClassDecl->needsOverloadResolutionForDestructor())
Douglas Gregor4923aa22010-07-02 20:37:36 +00005716 DeclareImplicitDestructor(ClassDecl);
5717 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005718}
5719
Francois Pichet8387e2a2011-04-22 22:18:13 +00005720void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5721 if (!D)
5722 return;
5723
5724 int NumParamList = D->getNumTemplateParameterLists();
5725 for (int i = 0; i < NumParamList; i++) {
5726 TemplateParameterList* Params = D->getTemplateParameterList(i);
5727 for (TemplateParameterList::iterator Param = Params->begin(),
5728 ParamEnd = Params->end();
5729 Param != ParamEnd; ++Param) {
5730 NamedDecl *Named = cast<NamedDecl>(*Param);
5731 if (Named->getDeclName()) {
5732 S->AddDecl(Named);
5733 IdResolver.AddDecl(Named);
5734 }
5735 }
5736 }
5737}
5738
John McCalld226f652010-08-21 09:40:31 +00005739void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005740 if (!D)
5741 return;
5742
5743 TemplateParameterList *Params = 0;
5744 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5745 Params = Template->getTemplateParameters();
5746 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5747 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5748 Params = PartialSpec->getTemplateParameters();
5749 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005750 return;
5751
Douglas Gregor6569d682009-05-27 23:11:45 +00005752 for (TemplateParameterList::iterator Param = Params->begin(),
5753 ParamEnd = Params->end();
5754 Param != ParamEnd; ++Param) {
5755 NamedDecl *Named = cast<NamedDecl>(*Param);
5756 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005757 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005758 IdResolver.AddDecl(Named);
5759 }
5760 }
5761}
5762
John McCalld226f652010-08-21 09:40:31 +00005763void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005764 if (!RecordD) return;
5765 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005766 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005767 PushDeclContext(S, Record);
5768}
5769
John McCalld226f652010-08-21 09:40:31 +00005770void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005771 if (!RecordD) return;
5772 PopDeclContext();
5773}
5774
Douglas Gregor72b505b2008-12-16 21:30:33 +00005775/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5776/// parsing a top-level (non-nested) C++ class, and we are now
5777/// parsing those parts of the given Method declaration that could
5778/// not be parsed earlier (C++ [class.mem]p2), such as default
5779/// arguments. This action should enter the scope of the given
5780/// Method declaration as if we had just parsed the qualified method
5781/// name. However, it should not bring the parameters into scope;
5782/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005783void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005784}
5785
5786/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5787/// C++ method declaration. We're (re-)introducing the given
5788/// function parameter into scope for use in parsing later parts of
5789/// the method declaration. For example, we could see an
5790/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005791void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005792 if (!ParamD)
5793 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005794
John McCalld226f652010-08-21 09:40:31 +00005795 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005796
5797 // If this parameter has an unparsed default argument, clear it out
5798 // to make way for the parsed default argument.
5799 if (Param->hasUnparsedDefaultArg())
5800 Param->setDefaultArg(0);
5801
John McCalld226f652010-08-21 09:40:31 +00005802 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005803 if (Param->getDeclName())
5804 IdResolver.AddDecl(Param);
5805}
5806
5807/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5808/// processing the delayed method declaration for Method. The method
5809/// declaration is now considered finished. There may be a separate
5810/// ActOnStartOfFunctionDef action later (not necessarily
5811/// immediately!) for this method, if it was also defined inside the
5812/// class body.
John McCalld226f652010-08-21 09:40:31 +00005813void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005814 if (!MethodD)
5815 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005816
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005817 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005818
John McCalld226f652010-08-21 09:40:31 +00005819 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005820
5821 // Now that we have our default arguments, check the constructor
5822 // again. It could produce additional diagnostics or affect whether
5823 // the class has implicitly-declared destructors, among other
5824 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005825 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5826 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005827
5828 // Check the default arguments, which we may have added.
5829 if (!Method->isInvalidDecl())
5830 CheckCXXDefaultArguments(Method);
5831}
5832
Douglas Gregor42a552f2008-11-05 20:51:48 +00005833/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005834/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005835/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005836/// emit diagnostics and set the invalid bit to true. In any case, the type
5837/// will be updated to reflect a well-formed type for the constructor and
5838/// returned.
5839QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005840 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005841 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005842
5843 // C++ [class.ctor]p3:
5844 // A constructor shall not be virtual (10.3) or static (9.4). A
5845 // constructor can be invoked for a const, volatile or const
5846 // volatile object. A constructor shall not be declared const,
5847 // volatile, or const volatile (9.3.2).
5848 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005849 if (!D.isInvalidType())
5850 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5851 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5852 << SourceRange(D.getIdentifierLoc());
5853 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005854 }
John McCalld931b082010-08-26 03:08:43 +00005855 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005856 if (!D.isInvalidType())
5857 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5858 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5859 << SourceRange(D.getIdentifierLoc());
5860 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005861 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005862 }
Mike Stump1eb44332009-09-09 15:08:12 +00005863
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005864 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005865 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005866 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005867 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5868 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005869 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005870 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5871 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005872 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005873 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5874 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005875 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005876 }
Mike Stump1eb44332009-09-09 15:08:12 +00005877
Douglas Gregorc938c162011-01-26 05:01:58 +00005878 // C++0x [class.ctor]p4:
5879 // A constructor shall not be declared with a ref-qualifier.
5880 if (FTI.hasRefQualifier()) {
5881 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5882 << FTI.RefQualifierIsLValueRef
5883 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5884 D.setInvalidType();
5885 }
5886
Douglas Gregor42a552f2008-11-05 20:51:48 +00005887 // Rebuild the function type "R" without any type qualifiers (in
5888 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005889 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005890 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005891 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5892 return R;
5893
5894 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5895 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005896 EPI.RefQualifier = RQ_None;
5897
Richard Smith07b0fdc2013-03-18 21:12:30 +00005898 return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005899}
5900
Douglas Gregor72b505b2008-12-16 21:30:33 +00005901/// CheckConstructor - Checks a fully-formed constructor for
5902/// well-formedness, issuing any diagnostics required. Returns true if
5903/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005904void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005905 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005906 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5907 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005908 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005909
5910 // C++ [class.copy]p3:
5911 // A declaration of a constructor for a class X is ill-formed if
5912 // its first parameter is of type (optionally cv-qualified) X and
5913 // either there are no other parameters or else all other
5914 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005915 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005916 ((Constructor->getNumParams() == 1) ||
5917 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005918 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5919 Constructor->getTemplateSpecializationKind()
5920 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005921 QualType ParamType = Constructor->getParamDecl(0)->getType();
5922 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5923 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005924 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005925 const char *ConstRef
5926 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5927 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005928 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005929 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005930
5931 // FIXME: Rather that making the constructor invalid, we should endeavor
5932 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005933 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005934 }
5935 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005936}
5937
John McCall15442822010-08-04 01:04:25 +00005938/// CheckDestructor - Checks a fully-formed destructor definition for
5939/// well-formedness, issuing any diagnostics required. Returns true
5940/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005941bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005942 CXXRecordDecl *RD = Destructor->getParent();
5943
Peter Collingbournef51cfb82013-05-20 14:12:25 +00005944 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005945 SourceLocation Loc;
5946
5947 if (!Destructor->isImplicit())
5948 Loc = Destructor->getLocation();
5949 else
5950 Loc = RD->getLocation();
5951
5952 // If we have a virtual destructor, look up the deallocation function
5953 FunctionDecl *OperatorDelete = 0;
5954 DeclarationName Name =
5955 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005956 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005957 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005958
Eli Friedman5f2987c2012-02-02 03:46:19 +00005959 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005960
5961 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005962 }
Anders Carlsson37909802009-11-30 21:24:50 +00005963
5964 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005965}
5966
Mike Stump1eb44332009-09-09 15:08:12 +00005967static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005968FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5969 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5970 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005971 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005972}
5973
Douglas Gregor42a552f2008-11-05 20:51:48 +00005974/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5975/// the well-formednes of the destructor declarator @p D with type @p
5976/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005977/// emit diagnostics and set the declarator to invalid. Even if this happens,
5978/// will be updated to reflect a well-formed type for the destructor and
5979/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005980QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005981 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005982 // C++ [class.dtor]p1:
5983 // [...] A typedef-name that names a class is a class-name
5984 // (7.1.3); however, a typedef-name that names a class shall not
5985 // be used as the identifier in the declarator for a destructor
5986 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005987 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005988 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005989 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005990 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005991 else if (const TemplateSpecializationType *TST =
5992 DeclaratorType->getAs<TemplateSpecializationType>())
5993 if (TST->isTypeAlias())
5994 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5995 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005996
5997 // C++ [class.dtor]p2:
5998 // A destructor is used to destroy objects of its class type. A
5999 // destructor takes no parameters, and no return type can be
6000 // specified for it (not even void). The address of a destructor
6001 // shall not be taken. A destructor shall not be static. A
6002 // destructor can be invoked for a const, volatile or const
6003 // volatile object. A destructor shall not be declared const,
6004 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00006005 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00006006 if (!D.isInvalidType())
6007 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6008 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00006009 << SourceRange(D.getIdentifierLoc())
6010 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6011
John McCalld931b082010-08-26 03:08:43 +00006012 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00006013 }
Chris Lattner65401802009-04-25 08:28:21 +00006014 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006015 // Destructors don't have return types, but the parser will
6016 // happily parse something like:
6017 //
6018 // class X {
6019 // float ~X();
6020 // };
6021 //
6022 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006023 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6024 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6025 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00006026 }
Mike Stump1eb44332009-09-09 15:08:12 +00006027
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006028 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00006029 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00006030 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006031 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6032 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006033 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006034 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6035 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00006036 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006037 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6038 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00006039 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006040 }
6041
Douglas Gregorc938c162011-01-26 05:01:58 +00006042 // C++0x [class.dtor]p2:
6043 // A destructor shall not be declared with a ref-qualifier.
6044 if (FTI.hasRefQualifier()) {
6045 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6046 << FTI.RefQualifierIsLValueRef
6047 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6048 D.setInvalidType();
6049 }
6050
Douglas Gregor42a552f2008-11-05 20:51:48 +00006051 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00006052 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006053 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6054
6055 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00006056 FTI.freeArgs();
6057 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00006058 }
6059
Mike Stump1eb44332009-09-09 15:08:12 +00006060 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00006061 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00006062 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00006063 D.setInvalidType();
6064 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00006065
6066 // Rebuild the function type "R" without any type qualifiers or
6067 // parameters (in case any of the errors above fired) and with
6068 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00006069 // types.
John McCalle23cf432010-12-14 08:05:40 +00006070 if (!D.isInvalidType())
6071 return R;
6072
Douglas Gregord92ec472010-07-01 05:10:53 +00006073 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00006074 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6075 EPI.Variadic = false;
6076 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00006077 EPI.RefQualifier = RQ_None;
Dmitri Gribenko55431692013-05-05 00:41:58 +00006078 return Context.getFunctionType(Context.VoidTy, None, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00006079}
6080
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006081/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6082/// well-formednes of the conversion function declarator @p D with
6083/// type @p R. If there are any errors in the declarator, this routine
6084/// will emit diagnostics and return true. Otherwise, it will return
6085/// false. Either way, the type @p R will be updated to reflect a
6086/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00006087void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00006088 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006089 // C++ [class.conv.fct]p1:
6090 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00006091 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00006092 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00006093 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00006094 if (!D.isInvalidType())
6095 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
Eli Friedman4cde94a2013-06-20 20:58:02 +00006096 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6097 << D.getName().getSourceRange();
Chris Lattner6e475012009-04-25 08:35:12 +00006098 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00006099 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006100 }
John McCalla3f81372010-04-13 00:04:31 +00006101
6102 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6103
Chris Lattner6e475012009-04-25 08:35:12 +00006104 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006105 // Conversion functions don't have return types, but the parser will
6106 // happily parse something like:
6107 //
6108 // class X {
6109 // float operator bool();
6110 // };
6111 //
6112 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00006113 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6114 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6115 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00006116 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006117 }
6118
John McCalla3f81372010-04-13 00:04:31 +00006119 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6120
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006121 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00006122 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006123 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6124
6125 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00006126 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00006127 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00006128 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006129 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00006130 D.setInvalidType();
6131 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006132
John McCalla3f81372010-04-13 00:04:31 +00006133 // Diagnose "&operator bool()" and other such nonsense. This
6134 // is actually a gcc extension which we don't support.
6135 if (Proto->getResultType() != ConvType) {
6136 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6137 << Proto->getResultType();
6138 D.setInvalidType();
6139 ConvType = Proto->getResultType();
6140 }
6141
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006142 // C++ [class.conv.fct]p4:
6143 // The conversion-type-id shall not represent a function type nor
6144 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006145 if (ConvType->isArrayType()) {
6146 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6147 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006148 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006149 } else if (ConvType->isFunctionType()) {
6150 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6151 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00006152 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006153 }
6154
6155 // Rebuild the function type "R" without any parameters (in case any
6156 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00006157 // return type.
John McCalle23cf432010-12-14 08:05:40 +00006158 if (D.isInvalidType())
Dmitri Gribenko55431692013-05-05 00:41:58 +00006159 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006160
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006161 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00006162 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00006163 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006164 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00006165 diag::warn_cxx98_compat_explicit_conversion_functions :
6166 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006167 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006168}
6169
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006170/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6171/// the declaration of the given C++ conversion function. This routine
6172/// is responsible for recording the conversion function in the C++
6173/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00006174Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006175 assert(Conversion && "Expected to receive a conversion function declaration");
6176
Douglas Gregor9d350972008-12-12 08:25:50 +00006177 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006178
6179 // Make sure we aren't redeclaring the conversion function.
6180 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006181
6182 // C++ [class.conv.fct]p1:
6183 // [...] A conversion function is never used to convert a
6184 // (possibly cv-qualified) object to the (possibly cv-qualified)
6185 // same object type (or a reference to it), to a (possibly
6186 // cv-qualified) base class of that type (or a reference to it),
6187 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00006188 // FIXME: Suppress this warning if the conversion function ends up being a
6189 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00006190 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006191 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00006192 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006193 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006194 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6195 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00006196 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00006197 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006198 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6199 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00006200 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006201 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006202 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00006203 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006204 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006205 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00006206 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00006207 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006208 }
6209
Douglas Gregore80622f2010-09-29 04:25:11 +00006210 if (FunctionTemplateDecl *ConversionTemplate
6211 = Conversion->getDescribedFunctionTemplate())
6212 return ConversionTemplate;
6213
John McCalld226f652010-08-21 09:40:31 +00006214 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00006215}
6216
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006217//===----------------------------------------------------------------------===//
6218// Namespace Handling
6219//===----------------------------------------------------------------------===//
6220
Richard Smithd1a55a62012-10-04 22:13:39 +00006221/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6222/// reopened.
6223static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6224 SourceLocation Loc,
6225 IdentifierInfo *II, bool *IsInline,
6226 NamespaceDecl *PrevNS) {
6227 assert(*IsInline != PrevNS->isInline());
John McCallea318642010-08-26 09:15:37 +00006228
Richard Smithc969e6a2012-10-05 01:46:25 +00006229 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6230 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6231 // inline namespaces, with the intention of bringing names into namespace std.
6232 //
6233 // We support this just well enough to get that case working; this is not
6234 // sufficient to support reopening namespaces as inline in general.
Richard Smithd1a55a62012-10-04 22:13:39 +00006235 if (*IsInline && II && II->getName().startswith("__atomic") &&
6236 S.getSourceManager().isInSystemHeader(Loc)) {
Richard Smithc969e6a2012-10-05 01:46:25 +00006237 // Mark all prior declarations of the namespace as inline.
Richard Smithd1a55a62012-10-04 22:13:39 +00006238 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6239 NS = NS->getPreviousDecl())
6240 NS->setInline(*IsInline);
6241 // Patch up the lookup table for the containing namespace. This isn't really
6242 // correct, but it's good enough for this particular case.
6243 for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6244 E = PrevNS->decls_end(); I != E; ++I)
6245 if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6246 PrevNS->getParent()->makeDeclVisibleInContext(ND);
6247 return;
6248 }
6249
6250 if (PrevNS->isInline())
6251 // The user probably just forgot the 'inline', so suggest that it
6252 // be added back.
6253 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6254 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6255 else
6256 S.Diag(Loc, diag::err_inline_namespace_mismatch)
6257 << IsInline;
6258
6259 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6260 *IsInline = PrevNS->isInline();
6261}
John McCallea318642010-08-26 09:15:37 +00006262
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006263/// ActOnStartNamespaceDef - This is called at the start of a namespace
6264/// definition.
John McCalld226f652010-08-21 09:40:31 +00006265Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00006266 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006267 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00006268 SourceLocation IdentLoc,
6269 IdentifierInfo *II,
6270 SourceLocation LBrace,
6271 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006272 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6273 // For anonymous namespace, take the location of the left brace.
6274 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006275 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00006276 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006277 bool IsStd = false;
6278 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006279 Scope *DeclRegionScope = NamespcScope->getParent();
6280
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006281 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006282 if (II) {
6283 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00006284 // The identifier in an original-namespace-definition shall not
6285 // have been previously defined in the declarative region in
6286 // which the original-namespace-definition appears. The
6287 // identifier in an original-namespace-definition is the name of
6288 // the namespace. Subsequently in that declarative region, it is
6289 // treated as an original-namespace-name.
6290 //
6291 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00006292 // look through using directives, just look for any ordinary names.
6293
6294 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006295 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6296 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00006297 NamedDecl *PrevDecl = 0;
David Blaikie3bc93e32012-12-19 00:45:41 +00006298 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6299 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6300 ++I) {
6301 if ((*I)->getIdentifierNamespace() & IDNS) {
6302 PrevDecl = *I;
Douglas Gregor010157f2011-05-06 23:28:47 +00006303 break;
6304 }
6305 }
6306
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006307 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6308
6309 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00006310 // This is an extended namespace definition.
Richard Smithd1a55a62012-10-04 22:13:39 +00006311 if (IsInline != PrevNS->isInline())
6312 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6313 &IsInline, PrevNS);
Douglas Gregor44b43212008-12-11 16:49:14 +00006314 } else if (PrevDecl) {
6315 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006316 Diag(Loc, diag::err_redefinition_different_kind)
6317 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00006318 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00006319 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00006320 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006321 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00006322 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00006323 // This is the first "real" definition of the namespace "std", so update
6324 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006325 PrevNS = getStdNamespace();
6326 IsStd = true;
6327 AddToKnown = !IsInline;
6328 } else {
6329 // We've seen this namespace for the first time.
6330 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00006331 }
Douglas Gregor44b43212008-12-11 16:49:14 +00006332 } else {
John McCall9aeed322009-10-01 00:25:31 +00006333 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006334
6335 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00006336 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00006337 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006338 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006339 } else {
6340 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006341 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00006342 }
6343
Richard Smithd1a55a62012-10-04 22:13:39 +00006344 if (PrevNS && IsInline != PrevNS->isInline())
6345 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6346 &IsInline, PrevNS);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006347 }
6348
6349 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6350 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00006351 if (IsInvalid)
6352 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006353
6354 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00006355
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006356 // FIXME: Should we be merging attributes?
6357 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006358 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006359
6360 if (IsStd)
6361 StdNamespace = Namespc;
6362 if (AddToKnown)
6363 KnownNamespaces[Namespc] = false;
6364
6365 if (II) {
6366 PushOnScopeChains(Namespc, DeclRegionScope);
6367 } else {
6368 // Link the anonymous namespace into its parent.
6369 DeclContext *Parent = CurContext->getRedeclContext();
6370 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6371 TU->setAnonymousNamespace(Namespc);
6372 } else {
6373 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00006374 }
John McCall9aeed322009-10-01 00:25:31 +00006375
Douglas Gregora4181472010-03-24 00:46:35 +00006376 CurContext->addDecl(Namespc);
6377
John McCall9aeed322009-10-01 00:25:31 +00006378 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
6379 // behaves as if it were replaced by
6380 // namespace unique { /* empty body */ }
6381 // using namespace unique;
6382 // namespace unique { namespace-body }
6383 // where all occurrences of 'unique' in a translation unit are
6384 // replaced by the same identifier and this identifier differs
6385 // from all other identifiers in the entire program.
6386
6387 // We just create the namespace with an empty name and then add an
6388 // implicit using declaration, just like the standard suggests.
6389 //
6390 // CodeGen enforces the "universally unique" aspect by giving all
6391 // declarations semantically contained within an anonymous
6392 // namespace internal linkage.
6393
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006394 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00006395 UsingDirectiveDecl* UD
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006396 = UsingDirectiveDecl::Create(Context, Parent,
John McCall5fdd7642009-12-16 02:06:49 +00006397 /* 'using' */ LBrace,
6398 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00006399 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00006400 /* identifier */ SourceLocation(),
6401 Namespc,
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006402 /* Ancestor */ Parent);
John McCall5fdd7642009-12-16 02:06:49 +00006403 UD->setImplicit();
Nick Lewycky4b7631b2012-11-04 20:21:54 +00006404 Parent->addDecl(UD);
John McCall5fdd7642009-12-16 02:06:49 +00006405 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006406 }
6407
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00006408 ActOnDocumentableDecl(Namespc);
6409
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006410 // Although we could have an invalid decl (i.e. the namespace name is a
6411 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00006412 // FIXME: We should be able to push Namespc here, so that the each DeclContext
6413 // for the namespace has the declarations that showed up in that particular
6414 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00006415 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00006416 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006417}
6418
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006419/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6420/// is a namespace alias, returns the namespace it points to.
6421static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6422 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6423 return AD->getNamespace();
6424 return dyn_cast_or_null<NamespaceDecl>(D);
6425}
6426
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006427/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6428/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00006429void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006430 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6431 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006432 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006433 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00006434 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00006435 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00006436}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006437
John McCall384aff82010-08-25 07:42:41 +00006438CXXRecordDecl *Sema::getStdBadAlloc() const {
6439 return cast_or_null<CXXRecordDecl>(
6440 StdBadAlloc.get(Context.getExternalSource()));
6441}
6442
6443NamespaceDecl *Sema::getStdNamespace() const {
6444 return cast_or_null<NamespaceDecl>(
6445 StdNamespace.get(Context.getExternalSource()));
6446}
6447
Douglas Gregor66992202010-06-29 17:53:46 +00006448/// \brief Retrieve the special "std" namespace, which may require us to
6449/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006450NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00006451 if (!StdNamespace) {
6452 // The "std" namespace has not yet been defined, so build one implicitly.
6453 StdNamespace = NamespaceDecl::Create(Context,
6454 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006455 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00006456 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00006457 &PP.getIdentifierTable().get("std"),
6458 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006459 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00006460 }
6461
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00006462 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00006463}
6464
Sebastian Redl395e04d2012-01-17 22:49:33 +00006465bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006466 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00006467 "Looking for std::initializer_list outside of C++.");
6468
6469 // We're looking for implicit instantiations of
6470 // template <typename E> class std::initializer_list.
6471
6472 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6473 return false;
6474
Sebastian Redl84760e32012-01-17 22:49:58 +00006475 ClassTemplateDecl *Template = 0;
6476 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006477
Sebastian Redl84760e32012-01-17 22:49:58 +00006478 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00006479
Sebastian Redl84760e32012-01-17 22:49:58 +00006480 ClassTemplateSpecializationDecl *Specialization =
6481 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6482 if (!Specialization)
6483 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006484
Sebastian Redl84760e32012-01-17 22:49:58 +00006485 Template = Specialization->getSpecializedTemplate();
6486 Arguments = Specialization->getTemplateArgs().data();
6487 } else if (const TemplateSpecializationType *TST =
6488 Ty->getAs<TemplateSpecializationType>()) {
6489 Template = dyn_cast_or_null<ClassTemplateDecl>(
6490 TST->getTemplateName().getAsTemplateDecl());
6491 Arguments = TST->getArgs();
6492 }
6493 if (!Template)
6494 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00006495
6496 if (!StdInitializerList) {
6497 // Haven't recognized std::initializer_list yet, maybe this is it.
6498 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6499 if (TemplateClass->getIdentifier() !=
6500 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006501 !getStdNamespace()->InEnclosingNamespaceSetOf(
6502 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00006503 return false;
6504 // This is a template called std::initializer_list, but is it the right
6505 // template?
6506 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006507 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00006508 return false;
6509 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6510 return false;
6511
6512 // It's the right template.
6513 StdInitializerList = Template;
6514 }
6515
6516 if (Template != StdInitializerList)
6517 return false;
6518
6519 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00006520 if (Element)
6521 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00006522 return true;
6523}
6524
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006525static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6526 NamespaceDecl *Std = S.getStdNamespace();
6527 if (!Std) {
6528 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6529 return 0;
6530 }
6531
6532 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6533 Loc, Sema::LookupOrdinaryName);
6534 if (!S.LookupQualifiedName(Result, Std)) {
6535 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6536 return 0;
6537 }
6538 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6539 if (!Template) {
6540 Result.suppressDiagnostics();
6541 // We found something weird. Complain about the first thing we found.
6542 NamedDecl *Found = *Result.begin();
6543 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6544 return 0;
6545 }
6546
6547 // We found some template called std::initializer_list. Now verify that it's
6548 // correct.
6549 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00006550 if (Params->getMinRequiredArguments() != 1 ||
6551 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00006552 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6553 return 0;
6554 }
6555
6556 return Template;
6557}
6558
6559QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6560 if (!StdInitializerList) {
6561 StdInitializerList = LookupStdInitializerList(*this, Loc);
6562 if (!StdInitializerList)
6563 return QualType();
6564 }
6565
6566 TemplateArgumentListInfo Args(Loc, Loc);
6567 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6568 Context.getTrivialTypeSourceInfo(Element,
6569 Loc)));
6570 return Context.getCanonicalType(
6571 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6572}
6573
Sebastian Redl98d36062012-01-17 22:50:14 +00006574bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6575 // C++ [dcl.init.list]p2:
6576 // A constructor is an initializer-list constructor if its first parameter
6577 // is of type std::initializer_list<E> or reference to possibly cv-qualified
6578 // std::initializer_list<E> for some type E, and either there are no other
6579 // parameters or else all other parameters have default arguments.
6580 if (Ctor->getNumParams() < 1 ||
6581 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6582 return false;
6583
6584 QualType ArgType = Ctor->getParamDecl(0)->getType();
6585 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6586 ArgType = RT->getPointeeType().getUnqualifiedType();
6587
6588 return isStdInitializerList(ArgType, 0);
6589}
6590
Douglas Gregor9172aa62011-03-26 22:25:30 +00006591/// \brief Determine whether a using statement is in a context where it will be
6592/// apply in all contexts.
6593static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6594 switch (CurContext->getDeclKind()) {
6595 case Decl::TranslationUnit:
6596 return true;
6597 case Decl::LinkageSpec:
6598 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6599 default:
6600 return false;
6601 }
6602}
6603
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006604namespace {
6605
6606// Callback to only accept typo corrections that are namespaces.
6607class NamespaceValidatorCCC : public CorrectionCandidateCallback {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00006608public:
6609 bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6610 if (NamedDecl *ND = candidate.getCorrectionDecl())
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006611 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006612 return false;
6613 }
6614};
6615
6616}
6617
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006618static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6619 CXXScopeSpec &SS,
6620 SourceLocation IdentLoc,
6621 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006622 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006623 R.clear();
6624 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006625 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00006626 Validator)) {
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006627 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
Richard Smith2d670972013-08-17 00:46:16 +00006628 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6629 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006630 Ident->getName().equals(CorrectedStr);
Richard Smith2d670972013-08-17 00:46:16 +00006631 S.diagnoseTypo(Corrected,
6632 S.PDiag(diag::err_using_directive_member_suggest)
6633 << Ident << DC << DroppedSpecifier << SS.getRange(),
6634 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006635 } else {
Richard Smith2d670972013-08-17 00:46:16 +00006636 S.diagnoseTypo(Corrected,
6637 S.PDiag(diag::err_using_directive_suggest) << Ident,
6638 S.PDiag(diag::note_namespace_defined_here));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +00006639 }
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00006640 R.addDecl(Corrected.getCorrectionDecl());
6641 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006642 }
6643 return false;
6644}
6645
John McCalld226f652010-08-21 09:40:31 +00006646Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006647 SourceLocation UsingLoc,
6648 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006649 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006650 SourceLocation IdentLoc,
6651 IdentifierInfo *NamespcName,
6652 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00006653 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6654 assert(NamespcName && "Invalid NamespcName.");
6655 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006656
6657 // This can only happen along a recovery path.
6658 while (S->getFlags() & Scope::TemplateParamScope)
6659 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006660 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006661
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006662 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006663 NestedNameSpecifier *Qualifier = 0;
6664 if (SS.isSet())
6665 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6666
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006667 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006668 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6669 LookupParsedName(R, S, &SS);
6670 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006671 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006672
Douglas Gregor66992202010-06-29 17:53:46 +00006673 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006674 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006675 // Allow "using namespace std;" or "using namespace ::std;" even if
6676 // "std" hasn't been defined yet, for GCC compatibility.
6677 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6678 NamespcName->isStr("std")) {
6679 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006680 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006681 R.resolveKind();
6682 }
6683 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006684 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006685 }
6686
John McCallf36e02d2009-10-09 21:13:30 +00006687 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006688 NamedDecl *Named = R.getFoundDecl();
6689 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6690 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006691 // C++ [namespace.udir]p1:
6692 // A using-directive specifies that the names in the nominated
6693 // namespace can be used in the scope in which the
6694 // using-directive appears after the using-directive. During
6695 // unqualified name lookup (3.4.1), the names appear as if they
6696 // were declared in the nearest enclosing namespace which
6697 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006698 // namespace. [Note: in this context, "contains" means "contains
6699 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006700
6701 // Find enclosing context containing both using-directive and
6702 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006703 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006704 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6705 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6706 CommonAncestor = CommonAncestor->getParent();
6707
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006708 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006709 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006710 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006711
Douglas Gregor9172aa62011-03-26 22:25:30 +00006712 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Eli Friedman24146972013-08-22 00:27:10 +00006713 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006714 Diag(IdentLoc, diag::warn_using_directive_in_header);
6715 }
6716
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006717 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006718 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006719 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006720 }
6721
Richard Smith6b3d3e52013-02-20 19:22:51 +00006722 if (UDir)
6723 ProcessDeclAttributeList(S, UDir, AttrList);
6724
John McCalld226f652010-08-21 09:40:31 +00006725 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006726}
6727
6728void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006729 // If the scope has an associated entity and the using directive is at
6730 // namespace or translation unit scope, add the UsingDirectiveDecl into
6731 // its lookup structure so qualified name lookup can find it.
6732 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6733 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006734 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006735 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00006736 // Otherwise, it is at block sope. The using-directives will affect lookup
6737 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00006738 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006739}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006740
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006741
John McCalld226f652010-08-21 09:40:31 +00006742Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006743 AccessSpecifier AS,
6744 bool HasUsingKeyword,
6745 SourceLocation UsingLoc,
6746 CXXScopeSpec &SS,
6747 UnqualifiedId &Name,
6748 AttributeList *AttrList,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006749 bool HasTypenameKeyword,
John McCall78b81052010-11-10 02:40:36 +00006750 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006751 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006752
Douglas Gregor12c118a2009-11-04 16:30:06 +00006753 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006754 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006755 case UnqualifiedId::IK_Identifier:
6756 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006757 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006758 case UnqualifiedId::IK_ConversionFunctionId:
6759 break;
6760
6761 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006762 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00006763 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00006764 Diag(Name.getLocStart(),
Richard Smith80ad52f2013-01-02 11:42:31 +00006765 getLangOpts().CPlusPlus11 ?
Richard Smith07b0fdc2013-03-18 21:12:30 +00006766 diag::warn_cxx98_compat_using_decl_constructor :
Richard Smithebaf0e62011-10-18 20:49:44 +00006767 diag::err_using_decl_constructor)
6768 << SS.getRange();
6769
Richard Smith80ad52f2013-01-02 11:42:31 +00006770 if (getLangOpts().CPlusPlus11) break;
John McCall604e7f12009-12-08 07:46:18 +00006771
John McCalld226f652010-08-21 09:40:31 +00006772 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006773
6774 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006775 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006776 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006777 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006778
6779 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00006780 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00006781 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006782 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006783 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006784
6785 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6786 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006787 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006788 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006789
Richard Smith07b0fdc2013-03-18 21:12:30 +00006790 // Warn about access declarations.
John McCall60fa3cf2009-12-11 02:10:03 +00006791 if (!HasUsingKeyword) {
Enea Zaffanellad4de59d2013-07-17 17:28:56 +00006792 Diag(Name.getLocStart(),
Richard Smith1b2209f2013-06-13 02:12:17 +00006793 getLangOpts().CPlusPlus11 ? diag::err_access_decl
6794 : diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006795 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006796 }
6797
Douglas Gregor56c04582010-12-16 00:46:58 +00006798 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6799 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6800 return 0;
6801
John McCall9488ea12009-11-17 05:59:44 +00006802 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006803 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006804 /* IsInstantiation */ false,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00006805 HasTypenameKeyword, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006806 if (UD)
6807 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006808
John McCalld226f652010-08-21 09:40:31 +00006809 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006810}
6811
Douglas Gregor09acc982010-07-07 23:08:52 +00006812/// \brief Determine whether a using declaration considers the given
6813/// declarations as "equivalent", e.g., if they are redeclarations of
6814/// the same entity or are both typedefs of the same type.
6815static bool
6816IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6817 bool &SuppressRedeclaration) {
6818 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6819 SuppressRedeclaration = false;
6820 return true;
6821 }
6822
Richard Smith162e1c12011-04-15 14:24:37 +00006823 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6824 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006825 SuppressRedeclaration = true;
6826 return Context.hasSameType(TD1->getUnderlyingType(),
6827 TD2->getUnderlyingType());
6828 }
6829
6830 return false;
6831}
6832
6833
John McCall9f54ad42009-12-10 09:41:52 +00006834/// Determines whether to create a using shadow decl for a particular
6835/// decl, given the set of decls existing prior to this using lookup.
6836bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6837 const LookupResult &Previous) {
6838 // Diagnose finding a decl which is not from a base class of the
6839 // current class. We do this now because there are cases where this
6840 // function will silently decide not to build a shadow decl, which
6841 // will pre-empt further diagnostics.
6842 //
6843 // We don't need to do this in C++0x because we do the check once on
6844 // the qualifier.
6845 //
6846 // FIXME: diagnose the following if we care enough:
6847 // struct A { int foo; };
6848 // struct B : A { using A::foo; };
6849 // template <class T> struct C : A {};
6850 // template <class T> struct D : C<T> { using B::foo; } // <---
6851 // This is invalid (during instantiation) in C++03 because B::foo
6852 // resolves to the using decl in B, which is not a base class of D<T>.
6853 // We can't diagnose it immediately because C<T> is an unknown
6854 // specialization. The UsingShadowDecl in D<T> then points directly
6855 // to A::foo, which will look well-formed when we instantiate.
6856 // The right solution is to not collapse the shadow-decl chain.
Richard Smith80ad52f2013-01-02 11:42:31 +00006857 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00006858 DeclContext *OrigDC = Orig->getDeclContext();
6859
6860 // Handle enums and anonymous structs.
6861 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6862 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6863 while (OrigRec->isAnonymousStructOrUnion())
6864 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6865
6866 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6867 if (OrigDC == CurContext) {
6868 Diag(Using->getLocation(),
6869 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006870 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006871 Diag(Orig->getLocation(), diag::note_using_decl_target);
6872 return true;
6873 }
6874
Douglas Gregordc355712011-02-25 00:36:19 +00006875 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006876 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006877 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006878 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006879 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006880 Diag(Orig->getLocation(), diag::note_using_decl_target);
6881 return true;
6882 }
6883 }
6884
6885 if (Previous.empty()) return false;
6886
6887 NamedDecl *Target = Orig;
6888 if (isa<UsingShadowDecl>(Target))
6889 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6890
John McCalld7533ec2009-12-11 02:33:26 +00006891 // If the target happens to be one of the previous declarations, we
6892 // don't have a conflict.
6893 //
6894 // FIXME: but we might be increasing its access, in which case we
6895 // should redeclare it.
6896 NamedDecl *NonTag = 0, *Tag = 0;
6897 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6898 I != E; ++I) {
6899 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006900 bool Result;
6901 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6902 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006903
6904 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6905 }
6906
John McCall9f54ad42009-12-10 09:41:52 +00006907 if (Target->isFunctionOrFunctionTemplate()) {
6908 FunctionDecl *FD;
6909 if (isa<FunctionTemplateDecl>(Target))
6910 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6911 else
6912 FD = cast<FunctionDecl>(Target);
6913
6914 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006915 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006916 case Ovl_Overload:
6917 return false;
6918
6919 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006920 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006921 break;
6922
6923 // We found a decl with the exact signature.
6924 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006925 // If we're in a record, we want to hide the target, so we
6926 // return true (without a diagnostic) to tell the caller not to
6927 // build a shadow decl.
6928 if (CurContext->isRecord())
6929 return true;
6930
6931 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006932 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006933 break;
6934 }
6935
6936 Diag(Target->getLocation(), diag::note_using_decl_target);
6937 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6938 return true;
6939 }
6940
6941 // Target is not a function.
6942
John McCall9f54ad42009-12-10 09:41:52 +00006943 if (isa<TagDecl>(Target)) {
6944 // No conflict between a tag and a non-tag.
6945 if (!Tag) return false;
6946
John McCall41ce66f2009-12-10 19:51:03 +00006947 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006948 Diag(Target->getLocation(), diag::note_using_decl_target);
6949 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6950 return true;
6951 }
6952
6953 // No conflict between a tag and a non-tag.
6954 if (!NonTag) return false;
6955
John McCall41ce66f2009-12-10 19:51:03 +00006956 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006957 Diag(Target->getLocation(), diag::note_using_decl_target);
6958 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6959 return true;
6960}
6961
John McCall9488ea12009-11-17 05:59:44 +00006962/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006963UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006964 UsingDecl *UD,
6965 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006966
6967 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006968 NamedDecl *Target = Orig;
6969 if (isa<UsingShadowDecl>(Target)) {
6970 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6971 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006972 }
6973
6974 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006975 = UsingShadowDecl::Create(Context, CurContext,
6976 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006977 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006978
6979 Shadow->setAccess(UD->getAccess());
6980 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6981 Shadow->setInvalidDecl();
6982
John McCall9488ea12009-11-17 05:59:44 +00006983 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006984 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006985 else
John McCall604e7f12009-12-08 07:46:18 +00006986 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006987
John McCall604e7f12009-12-08 07:46:18 +00006988
John McCall9f54ad42009-12-10 09:41:52 +00006989 return Shadow;
6990}
John McCall604e7f12009-12-08 07:46:18 +00006991
John McCall9f54ad42009-12-10 09:41:52 +00006992/// Hides a using shadow declaration. This is required by the current
6993/// using-decl implementation when a resolvable using declaration in a
6994/// class is followed by a declaration which would hide or override
6995/// one or more of the using decl's targets; for example:
6996///
6997/// struct Base { void foo(int); };
6998/// struct Derived : Base {
6999/// using Base::foo;
7000/// void foo(int);
7001/// };
7002///
7003/// The governing language is C++03 [namespace.udecl]p12:
7004///
7005/// When a using-declaration brings names from a base class into a
7006/// derived class scope, member functions in the derived class
7007/// override and/or hide member functions with the same name and
7008/// parameter types in a base class (rather than conflicting).
7009///
7010/// There are two ways to implement this:
7011/// (1) optimistically create shadow decls when they're not hidden
7012/// by existing declarations, or
7013/// (2) don't create any shadow decls (or at least don't make them
7014/// visible) until we've fully parsed/instantiated the class.
7015/// The problem with (1) is that we might have to retroactively remove
7016/// a shadow decl, which requires several O(n) operations because the
7017/// decl structures are (very reasonably) not designed for removal.
7018/// (2) avoids this but is very fiddly and phase-dependent.
7019void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00007020 if (Shadow->getDeclName().getNameKind() ==
7021 DeclarationName::CXXConversionFunctionName)
7022 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7023
John McCall9f54ad42009-12-10 09:41:52 +00007024 // Remove it from the DeclContext...
7025 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007026
John McCall9f54ad42009-12-10 09:41:52 +00007027 // ...and the scope, if applicable...
7028 if (S) {
John McCalld226f652010-08-21 09:40:31 +00007029 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00007030 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00007031 }
7032
John McCall9f54ad42009-12-10 09:41:52 +00007033 // ...and the using decl.
7034 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7035
7036 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00007037 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00007038}
7039
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007040namespace {
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007041class UsingValidatorCCC : public CorrectionCandidateCallback {
7042public:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007043 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation)
7044 : HasTypenameKeyword(HasTypenameKeyword),
7045 IsInstantiation(IsInstantiation) {}
7046
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007047 bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7048 NamedDecl *ND = Candidate.getCorrectionDecl();
7049
7050 // Keywords are not valid here.
7051 if (!ND || isa<NamespaceDecl>(ND))
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007052 return false;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007053
7054 // Completely unqualified names are invalid for a 'using' declaration.
7055 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7056 return false;
7057
7058 if (isa<TypeDecl>(ND))
7059 return HasTypenameKeyword || !IsInstantiation;
7060
7061 return !HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007062 }
7063
7064private:
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007065 bool HasTypenameKeyword;
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007066 bool IsInstantiation;
7067};
Benjamin Kramer4c7736e2013-07-24 15:28:33 +00007068} // end anonymous namespace
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007069
John McCall7ba107a2009-11-18 02:36:19 +00007070/// Builds a using declaration.
7071///
7072/// \param IsInstantiation - Whether this call arises from an
7073/// instantiation of an unresolved using declaration. We treat
7074/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00007075NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7076 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007077 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007078 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00007079 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00007080 bool IsInstantiation,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007081 bool HasTypenameKeyword,
John McCall7ba107a2009-11-18 02:36:19 +00007082 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00007083 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007084 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00007085 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00007086
Anders Carlsson550b14b2009-08-28 05:49:21 +00007087 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00007088
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007089 if (SS.isEmpty()) {
7090 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00007091 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007092 }
Mike Stump1eb44332009-09-09 15:08:12 +00007093
John McCall9f54ad42009-12-10 09:41:52 +00007094 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007095 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00007096 ForRedeclaration);
7097 Previous.setHideTags(false);
7098 if (S) {
7099 LookupName(Previous, S);
7100
7101 // It is really dumb that we have to do this.
7102 LookupResult::Filter F = Previous.makeFilter();
7103 while (F.hasNext()) {
7104 NamedDecl *D = F.next();
7105 if (!isDeclInScope(D, CurContext, S))
7106 F.erase();
7107 }
7108 F.done();
7109 } else {
7110 assert(IsInstantiation && "no scope in non-instantiation");
7111 assert(CurContext->isRecord() && "scope not record in instantiation");
7112 LookupQualifiedName(Previous, CurContext);
7113 }
7114
John McCall9f54ad42009-12-10 09:41:52 +00007115 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007116 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7117 SS, IdentLoc, Previous))
John McCall9f54ad42009-12-10 09:41:52 +00007118 return 0;
7119
7120 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00007121 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7122 return 0;
7123
John McCallaf8e6ed2009-11-12 03:15:40 +00007124 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007125 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00007126 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00007127 if (!LookupContext) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007128 if (HasTypenameKeyword) {
John McCalled976492009-12-04 22:46:56 +00007129 // FIXME: not all declaration name kinds are legal here
7130 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7131 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00007132 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007133 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00007134 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007135 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7136 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00007137 }
John McCalled976492009-12-04 22:46:56 +00007138 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00007139 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007140 NameInfo, HasTypenameKeyword);
Anders Carlsson550b14b2009-08-28 05:49:21 +00007141 }
John McCalled976492009-12-04 22:46:56 +00007142 D->setAccess(AS);
7143 CurContext->addDecl(D);
7144
7145 if (!LookupContext) return D;
7146 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00007147
John McCall77bb1aa2010-05-01 00:40:08 +00007148 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00007149 UD->setInvalidDecl();
7150 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007151 }
7152
Richard Smithc5a89a12012-04-02 01:30:27 +00007153 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007154 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00007155 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00007156 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007157 return UD;
7158 }
7159
7160 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00007161
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00007162 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00007163
John McCall604e7f12009-12-08 07:46:18 +00007164 // Unlike most lookups, we don't always want to hide tag
7165 // declarations: tag names are visible through the using declaration
7166 // even if hidden by ordinary names, *except* in a dependent context
7167 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00007168 if (!IsInstantiation)
7169 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00007170
John McCallb9abd8722012-04-07 03:04:20 +00007171 // For the purposes of this lookup, we have a base object type
7172 // equal to that of the current context.
7173 if (CurContext->isRecord()) {
7174 R.setBaseObjectType(
7175 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7176 }
7177
John McCalla24dc2e2009-11-17 02:14:36 +00007178 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00007179
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007180 // Try to correct typos if possible.
John McCallf36e02d2009-10-09 21:13:30 +00007181 if (R.empty()) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007182 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation);
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007183 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7184 R.getLookupKind(), S, &SS, CCC)){
7185 // We reject any correction for which ND would be NULL.
7186 NamedDecl *ND = Corrected.getCorrectionDecl();
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007187 R.setLookupName(Corrected.getCorrection());
7188 R.addDecl(ND);
Richard Smith2d670972013-08-17 00:46:16 +00007189 // We reject candidates where DroppedSpecifier == true, hence the
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007190 // literal '0' below.
Richard Smith2d670972013-08-17 00:46:16 +00007191 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7192 << NameInfo.getName() << LookupContext << 0
7193 << SS.getRange());
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007194 } else {
Richard Smith2d670972013-08-17 00:46:16 +00007195 Diag(IdentLoc, diag::err_no_member)
Kaelyn Uhrain0daf1f42013-07-10 17:34:22 +00007196 << NameInfo.getName() << LookupContext << SS.getRange();
7197 UD->setInvalidDecl();
7198 return UD;
7199 }
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007200 }
7201
John McCalled976492009-12-04 22:46:56 +00007202 if (R.isAmbiguous()) {
7203 UD->setInvalidDecl();
7204 return UD;
7205 }
Mike Stump1eb44332009-09-09 15:08:12 +00007206
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007207 if (HasTypenameKeyword) {
John McCall7ba107a2009-11-18 02:36:19 +00007208 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00007209 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007210 Diag(IdentLoc, diag::err_using_typename_non_type);
7211 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7212 Diag((*I)->getUnderlyingDecl()->getLocation(),
7213 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007214 UD->setInvalidDecl();
7215 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007216 }
7217 } else {
7218 // If we asked for a non-typename and we got a type, error out,
7219 // but only if this is an instantiation of an unresolved using
7220 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00007221 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00007222 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7223 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00007224 UD->setInvalidDecl();
7225 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00007226 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00007227 }
7228
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007229 // C++0x N2914 [namespace.udecl]p6:
7230 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00007231 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007232 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7233 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00007234 UD->setInvalidDecl();
7235 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00007236 }
Mike Stump1eb44332009-09-09 15:08:12 +00007237
John McCall9f54ad42009-12-10 09:41:52 +00007238 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7239 if (!CheckUsingShadowDecl(UD, *I, Previous))
7240 BuildUsingShadowDecl(S, UD, *I);
7241 }
John McCall9488ea12009-11-17 05:59:44 +00007242
7243 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00007244}
7245
Sebastian Redlf677ea32011-02-05 19:23:19 +00007246/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00007247bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007248 assert(!UD->hasTypename() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00007249
Douglas Gregordc355712011-02-25 00:36:19 +00007250 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007251 assert(SourceType &&
7252 "Using decl naming constructor doesn't have type in scope spec.");
7253 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7254
7255 // Check whether the named type is a direct base class.
7256 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7257 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7258 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7259 BaseIt != BaseE; ++BaseIt) {
7260 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7261 if (CanonicalSourceType == BaseType)
7262 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00007263 if (BaseIt->getType()->isDependentType())
7264 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007265 }
7266
7267 if (BaseIt == BaseE) {
7268 // Did not find SourceType in the bases.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007269 Diag(UD->getUsingLoc(),
Sebastian Redlf677ea32011-02-05 19:23:19 +00007270 diag::err_using_decl_constructor_not_in_direct_base)
7271 << UD->getNameInfo().getSourceRange()
7272 << QualType(SourceType, 0) << TargetClass;
7273 return true;
7274 }
7275
Richard Smithc5a89a12012-04-02 01:30:27 +00007276 if (!CurContext->isDependentContext())
7277 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007278
7279 return false;
7280}
7281
John McCall9f54ad42009-12-10 09:41:52 +00007282/// Checks that the given using declaration is not an invalid
7283/// redeclaration. Note that this is checking only for the using decl
7284/// itself, not for any ill-formedness among the UsingShadowDecls.
7285bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007286 bool HasTypenameKeyword,
John McCall9f54ad42009-12-10 09:41:52 +00007287 const CXXScopeSpec &SS,
7288 SourceLocation NameLoc,
7289 const LookupResult &Prev) {
7290 // C++03 [namespace.udecl]p8:
7291 // C++0x [namespace.udecl]p10:
7292 // A using-declaration is a declaration and can therefore be used
7293 // repeatedly where (and only where) multiple declarations are
7294 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00007295 //
John McCall8a726212010-11-29 18:01:58 +00007296 // That's in non-member contexts.
7297 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00007298 return false;
7299
7300 NestedNameSpecifier *Qual
7301 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7302
7303 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7304 NamedDecl *D = *I;
7305
7306 bool DTypename;
7307 NestedNameSpecifier *DQual;
7308 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007309 DTypename = UD->hasTypename();
Douglas Gregordc355712011-02-25 00:36:19 +00007310 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007311 } else if (UnresolvedUsingValueDecl *UD
7312 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7313 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00007314 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007315 } else if (UnresolvedUsingTypenameDecl *UD
7316 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7317 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00007318 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00007319 } else continue;
7320
7321 // using decls differ if one says 'typename' and the other doesn't.
7322 // FIXME: non-dependent using decls?
Enea Zaffanella8d030c72013-07-22 10:54:09 +00007323 if (HasTypenameKeyword != DTypename) continue;
John McCall9f54ad42009-12-10 09:41:52 +00007324
7325 // using decls differ if they name different scopes (but note that
7326 // template instantiation can cause this check to trigger when it
7327 // didn't before instantiation).
7328 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7329 Context.getCanonicalNestedNameSpecifier(DQual))
7330 continue;
7331
7332 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00007333 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00007334 return true;
7335 }
7336
7337 return false;
7338}
7339
John McCall604e7f12009-12-08 07:46:18 +00007340
John McCalled976492009-12-04 22:46:56 +00007341/// Checks that the given nested-name qualifier used in a using decl
7342/// in the current context is appropriately related to the current
7343/// scope. If an error is found, diagnoses it and returns true.
7344bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7345 const CXXScopeSpec &SS,
7346 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00007347 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00007348
John McCall604e7f12009-12-08 07:46:18 +00007349 if (!CurContext->isRecord()) {
7350 // C++03 [namespace.udecl]p3:
7351 // C++0x [namespace.udecl]p8:
7352 // A using-declaration for a class member shall be a member-declaration.
7353
7354 // If we weren't able to compute a valid scope, it must be a
7355 // dependent class scope.
7356 if (!NamedContext || NamedContext->isRecord()) {
7357 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7358 << SS.getRange();
7359 return true;
7360 }
7361
7362 // Otherwise, everything is known to be fine.
7363 return false;
7364 }
7365
7366 // The current scope is a record.
7367
7368 // If the named context is dependent, we can't decide much.
7369 if (!NamedContext) {
7370 // FIXME: in C++0x, we can diagnose if we can prove that the
7371 // nested-name-specifier does not refer to a base class, which is
7372 // still possible in some cases.
7373
7374 // Otherwise we have to conservatively report that things might be
7375 // okay.
7376 return false;
7377 }
7378
7379 if (!NamedContext->isRecord()) {
7380 // Ideally this would point at the last name in the specifier,
7381 // but we don't have that level of source info.
7382 Diag(SS.getRange().getBegin(),
7383 diag::err_using_decl_nested_name_specifier_is_not_class)
7384 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7385 return true;
7386 }
7387
Douglas Gregor6fb07292010-12-21 07:41:49 +00007388 if (!NamedContext->isDependentContext() &&
7389 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7390 return true;
7391
Richard Smith80ad52f2013-01-02 11:42:31 +00007392 if (getLangOpts().CPlusPlus11) {
John McCall604e7f12009-12-08 07:46:18 +00007393 // C++0x [namespace.udecl]p3:
7394 // In a using-declaration used as a member-declaration, the
7395 // nested-name-specifier shall name a base class of the class
7396 // being defined.
7397
7398 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7399 cast<CXXRecordDecl>(NamedContext))) {
7400 if (CurContext == NamedContext) {
7401 Diag(NameLoc,
7402 diag::err_using_decl_nested_name_specifier_is_current_class)
7403 << SS.getRange();
7404 return true;
7405 }
7406
7407 Diag(SS.getRange().getBegin(),
7408 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7409 << (NestedNameSpecifier*) SS.getScopeRep()
7410 << cast<CXXRecordDecl>(CurContext)
7411 << SS.getRange();
7412 return true;
7413 }
7414
7415 return false;
7416 }
7417
7418 // C++03 [namespace.udecl]p4:
7419 // A using-declaration used as a member-declaration shall refer
7420 // to a member of a base class of the class being defined [etc.].
7421
7422 // Salient point: SS doesn't have to name a base class as long as
7423 // lookup only finds members from base classes. Therefore we can
7424 // diagnose here only if we can prove that that can't happen,
7425 // i.e. if the class hierarchies provably don't intersect.
7426
7427 // TODO: it would be nice if "definitely valid" results were cached
7428 // in the UsingDecl and UsingShadowDecl so that these checks didn't
7429 // need to be repeated.
7430
7431 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00007432 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00007433
7434 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7435 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7436 Data->Bases.insert(Base);
7437 return true;
7438 }
7439
7440 bool hasDependentBases(const CXXRecordDecl *Class) {
7441 return !Class->forallBases(collect, this);
7442 }
7443
7444 /// Returns true if the base is dependent or is one of the
7445 /// accumulated base classes.
7446 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7447 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7448 return !Data->Bases.count(Base);
7449 }
7450
7451 bool mightShareBases(const CXXRecordDecl *Class) {
7452 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7453 }
7454 };
7455
7456 UserData Data;
7457
7458 // Returns false if we find a dependent base.
7459 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7460 return false;
7461
7462 // Returns false if the class has a dependent base or if it or one
7463 // of its bases is present in the base set of the current context.
7464 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7465 return false;
7466
7467 Diag(SS.getRange().getBegin(),
7468 diag::err_using_decl_nested_name_specifier_is_not_base_class)
7469 << (NestedNameSpecifier*) SS.getScopeRep()
7470 << cast<CXXRecordDecl>(CurContext)
7471 << SS.getRange();
7472
7473 return true;
John McCalled976492009-12-04 22:46:56 +00007474}
7475
Richard Smith162e1c12011-04-15 14:24:37 +00007476Decl *Sema::ActOnAliasDeclaration(Scope *S,
7477 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007478 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00007479 SourceLocation UsingLoc,
7480 UnqualifiedId &Name,
Richard Smith6b3d3e52013-02-20 19:22:51 +00007481 AttributeList *AttrList,
Richard Smith162e1c12011-04-15 14:24:37 +00007482 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00007483 // Skip up to the relevant declaration scope.
7484 while (S->getFlags() & Scope::TemplateParamScope)
7485 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00007486 assert((S->getFlags() & Scope::DeclScope) &&
7487 "got alias-declaration outside of declaration scope");
7488
7489 if (Type.isInvalid())
7490 return 0;
7491
7492 bool Invalid = false;
7493 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7494 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00007495 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00007496
7497 if (DiagnoseClassNameShadow(CurContext, NameInfo))
7498 return 0;
7499
7500 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00007501 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00007502 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007503 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7504 TInfo->getTypeLoc().getBeginLoc());
7505 }
Richard Smith162e1c12011-04-15 14:24:37 +00007506
7507 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7508 LookupName(Previous, S);
7509
7510 // Warn about shadowing the name of a template parameter.
7511 if (Previous.isSingleResult() &&
7512 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00007513 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00007514 Previous.clear();
7515 }
7516
7517 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7518 "name in alias declaration must be an identifier");
7519 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7520 Name.StartLocation,
7521 Name.Identifier, TInfo);
7522
7523 NewTD->setAccess(AS);
7524
7525 if (Invalid)
7526 NewTD->setInvalidDecl();
7527
Richard Smith6b3d3e52013-02-20 19:22:51 +00007528 ProcessDeclAttributeList(S, NewTD, AttrList);
7529
Richard Smith3e4c6c42011-05-05 21:57:07 +00007530 CheckTypedefForVariablyModifiedType(S, NewTD);
7531 Invalid |= NewTD->isInvalidDecl();
7532
Richard Smith162e1c12011-04-15 14:24:37 +00007533 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00007534
7535 NamedDecl *NewND;
7536 if (TemplateParamLists.size()) {
7537 TypeAliasTemplateDecl *OldDecl = 0;
7538 TemplateParameterList *OldTemplateParams = 0;
7539
7540 if (TemplateParamLists.size() != 1) {
7541 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007542 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7543 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00007544 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007545 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00007546
7547 // Only consider previous declarations in the same scope.
7548 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7549 /*ExplicitInstantiationOrSpecialization*/false);
7550 if (!Previous.empty()) {
7551 Redeclaration = true;
7552
7553 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7554 if (!OldDecl && !Invalid) {
7555 Diag(UsingLoc, diag::err_redefinition_different_kind)
7556 << Name.Identifier;
7557
7558 NamedDecl *OldD = Previous.getRepresentativeDecl();
7559 if (OldD->getLocation().isValid())
7560 Diag(OldD->getLocation(), diag::note_previous_definition);
7561
7562 Invalid = true;
7563 }
7564
7565 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7566 if (TemplateParameterListsAreEqual(TemplateParams,
7567 OldDecl->getTemplateParameters(),
7568 /*Complain=*/true,
7569 TPL_TemplateMatch))
7570 OldTemplateParams = OldDecl->getTemplateParameters();
7571 else
7572 Invalid = true;
7573
7574 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7575 if (!Invalid &&
7576 !Context.hasSameType(OldTD->getUnderlyingType(),
7577 NewTD->getUnderlyingType())) {
7578 // FIXME: The C++0x standard does not clearly say this is ill-formed,
7579 // but we can't reasonably accept it.
7580 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7581 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7582 if (OldTD->getLocation().isValid())
7583 Diag(OldTD->getLocation(), diag::note_previous_definition);
7584 Invalid = true;
7585 }
7586 }
7587 }
7588
7589 // Merge any previous default template arguments into our parameters,
7590 // and check the parameter list.
7591 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7592 TPC_TypeAliasTemplate))
7593 return 0;
7594
7595 TypeAliasTemplateDecl *NewDecl =
7596 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7597 Name.Identifier, TemplateParams,
7598 NewTD);
7599
7600 NewDecl->setAccess(AS);
7601
7602 if (Invalid)
7603 NewDecl->setInvalidDecl();
7604 else if (OldDecl)
7605 NewDecl->setPreviousDeclaration(OldDecl);
7606
7607 NewND = NewDecl;
7608 } else {
7609 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7610 NewND = NewTD;
7611 }
Richard Smith162e1c12011-04-15 14:24:37 +00007612
7613 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00007614 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00007615
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00007616 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00007617 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00007618}
7619
John McCalld226f652010-08-21 09:40:31 +00007620Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007621 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00007622 SourceLocation AliasLoc,
7623 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00007624 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00007625 SourceLocation IdentLoc,
7626 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00007627
Anders Carlsson81c85c42009-03-28 23:53:49 +00007628 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00007629 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7630 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00007631
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007632 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00007633 NamedDecl *PrevDecl
7634 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7635 ForRedeclaration);
7636 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7637 PrevDecl = 0;
7638
7639 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00007640 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007641 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00007642 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00007643 // FIXME: At some point, we'll want to create the (redundant)
7644 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00007645 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00007646 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00007647 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00007648 }
Mike Stump1eb44332009-09-09 15:08:12 +00007649
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007650 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7651 diag::err_redefinition_different_kind;
7652 Diag(AliasLoc, DiagID) << Alias;
7653 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00007654 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00007655 }
7656
John McCalla24dc2e2009-11-17 02:14:36 +00007657 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00007658 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00007659
John McCallf36e02d2009-10-09 21:13:30 +00007660 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00007661 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00007662 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00007663 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00007664 }
Anders Carlsson5721c682009-03-28 06:42:02 +00007665 }
Mike Stump1eb44332009-09-09 15:08:12 +00007666
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007667 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00007668 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00007669 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00007670 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00007671
John McCall3dbd3d52010-02-16 06:53:13 +00007672 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00007673 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00007674}
7675
Sean Hunt001cad92011-05-10 00:49:42 +00007676Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007677Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7678 CXXMethodDecl *MD) {
7679 CXXRecordDecl *ClassDecl = MD->getParent();
7680
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007681 // C++ [except.spec]p14:
7682 // An implicitly declared special member function (Clause 12) shall have an
7683 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00007684 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007685 if (ClassDecl->isInvalidDecl())
7686 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007687
Sebastian Redl60618fa2011-03-12 11:50:43 +00007688 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007689 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7690 BEnd = ClassDecl->bases_end();
7691 B != BEnd; ++B) {
7692 if (B->isVirtual()) // Handled below.
7693 continue;
7694
Douglas Gregor18274032010-07-03 00:47:00 +00007695 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7696 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007697 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7698 // If this is a deleted function, add it anyway. This might be conformant
7699 // with the standard. This might not. I'm not sure. It might not matter.
7700 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007701 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007702 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007703 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007704
7705 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007706 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7707 BEnd = ClassDecl->vbases_end();
7708 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007709 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7710 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007711 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7712 // If this is a deleted function, add it anyway. This might be conformant
7713 // with the standard. This might not. I'm not sure. It might not matter.
7714 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007715 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007716 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007717 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007718
7719 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007720 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7721 FEnd = ClassDecl->field_end();
7722 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007723 if (F->hasInClassInitializer()) {
7724 if (Expr *E = F->getInClassInitializer())
7725 ExceptSpec.CalledExpr(E);
7726 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007727 // DR1351:
7728 // If the brace-or-equal-initializer of a non-static data member
7729 // invokes a defaulted default constructor of its class or of an
7730 // enclosing class in a potentially evaluated subexpression, the
7731 // program is ill-formed.
7732 //
7733 // This resolution is unworkable: the exception specification of the
7734 // default constructor can be needed in an unevaluated context, in
7735 // particular, in the operand of a noexcept-expression, and we can be
7736 // unable to compute an exception specification for an enclosed class.
7737 //
7738 // We do not allow an in-class initializer to require the evaluation
7739 // of the exception specification for any in-class initializer whose
7740 // definition is not lexically complete.
7741 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00007742 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007743 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007744 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7745 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7746 // If this is a deleted function, add it anyway. This might be conformant
7747 // with the standard. This might not. I'm not sure. It might not matter.
7748 // In particular, the problem is that this function never gets called. It
7749 // might just be ill-formed because this function attempts to refer to
7750 // a deleted function here.
7751 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00007752 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007753 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007754 }
John McCalle23cf432010-12-14 08:05:40 +00007755
Sean Hunt001cad92011-05-10 00:49:42 +00007756 return ExceptSpec;
7757}
7758
Richard Smith07b0fdc2013-03-18 21:12:30 +00007759Sema::ImplicitExceptionSpecification
Richard Smith0b0ca472013-04-10 06:11:48 +00007760Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7761 CXXRecordDecl *ClassDecl = CD->getParent();
7762
7763 // C++ [except.spec]p14:
7764 // An inheriting constructor [...] shall have an exception-specification. [...]
Richard Smith07b0fdc2013-03-18 21:12:30 +00007765 ImplicitExceptionSpecification ExceptSpec(*this);
Richard Smith0b0ca472013-04-10 06:11:48 +00007766 if (ClassDecl->isInvalidDecl())
7767 return ExceptSpec;
7768
7769 // Inherited constructor.
7770 const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7771 const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7772 // FIXME: Copying or moving the parameters could add extra exceptions to the
7773 // set, as could the default arguments for the inherited constructor. This
7774 // will be addressed when we implement the resolution of core issue 1351.
7775 ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7776
7777 // Direct base-class constructors.
7778 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7779 BEnd = ClassDecl->bases_end();
7780 B != BEnd; ++B) {
7781 if (B->isVirtual()) // Handled below.
7782 continue;
7783
7784 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7785 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7786 if (BaseClassDecl == InheritedDecl)
7787 continue;
7788 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7789 if (Constructor)
7790 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7791 }
7792 }
7793
7794 // Virtual base-class constructors.
7795 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7796 BEnd = ClassDecl->vbases_end();
7797 B != BEnd; ++B) {
7798 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7799 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7800 if (BaseClassDecl == InheritedDecl)
7801 continue;
7802 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7803 if (Constructor)
7804 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7805 }
7806 }
7807
7808 // Field constructors.
7809 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7810 FEnd = ClassDecl->field_end();
7811 F != FEnd; ++F) {
7812 if (F->hasInClassInitializer()) {
7813 if (Expr *E = F->getInClassInitializer())
7814 ExceptSpec.CalledExpr(E);
7815 else if (!F->isInvalidDecl())
7816 Diag(CD->getLocation(),
7817 diag::err_in_class_initializer_references_def_ctor) << CD;
7818 } else if (const RecordType *RecordTy
7819 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7820 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7821 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7822 if (Constructor)
7823 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7824 }
7825 }
7826
Richard Smith07b0fdc2013-03-18 21:12:30 +00007827 return ExceptSpec;
7828}
7829
Richard Smithafb49182012-11-29 01:34:07 +00007830namespace {
7831/// RAII object to register a special member as being currently declared.
7832struct DeclaringSpecialMember {
7833 Sema &S;
7834 Sema::SpecialMemberDecl D;
7835 bool WasAlreadyBeingDeclared;
7836
7837 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7838 : S(S), D(RD, CSM) {
7839 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7840 if (WasAlreadyBeingDeclared)
7841 // This almost never happens, but if it does, ensure that our cache
7842 // doesn't contain a stale result.
7843 S.SpecialMemberCache.clear();
7844
7845 // FIXME: Register a note to be produced if we encounter an error while
7846 // declaring the special member.
7847 }
7848 ~DeclaringSpecialMember() {
7849 if (!WasAlreadyBeingDeclared)
7850 S.SpecialMembersBeingDeclared.erase(D);
7851 }
7852
7853 /// \brief Are we already trying to declare this special member?
7854 bool isAlreadyBeingDeclared() const {
7855 return WasAlreadyBeingDeclared;
7856 }
7857};
7858}
7859
Sean Hunt001cad92011-05-10 00:49:42 +00007860CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7861 CXXRecordDecl *ClassDecl) {
7862 // C++ [class.ctor]p5:
7863 // A default constructor for a class X is a constructor of class X
7864 // that can be called without an argument. If there is no
7865 // user-declared constructor for class X, a default constructor is
7866 // implicitly declared. An implicitly-declared default constructor
7867 // is an inline public member of its class.
Richard Smithd0adeb62012-11-27 21:20:31 +00007868 assert(ClassDecl->needsImplicitDefaultConstructor() &&
Sean Hunt001cad92011-05-10 00:49:42 +00007869 "Should not build implicit default constructor!");
7870
Richard Smithafb49182012-11-29 01:34:07 +00007871 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7872 if (DSM.isAlreadyBeingDeclared())
7873 return 0;
7874
Richard Smith7756afa2012-06-10 05:43:50 +00007875 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7876 CXXDefaultConstructor,
7877 false);
7878
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007879 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007880 CanQualType ClassType
7881 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007882 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007883 DeclarationName Name
7884 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007885 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007886 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00007887 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00007888 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00007889 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007890 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007891 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007892 DefaultCon->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00007893
7894 // Build an exception specification pointing back at this constructor.
7895 FunctionProtoType::ExtProtoInfo EPI;
7896 EPI.ExceptionSpecType = EST_Unevaluated;
7897 EPI.ExceptionSpecDecl = DefaultCon;
Dmitri Gribenko55431692013-05-05 00:41:58 +00007898 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00007899
Richard Smithbc2a35d2012-12-08 08:32:28 +00007900 // We don't need to use SpecialMemberIsTrivial here; triviality for default
7901 // constructors is easy to compute.
7902 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7903
7904 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00007905 SetDeclDeleted(DefaultCon, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00007906
Douglas Gregor18274032010-07-03 00:47:00 +00007907 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007908 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
Richard Smithbc2a35d2012-12-08 08:32:28 +00007909
Douglas Gregor23c94db2010-07-02 17:43:08 +00007910 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007911 PushOnScopeChains(DefaultCon, S, false);
7912 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007913
Douglas Gregor32df23e2010-07-01 22:02:46 +00007914 return DefaultCon;
7915}
7916
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007917void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7918 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007919 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007920 !Constructor->doesThisDeclarationHaveABody() &&
7921 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007922 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007923
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007924 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007925 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007926
Eli Friedman9a14db32012-10-18 20:14:08 +00007927 SynthesizedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007928 DiagnosticErrorTrap Trap(Diags);
David Blaikie93c86172013-01-17 05:26:25 +00007929 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007930 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007931 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007932 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007933 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007934 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007935 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007936
7937 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007938 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007939
7940 Constructor->setUsed();
7941 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007942
7943 if (ASTMutationListener *L = getASTMutationListener()) {
7944 L->CompletedImplicitDefinition(Constructor);
7945 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007946}
7947
Richard Smith7a614d82011-06-11 17:19:42 +00007948void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
Richard Smith1d28caf2012-12-11 01:14:52 +00007949 // Check that any explicitly-defaulted methods have exception specifications
7950 // compatible with their implicit exception specifications.
7951 CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
Richard Smith7a614d82011-06-11 17:19:42 +00007952}
7953
Richard Smith4841ca52013-04-10 05:48:59 +00007954namespace {
7955/// Information on inheriting constructors to declare.
7956class InheritingConstructorInfo {
7957public:
7958 InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7959 : SemaRef(SemaRef), Derived(Derived) {
7960 // Mark the constructors that we already have in the derived class.
7961 //
7962 // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7963 // unless there is a user-declared constructor with the same signature in
7964 // the class where the using-declaration appears.
7965 visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7966 }
7967
7968 void inheritAll(CXXRecordDecl *RD) {
7969 visitAll(RD, &InheritingConstructorInfo::inherit);
7970 }
7971
7972private:
7973 /// Information about an inheriting constructor.
7974 struct InheritingConstructor {
7975 InheritingConstructor()
7976 : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7977
7978 /// If \c true, a constructor with this signature is already declared
7979 /// in the derived class.
7980 bool DeclaredInDerived;
7981
7982 /// The constructor which is inherited.
7983 const CXXConstructorDecl *BaseCtor;
7984
7985 /// The derived constructor we declared.
7986 CXXConstructorDecl *DerivedCtor;
7987 };
7988
7989 /// Inheriting constructors with a given canonical type. There can be at
7990 /// most one such non-template constructor, and any number of templated
7991 /// constructors.
7992 struct InheritingConstructorsForType {
7993 InheritingConstructor NonTemplate;
Robert Wilhelme7205c02013-08-10 12:33:24 +00007994 SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
7995 Templates;
Richard Smith4841ca52013-04-10 05:48:59 +00007996
7997 InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7998 if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7999 TemplateParameterList *ParamList = FTD->getTemplateParameters();
8000 for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8001 if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8002 false, S.TPL_TemplateMatch))
8003 return Templates[I].second;
8004 Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8005 return Templates.back().second;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008006 }
Richard Smith4841ca52013-04-10 05:48:59 +00008007
8008 return NonTemplate;
8009 }
8010 };
8011
8012 /// Get or create the inheriting constructor record for a constructor.
8013 InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8014 QualType CtorType) {
8015 return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8016 .getEntry(SemaRef, Ctor);
8017 }
8018
8019 typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8020
8021 /// Process all constructors for a class.
8022 void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8023 for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8024 CtorE = RD->ctor_end();
8025 CtorIt != CtorE; ++CtorIt)
8026 (this->*Callback)(*CtorIt);
8027 for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8028 I(RD->decls_begin()), E(RD->decls_end());
8029 I != E; ++I) {
8030 const FunctionDecl *FD = (*I)->getTemplatedDecl();
8031 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8032 (this->*Callback)(CD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008033 }
8034 }
Richard Smith4841ca52013-04-10 05:48:59 +00008035
8036 /// Note that a constructor (or constructor template) was declared in Derived.
8037 void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8038 getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8039 }
8040
8041 /// Inherit a single constructor.
8042 void inherit(const CXXConstructorDecl *Ctor) {
8043 const FunctionProtoType *CtorType =
8044 Ctor->getType()->castAs<FunctionProtoType>();
8045 ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8046 FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8047
8048 SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8049
8050 // Core issue (no number yet): the ellipsis is always discarded.
8051 if (EPI.Variadic) {
8052 SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8053 SemaRef.Diag(Ctor->getLocation(),
8054 diag::note_using_decl_constructor_ellipsis);
8055 EPI.Variadic = false;
8056 }
8057
8058 // Declare a constructor for each number of parameters.
8059 //
8060 // C++11 [class.inhctor]p1:
8061 // The candidate set of inherited constructors from the class X named in
8062 // the using-declaration consists of [... modulo defects ...] for each
8063 // constructor or constructor template of X, the set of constructors or
8064 // constructor templates that results from omitting any ellipsis parameter
8065 // specification and successively omitting parameters with a default
8066 // argument from the end of the parameter-type-list
Richard Smith987c0302013-04-17 19:00:52 +00008067 unsigned MinParams = minParamsToInherit(Ctor);
8068 unsigned Params = Ctor->getNumParams();
8069 if (Params >= MinParams) {
8070 do
8071 declareCtor(UsingLoc, Ctor,
8072 SemaRef.Context.getFunctionType(
8073 Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8074 while (Params > MinParams &&
8075 Ctor->getParamDecl(--Params)->hasDefaultArg());
8076 }
Richard Smith4841ca52013-04-10 05:48:59 +00008077 }
8078
8079 /// Find the using-declaration which specified that we should inherit the
8080 /// constructors of \p Base.
8081 SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8082 // No fancy lookup required; just look for the base constructor name
8083 // directly within the derived class.
8084 ASTContext &Context = SemaRef.Context;
8085 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8086 Context.getCanonicalType(Context.getRecordType(Base)));
8087 DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8088 return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8089 }
8090
8091 unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8092 // C++11 [class.inhctor]p3:
8093 // [F]or each constructor template in the candidate set of inherited
8094 // constructors, a constructor template is implicitly declared
8095 if (Ctor->getDescribedFunctionTemplate())
8096 return 0;
8097
8098 // For each non-template constructor in the candidate set of inherited
8099 // constructors other than a constructor having no parameters or a
8100 // copy/move constructor having a single parameter, a constructor is
8101 // implicitly declared [...]
8102 if (Ctor->getNumParams() == 0)
8103 return 1;
8104 if (Ctor->isCopyOrMoveConstructor())
8105 return 2;
8106
8107 // Per discussion on core reflector, never inherit a constructor which
8108 // would become a default, copy, or move constructor of Derived either.
8109 const ParmVarDecl *PD = Ctor->getParamDecl(0);
8110 const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8111 return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8112 }
8113
8114 /// Declare a single inheriting constructor, inheriting the specified
8115 /// constructor, with the given type.
8116 void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8117 QualType DerivedType) {
8118 InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8119
8120 // C++11 [class.inhctor]p3:
8121 // ... a constructor is implicitly declared with the same constructor
8122 // characteristics unless there is a user-declared constructor with
8123 // the same signature in the class where the using-declaration appears
8124 if (Entry.DeclaredInDerived)
8125 return;
8126
8127 // C++11 [class.inhctor]p7:
8128 // If two using-declarations declare inheriting constructors with the
8129 // same signature, the program is ill-formed
8130 if (Entry.DerivedCtor) {
8131 if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8132 // Only diagnose this once per constructor.
8133 if (Entry.DerivedCtor->isInvalidDecl())
8134 return;
8135 Entry.DerivedCtor->setInvalidDecl();
8136
8137 SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8138 SemaRef.Diag(BaseCtor->getLocation(),
8139 diag::note_using_decl_constructor_conflict_current_ctor);
8140 SemaRef.Diag(Entry.BaseCtor->getLocation(),
8141 diag::note_using_decl_constructor_conflict_previous_ctor);
8142 SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8143 diag::note_using_decl_constructor_conflict_previous_using);
8144 } else {
8145 // Core issue (no number): if the same inheriting constructor is
8146 // produced by multiple base class constructors from the same base
8147 // class, the inheriting constructor is defined as deleted.
8148 SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8149 }
8150
8151 return;
8152 }
8153
8154 ASTContext &Context = SemaRef.Context;
8155 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8156 Context.getCanonicalType(Context.getRecordType(Derived)));
8157 DeclarationNameInfo NameInfo(Name, UsingLoc);
8158
8159 TemplateParameterList *TemplateParams = 0;
8160 if (const FunctionTemplateDecl *FTD =
8161 BaseCtor->getDescribedFunctionTemplate()) {
8162 TemplateParams = FTD->getTemplateParameters();
8163 // We're reusing template parameters from a different DeclContext. This
8164 // is questionable at best, but works out because the template depth in
8165 // both places is guaranteed to be 0.
8166 // FIXME: Rebuild the template parameters in the new context, and
8167 // transform the function type to refer to them.
8168 }
8169
8170 // Build type source info pointing at the using-declaration. This is
8171 // required by template instantiation.
8172 TypeSourceInfo *TInfo =
8173 Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8174 FunctionProtoTypeLoc ProtoLoc =
8175 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8176
8177 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8178 Context, Derived, UsingLoc, NameInfo, DerivedType,
8179 TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8180 /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8181
8182 // Build an unevaluated exception specification for this constructor.
8183 const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8184 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8185 EPI.ExceptionSpecType = EST_Unevaluated;
8186 EPI.ExceptionSpecDecl = DerivedCtor;
8187 DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8188 FPT->getArgTypes(), EPI));
8189
8190 // Build the parameter declarations.
8191 SmallVector<ParmVarDecl *, 16> ParamDecls;
8192 for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8193 TypeSourceInfo *TInfo =
8194 Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8195 ParmVarDecl *PD = ParmVarDecl::Create(
8196 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8197 FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8198 PD->setScopeInfo(0, I);
8199 PD->setImplicit();
8200 ParamDecls.push_back(PD);
8201 ProtoLoc.setArg(I, PD);
8202 }
8203
8204 // Set up the new constructor.
8205 DerivedCtor->setAccess(BaseCtor->getAccess());
8206 DerivedCtor->setParams(ParamDecls);
8207 DerivedCtor->setInheritedConstructor(BaseCtor);
8208 if (BaseCtor->isDeleted())
8209 SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8210
8211 // If this is a constructor template, build the template declaration.
8212 if (TemplateParams) {
8213 FunctionTemplateDecl *DerivedTemplate =
8214 FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8215 TemplateParams, DerivedCtor);
8216 DerivedTemplate->setAccess(BaseCtor->getAccess());
8217 DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8218 Derived->addDecl(DerivedTemplate);
8219 } else {
8220 Derived->addDecl(DerivedCtor);
8221 }
8222
8223 Entry.BaseCtor = BaseCtor;
8224 Entry.DerivedCtor = DerivedCtor;
8225 }
8226
8227 Sema &SemaRef;
8228 CXXRecordDecl *Derived;
8229 typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8230 MapType Map;
8231};
8232}
8233
8234void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8235 // Defer declaring the inheriting constructors until the class is
8236 // instantiated.
8237 if (ClassDecl->isDependentContext())
Sebastian Redlf677ea32011-02-05 19:23:19 +00008238 return;
8239
Richard Smith4841ca52013-04-10 05:48:59 +00008240 // Find base classes from which we might inherit constructors.
8241 SmallVector<CXXRecordDecl*, 4> InheritedBases;
8242 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8243 BaseE = ClassDecl->bases_end();
8244 BaseIt != BaseE; ++BaseIt)
8245 if (BaseIt->getInheritConstructors())
8246 InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
Richard Smith07b0fdc2013-03-18 21:12:30 +00008247
Richard Smith4841ca52013-04-10 05:48:59 +00008248 // Go no further if we're not inheriting any constructors.
8249 if (InheritedBases.empty())
8250 return;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008251
Richard Smith4841ca52013-04-10 05:48:59 +00008252 // Declare the inherited constructors.
8253 InheritingConstructorInfo ICI(*this, ClassDecl);
8254 for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8255 ICI.inheritAll(InheritedBases[I]);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008256}
8257
Richard Smith07b0fdc2013-03-18 21:12:30 +00008258void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8259 CXXConstructorDecl *Constructor) {
8260 CXXRecordDecl *ClassDecl = Constructor->getParent();
8261 assert(Constructor->getInheritedConstructor() &&
8262 !Constructor->doesThisDeclarationHaveABody() &&
8263 !Constructor->isDeleted());
8264
8265 SynthesizedFunctionScope Scope(*this, Constructor);
8266 DiagnosticErrorTrap Trap(Diags);
8267 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8268 Trap.hasErrorOccurred()) {
8269 Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8270 << Context.getTagDeclType(ClassDecl);
8271 Constructor->setInvalidDecl();
8272 return;
8273 }
8274
8275 SourceLocation Loc = Constructor->getLocation();
8276 Constructor->setBody(new (Context) CompoundStmt(Loc));
8277
8278 Constructor->setUsed();
8279 MarkVTableUsed(CurrentLocation, ClassDecl);
8280
8281 if (ASTMutationListener *L = getASTMutationListener()) {
8282 L->CompletedImplicitDefinition(Constructor);
8283 }
8284}
8285
8286
Sean Huntcb45a0f2011-05-12 22:46:25 +00008287Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008288Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8289 CXXRecordDecl *ClassDecl = MD->getParent();
8290
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008291 // C++ [except.spec]p14:
8292 // An implicitly declared special member function (Clause 12) shall have
8293 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00008294 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008295 if (ClassDecl->isInvalidDecl())
8296 return ExceptSpec;
8297
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008298 // Direct base-class destructors.
8299 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8300 BEnd = ClassDecl->bases_end();
8301 B != BEnd; ++B) {
8302 if (B->isVirtual()) // Handled below.
8303 continue;
8304
8305 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008306 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008307 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008308 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008309
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008310 // Virtual base-class destructors.
8311 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8312 BEnd = ClassDecl->vbases_end();
8313 B != BEnd; ++B) {
8314 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008315 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008316 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008317 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00008318
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008319 // Field destructors.
8320 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8321 FEnd = ClassDecl->field_end();
8322 F != FEnd; ++F) {
8323 if (const RecordType *RecordTy
8324 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00008325 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00008326 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008327 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008328
Sean Huntcb45a0f2011-05-12 22:46:25 +00008329 return ExceptSpec;
8330}
8331
8332CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8333 // C++ [class.dtor]p2:
8334 // If a class has no user-declared destructor, a destructor is
8335 // declared implicitly. An implicitly-declared destructor is an
8336 // inline public member of its class.
Richard Smithe5411b72012-12-01 02:35:44 +00008337 assert(ClassDecl->needsImplicitDestructor());
Sean Huntcb45a0f2011-05-12 22:46:25 +00008338
Richard Smithafb49182012-11-29 01:34:07 +00008339 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8340 if (DSM.isAlreadyBeingDeclared())
8341 return 0;
8342
Douglas Gregor4923aa22010-07-02 20:37:36 +00008343 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008344 CanQualType ClassType
8345 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008346 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008347 DeclarationName Name
8348 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008349 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008350 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00008351 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8352 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00008353 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008354 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008355 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008356 Destructor->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008357
8358 // Build an exception specification pointing back at this destructor.
8359 FunctionProtoType::ExtProtoInfo EPI;
8360 EPI.ExceptionSpecType = EST_Unevaluated;
8361 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008362 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008363
Richard Smithbc2a35d2012-12-08 08:32:28 +00008364 AddOverriddenMethods(ClassDecl, Destructor);
8365
8366 // We don't need to use SpecialMemberIsTrivial here; triviality for
8367 // destructors is easy to compute.
8368 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8369
8370 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008371 SetDeclDeleted(Destructor, ClassLoc);
Richard Smithbc2a35d2012-12-08 08:32:28 +00008372
Douglas Gregor4923aa22010-07-02 20:37:36 +00008373 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00008374 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00008375
Douglas Gregor4923aa22010-07-02 20:37:36 +00008376 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00008377 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00008378 PushOnScopeChains(Destructor, S, false);
8379 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00008380
Douglas Gregorfabd43a2010-07-01 19:09:28 +00008381 return Destructor;
8382}
8383
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008384void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00008385 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00008386 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00008387 !Destructor->doesThisDeclarationHaveABody() &&
8388 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008389 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00008390 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008391 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008392
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008393 if (Destructor->isInvalidDecl())
8394 return;
8395
Eli Friedman9a14db32012-10-18 20:14:08 +00008396 SynthesizedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008397
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008398 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00008399 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8400 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00008401
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008402 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00008403 Diag(CurrentLocation, diag::note_member_synthesized_at)
8404 << CXXDestructor << Context.getTagDeclType(ClassDecl);
8405
8406 Destructor->setInvalidDecl();
8407 return;
8408 }
8409
Douglas Gregor4ada9d32010-09-20 16:48:21 +00008410 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008411 Destructor->setBody(new (Context) CompoundStmt(Loc));
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008412 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00008413 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008414
8415 if (ASTMutationListener *L = getASTMutationListener()) {
8416 L->CompletedImplicitDefinition(Destructor);
8417 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00008418}
8419
Richard Smitha4156b82012-04-21 18:42:51 +00008420/// \brief Perform any semantic analysis which needs to be delayed until all
8421/// pending class member declarations have been parsed.
8422void Sema::ActOnFinishCXXMemberDecls() {
Douglas Gregor10318842013-02-01 04:49:10 +00008423 // If the context is an invalid C++ class, just suppress these checks.
8424 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8425 if (Record->isInvalidDecl()) {
8426 DelayedDestructorExceptionSpecChecks.clear();
8427 return;
8428 }
8429 }
8430
Richard Smitha4156b82012-04-21 18:42:51 +00008431 // Perform any deferred checking of exception specifications for virtual
8432 // destructors.
8433 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8434 i != e; ++i) {
8435 const CXXDestructorDecl *Dtor =
8436 DelayedDestructorExceptionSpecChecks[i].first;
8437 assert(!Dtor->getParent()->isDependentType() &&
8438 "Should not ever add destructors of templates into the list.");
8439 CheckOverridingFunctionExceptionSpec(Dtor,
8440 DelayedDestructorExceptionSpecChecks[i].second);
8441 }
8442 DelayedDestructorExceptionSpecChecks.clear();
8443}
8444
Richard Smithb9d0b762012-07-27 04:22:15 +00008445void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8446 CXXDestructorDecl *Destructor) {
Richard Smith80ad52f2013-01-02 11:42:31 +00008447 assert(getLangOpts().CPlusPlus11 &&
Richard Smithb9d0b762012-07-27 04:22:15 +00008448 "adjusting dtor exception specs was introduced in c++11");
8449
Sebastian Redl0ee33912011-05-19 05:13:44 +00008450 // C++11 [class.dtor]p3:
8451 // A declaration of a destructor that does not have an exception-
8452 // specification is implicitly considered to have the same exception-
8453 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00008454 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00008455 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00008456 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00008457 return;
8458
Chandler Carruth3f224b22011-09-20 04:55:26 +00008459 // Replace the destructor's type, building off the existing one. Fortunately,
8460 // the only thing of interest in the destructor type is its extended info.
8461 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00008462 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8463 EPI.ExceptionSpecType = EST_Unevaluated;
8464 EPI.ExceptionSpecDecl = Destructor;
Dmitri Gribenko55431692013-05-05 00:41:58 +00008465 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00008466
Sebastian Redl0ee33912011-05-19 05:13:44 +00008467 // FIXME: If the destructor has a body that could throw, and the newly created
8468 // spec doesn't allow exceptions, we should emit a warning, because this
8469 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00008470 // However, we don't have a body or an exception specification yet, so it
8471 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00008472}
8473
Richard Smith8c889532012-11-14 00:50:40 +00008474/// When generating a defaulted copy or move assignment operator, if a field
8475/// should be copied with __builtin_memcpy rather than via explicit assignments,
8476/// do so. This optimization only applies for arrays of scalars, and for arrays
8477/// of class type where the selected copy/move-assignment operator is trivial.
8478static StmtResult
8479buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8480 Expr *To, Expr *From) {
8481 // Compute the size of the memory buffer to be copied.
8482 QualType SizeType = S.Context.getSizeType();
8483 llvm::APInt Size(S.Context.getTypeSize(SizeType),
8484 S.Context.getTypeSizeInChars(T).getQuantity());
8485
8486 // Take the address of the field references for "from" and "to". We
8487 // directly construct UnaryOperators here because semantic analysis
8488 // does not permit us to take the address of an xvalue.
8489 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8490 S.Context.getPointerType(From->getType()),
8491 VK_RValue, OK_Ordinary, Loc);
8492 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8493 S.Context.getPointerType(To->getType()),
8494 VK_RValue, OK_Ordinary, Loc);
8495
8496 const Type *E = T->getBaseElementTypeUnsafe();
8497 bool NeedsCollectableMemCpy =
8498 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8499
8500 // Create a reference to the __builtin_objc_memmove_collectable function
8501 StringRef MemCpyName = NeedsCollectableMemCpy ?
8502 "__builtin_objc_memmove_collectable" :
8503 "__builtin_memcpy";
8504 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8505 Sema::LookupOrdinaryName);
8506 S.LookupName(R, S.TUScope, true);
8507
8508 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8509 if (!MemCpy)
8510 // Something went horribly wrong earlier, and we will have complained
8511 // about it.
8512 return StmtError();
8513
8514 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8515 VK_RValue, Loc, 0);
8516 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8517
8518 Expr *CallArgs[] = {
8519 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8520 };
8521 ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8522 Loc, CallArgs, Loc);
8523
8524 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8525 return S.Owned(Call.takeAs<Stmt>());
8526}
8527
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008528/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00008529/// \c To.
8530///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008531/// This routine is used to copy/move the members of a class with an
8532/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00008533/// copied are arrays, this routine builds for loops to copy them.
8534///
8535/// \param S The Sema object used for type-checking.
8536///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008537/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008538///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008539/// \param T The type of the expressions being copied/moved. Both expressions
8540/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008541///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008542/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008543///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008544/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00008545///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008546/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008547/// Otherwise, it's a non-static member subobject.
8548///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008549/// \param Copying Whether we're copying or moving.
8550///
Douglas Gregor06a9f362010-05-01 20:49:11 +00008551/// \param Depth Internal parameter recording the depth of the recursion.
8552///
Richard Smith8c889532012-11-14 00:50:40 +00008553/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8554/// if a memcpy should be used instead.
John McCall60d7b3a2010-08-24 06:29:42 +00008555static StmtResult
Richard Smith8c889532012-11-14 00:50:40 +00008556buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8557 Expr *To, Expr *From,
8558 bool CopyingBaseSubobject, bool Copying,
8559 unsigned Depth = 0) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008560 // C++11 [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00008561 // Each subobject is assigned in the manner appropriate to its type:
8562 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008563 // - if the subobject is of class type, as if by a call to operator= with
8564 // the subobject as the object expression and the corresponding
8565 // subobject of x as a single function argument (as if by explicit
8566 // qualification; that is, ignoring any possible virtual overriding
8567 // functions in more derived classes);
Richard Smith044c8aa2012-11-13 00:54:12 +00008568 //
8569 // C++03 [class.copy]p13:
8570 // - if the subobject is of class type, the copy assignment operator for
8571 // the class is used (as if by explicit qualification; that is,
8572 // ignoring any possible virtual overriding functions in more derived
8573 // classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008574 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8575 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
Richard Smith044c8aa2012-11-13 00:54:12 +00008576
Douglas Gregor06a9f362010-05-01 20:49:11 +00008577 // Look for operator=.
8578 DeclarationName Name
8579 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8580 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8581 S.LookupQualifiedName(OpLookup, ClassDecl, false);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008582
Richard Smith044c8aa2012-11-13 00:54:12 +00008583 // Prior to C++11, filter out any result that isn't a copy/move-assignment
8584 // operator.
Richard Smith80ad52f2013-01-02 11:42:31 +00008585 if (!S.getLangOpts().CPlusPlus11) {
Richard Smith044c8aa2012-11-13 00:54:12 +00008586 LookupResult::Filter F = OpLookup.makeFilter();
8587 while (F.hasNext()) {
8588 NamedDecl *D = F.next();
8589 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8590 if (Method->isCopyAssignmentOperator() ||
8591 (!Copying && Method->isMoveAssignmentOperator()))
8592 continue;
8593
8594 F.erase();
8595 }
8596 F.done();
John McCallb0207482010-03-16 06:11:48 +00008597 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008598
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008599 // Suppress the protected check (C++ [class.protected]) for each of the
Richard Smith044c8aa2012-11-13 00:54:12 +00008600 // assignment operators we found. This strange dance is required when
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008601 // we're assigning via a base classes's copy-assignment operator. To
Richard Smith044c8aa2012-11-13 00:54:12 +00008602 // ensure that we're getting the right base class subobject (without
Douglas Gregor6cdc1612010-05-04 15:20:55 +00008603 // ambiguities), we need to cast "this" to that subobject type; to
8604 // ensure that we don't go through the virtual call mechanism, we need
8605 // to qualify the operator= name with the base class (see below). However,
8606 // this means that if the base class has a protected copy assignment
8607 // operator, the protected member access check will fail. So, we
8608 // rewrite "protected" access to "public" access in this case, since we
8609 // know by construction that we're calling from a derived class.
8610 if (CopyingBaseSubobject) {
8611 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8612 L != LEnd; ++L) {
8613 if (L.getAccess() == AS_protected)
8614 L.setAccess(AS_public);
8615 }
8616 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008617
Douglas Gregor06a9f362010-05-01 20:49:11 +00008618 // Create the nested-name-specifier that will be used to qualify the
8619 // reference to operator=; this is required to suppress the virtual
8620 // call mechanism.
8621 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008622 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Richard Smith044c8aa2012-11-13 00:54:12 +00008623 SS.MakeTrivial(S.Context,
8624 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00008625 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00008626 Loc);
Richard Smith044c8aa2012-11-13 00:54:12 +00008627
Douglas Gregor06a9f362010-05-01 20:49:11 +00008628 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00008629 ExprResult OpEqualRef
Richard Smith044c8aa2012-11-13 00:54:12 +00008630 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008631 /*TemplateKWLoc=*/SourceLocation(),
8632 /*FirstQualifierInScope=*/0,
8633 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008634 /*TemplateArgs=*/0,
8635 /*SuppressQualifierCheck=*/true);
8636 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008637 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008638
Douglas Gregor06a9f362010-05-01 20:49:11 +00008639 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00008640
Richard Smith044c8aa2012-11-13 00:54:12 +00008641 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00008642 OpEqualRef.takeAs<Expr>(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +00008643 Loc, From, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008644 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008645 return StmtError();
Richard Smith044c8aa2012-11-13 00:54:12 +00008646
Richard Smith8c889532012-11-14 00:50:40 +00008647 // If we built a call to a trivial 'operator=' while copying an array,
8648 // bail out. We'll replace the whole shebang with a memcpy.
8649 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8650 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8651 return StmtResult((Stmt*)0);
8652
Richard Smith044c8aa2012-11-13 00:54:12 +00008653 // Convert to an expression-statement, and clean up any produced
8654 // temporaries.
Richard Smith41956372013-01-14 22:39:08 +00008655 return S.ActOnExprStmt(Call);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008656 }
John McCallb0207482010-03-16 06:11:48 +00008657
Richard Smith044c8aa2012-11-13 00:54:12 +00008658 // - if the subobject is of scalar type, the built-in assignment
Douglas Gregor06a9f362010-05-01 20:49:11 +00008659 // operator is used.
Richard Smith044c8aa2012-11-13 00:54:12 +00008660 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008661 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00008662 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008663 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008664 return StmtError();
Richard Smith41956372013-01-14 22:39:08 +00008665 return S.ActOnExprStmt(Assignment);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008666 }
Richard Smith044c8aa2012-11-13 00:54:12 +00008667
8668 // - if the subobject is an array, each element is assigned, in the
Douglas Gregor06a9f362010-05-01 20:49:11 +00008669 // manner appropriate to the element type;
Richard Smith044c8aa2012-11-13 00:54:12 +00008670
Douglas Gregor06a9f362010-05-01 20:49:11 +00008671 // Construct a loop over the array bounds, e.g.,
8672 //
8673 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8674 //
8675 // that will copy each of the array elements.
8676 QualType SizeType = S.Context.getSizeType();
Richard Smith8c889532012-11-14 00:50:40 +00008677
Douglas Gregor06a9f362010-05-01 20:49:11 +00008678 // Create the iteration variable.
8679 IdentifierInfo *IterationVarName = 0;
8680 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00008681 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008682 llvm::raw_svector_ostream OS(Str);
8683 OS << "__i" << Depth;
8684 IterationVarName = &S.Context.Idents.get(OS.str());
8685 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008686 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008687 IterationVarName, SizeType,
8688 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00008689 SC_None);
Richard Smith8c889532012-11-14 00:50:40 +00008690
Douglas Gregor06a9f362010-05-01 20:49:11 +00008691 // Initialize the iteration variable to zero.
8692 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008693 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00008694
8695 // Create a reference to the iteration variable; we'll use this several
8696 // times throughout.
8697 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00008698 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008699 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00008700 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8701 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8702
Douglas Gregor06a9f362010-05-01 20:49:11 +00008703 // Create the DeclStmt that holds the iteration variable.
8704 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
Richard Smith8c889532012-11-14 00:50:40 +00008705
Douglas Gregor06a9f362010-05-01 20:49:11 +00008706 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00008707 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008708 IterationVarRefRVal,
8709 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00008710 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00008711 IterationVarRefRVal,
8712 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008713 if (!Copying) // Cast to rvalue
8714 From = CastForMoving(S, From);
8715
8716 // Build the copy/move for an individual element of the array.
Richard Smith8c889532012-11-14 00:50:40 +00008717 StmtResult Copy =
8718 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8719 To, From, CopyingBaseSubobject,
8720 Copying, Depth + 1);
8721 // Bail out if copying fails or if we determined that we should use memcpy.
8722 if (Copy.isInvalid() || !Copy.get())
8723 return Copy;
8724
8725 // Create the comparison against the array bound.
8726 llvm::APInt Upper
8727 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8728 Expr *Comparison
8729 = new (S.Context) BinaryOperator(IterationVarRefRVal,
8730 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8731 BO_NE, S.Context.BoolTy,
8732 VK_RValue, OK_Ordinary, Loc, false);
8733
8734 // Create the pre-increment of the iteration variable.
8735 Expr *Increment
8736 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8737 VK_LValue, OK_Ordinary, Loc);
8738
Douglas Gregor06a9f362010-05-01 20:49:11 +00008739 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00008740 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00008741 S.MakeFullExpr(Comparison),
Richard Smith41956372013-01-14 22:39:08 +00008742 0, S.MakeFullDiscardedValueExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00008743 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008744}
8745
Richard Smith8c889532012-11-14 00:50:40 +00008746static StmtResult
8747buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8748 Expr *To, Expr *From,
8749 bool CopyingBaseSubobject, bool Copying) {
8750 // Maybe we should use a memcpy?
8751 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8752 T.isTriviallyCopyableType(S.Context))
8753 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8754
8755 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8756 CopyingBaseSubobject,
8757 Copying, 0));
8758
8759 // If we ended up picking a trivial assignment operator for an array of a
8760 // non-trivially-copyable class type, just emit a memcpy.
8761 if (!Result.isInvalid() && !Result.get())
8762 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8763
8764 return Result;
8765}
8766
Richard Smithb9d0b762012-07-27 04:22:15 +00008767Sema::ImplicitExceptionSpecification
8768Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8769 CXXRecordDecl *ClassDecl = MD->getParent();
8770
8771 ImplicitExceptionSpecification ExceptSpec(*this);
8772 if (ClassDecl->isInvalidDecl())
8773 return ExceptSpec;
8774
8775 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8776 assert(T->getNumArgs() == 1 && "not a copy assignment op");
8777 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8778
Douglas Gregorb87786f2010-07-01 17:48:08 +00008779 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00008780 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00008781 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00008782
8783 // It is unspecified whether or not an implicit copy assignment operator
8784 // attempts to deduplicate calls to assignment operators of virtual bases are
8785 // made. As such, this exception specification is effectively unspecified.
8786 // Based on a similar decision made for constness in C++0x, we're erring on
8787 // the side of assuming such calls to be made regardless of whether they
8788 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00008789 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8790 BaseEnd = ClassDecl->bases_end();
8791 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008792 if (Base->isVirtual())
8793 continue;
8794
Douglas Gregora376d102010-07-02 21:50:04 +00008795 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00008796 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008797 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8798 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008799 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00008800 }
Sean Hunt661c67a2011-06-21 23:42:56 +00008801
8802 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8803 BaseEnd = ClassDecl->vbases_end();
8804 Base != BaseEnd; ++Base) {
8805 CXXRecordDecl *BaseClassDecl
8806 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8807 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8808 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008809 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00008810 }
8811
Douglas Gregorb87786f2010-07-01 17:48:08 +00008812 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8813 FieldEnd = ClassDecl->field_end();
8814 Field != FieldEnd;
8815 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008816 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00008817 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8818 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008819 LookupCopyingAssignment(FieldClassDecl,
8820 ArgQuals | FieldType.getCVRQualifiers(),
8821 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008822 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008823 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00008824 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008825
Richard Smithb9d0b762012-07-27 04:22:15 +00008826 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00008827}
8828
8829CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8830 // Note: The following rules are largely analoguous to the copy
8831 // constructor rules. Note that virtual bases are not taken into account
8832 // for determining the argument type of the operator. Note also that
8833 // operators taking an object instead of a reference are allowed.
Richard Smithe5411b72012-12-01 02:35:44 +00008834 assert(ClassDecl->needsImplicitCopyAssignment());
Sean Hunt30de05c2011-05-14 05:23:20 +00008835
Richard Smithafb49182012-11-29 01:34:07 +00008836 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8837 if (DSM.isAlreadyBeingDeclared())
8838 return 0;
8839
Sean Hunt30de05c2011-05-14 05:23:20 +00008840 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8841 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smitha8942d72013-05-07 03:19:20 +00008842 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8843 if (Const)
Sean Hunt30de05c2011-05-14 05:23:20 +00008844 ArgType = ArgType.withConst();
8845 ArgType = Context.getLValueReferenceType(ArgType);
8846
Richard Smitha8942d72013-05-07 03:19:20 +00008847 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8848 CXXCopyAssignment,
8849 Const);
8850
Douglas Gregord3c35902010-07-01 16:36:15 +00008851 // An implicitly-declared copy assignment operator is an inline public
8852 // member of its class.
8853 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008854 SourceLocation ClassLoc = ClassDecl->getLocation();
8855 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00008856 CXXMethodDecl *CopyAssignment =
8857 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8858 /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8859 /*isInline=*/ true, Constexpr, SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00008860 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00008861 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00008862 CopyAssignment->setImplicit();
Richard Smithb9d0b762012-07-27 04:22:15 +00008863
8864 // Build an exception specification pointing back at this member.
8865 FunctionProtoType::ExtProtoInfo EPI;
8866 EPI.ExceptionSpecType = EST_Unevaluated;
8867 EPI.ExceptionSpecDecl = CopyAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00008868 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00008869
Douglas Gregord3c35902010-07-01 16:36:15 +00008870 // Add the parameter to the operator.
8871 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008872 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00008873 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008874 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008875 CopyAssignment->setParams(FromParam);
Sean Hunt7f410192011-05-14 05:23:24 +00008876
Richard Smithbc2a35d2012-12-08 08:32:28 +00008877 AddOverriddenMethods(ClassDecl, CopyAssignment);
8878
8879 CopyAssignment->setTrivial(
8880 ClassDecl->needsOverloadResolutionForCopyAssignment()
8881 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8882 : ClassDecl->hasTrivialCopyAssignment());
8883
Richard Smitha8942d72013-05-07 03:19:20 +00008884 // C++11 [class.copy]p19:
Nico Weberafcc96a2012-01-23 03:19:29 +00008885 // .... If the class definition does not explicitly declare a copy
8886 // assignment operator, there is no user-declared move constructor, and
8887 // there is no user-declared move assignment operator, a copy assignment
8888 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008889 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00008890 SetDeclDeleted(CopyAssignment, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00008891
Richard Smithbc2a35d2012-12-08 08:32:28 +00008892 // Note that we have added this copy-assignment operator.
8893 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8894
8895 if (Scope *S = getScopeForContext(ClassDecl))
8896 PushOnScopeChains(CopyAssignment, S, false);
8897 ClassDecl->addDecl(CopyAssignment);
8898
Douglas Gregord3c35902010-07-01 16:36:15 +00008899 return CopyAssignment;
8900}
8901
Richard Smith36155c12013-06-13 03:23:42 +00008902/// Diagnose an implicit copy operation for a class which is odr-used, but
8903/// which is deprecated because the class has a user-declared copy constructor,
8904/// copy assignment operator, or destructor.
8905static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
8906 SourceLocation UseLoc) {
8907 assert(CopyOp->isImplicit());
8908
8909 CXXRecordDecl *RD = CopyOp->getParent();
8910 CXXMethodDecl *UserDeclaredOperation = 0;
8911
8912 // In Microsoft mode, assignment operations don't affect constructors and
8913 // vice versa.
8914 if (RD->hasUserDeclaredDestructor()) {
8915 UserDeclaredOperation = RD->getDestructor();
8916 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
8917 RD->hasUserDeclaredCopyConstructor() &&
8918 !S.getLangOpts().MicrosoftMode) {
8919 // Find any user-declared copy constructor.
8920 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
8921 E = RD->ctor_end(); I != E; ++I) {
8922 if (I->isCopyConstructor()) {
8923 UserDeclaredOperation = *I;
8924 break;
8925 }
8926 }
8927 assert(UserDeclaredOperation);
8928 } else if (isa<CXXConstructorDecl>(CopyOp) &&
8929 RD->hasUserDeclaredCopyAssignment() &&
8930 !S.getLangOpts().MicrosoftMode) {
8931 // Find any user-declared move assignment operator.
8932 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
8933 E = RD->method_end(); I != E; ++I) {
8934 if (I->isCopyAssignmentOperator()) {
8935 UserDeclaredOperation = *I;
8936 break;
8937 }
8938 }
8939 assert(UserDeclaredOperation);
8940 }
8941
8942 if (UserDeclaredOperation) {
8943 S.Diag(UserDeclaredOperation->getLocation(),
8944 diag::warn_deprecated_copy_operation)
8945 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
8946 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
8947 S.Diag(UseLoc, diag::note_member_synthesized_at)
8948 << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
8949 : Sema::CXXCopyAssignment)
8950 << RD;
8951 }
8952}
8953
Douglas Gregor06a9f362010-05-01 20:49:11 +00008954void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8955 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00008956 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008957 CopyAssignOperator->isOverloadedOperator() &&
8958 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008959 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8960 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00008961 "DefineImplicitCopyAssignment called for wrong function");
8962
8963 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8964
8965 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8966 CopyAssignOperator->setInvalidDecl();
8967 return;
8968 }
Richard Smith36155c12013-06-13 03:23:42 +00008969
8970 // C++11 [class.copy]p18:
8971 // The [definition of an implicitly declared copy assignment operator] is
8972 // deprecated if the class has a user-declared copy constructor or a
8973 // user-declared destructor.
8974 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
8975 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
8976
Douglas Gregor06a9f362010-05-01 20:49:11 +00008977 CopyAssignOperator->setUsed();
8978
Eli Friedman9a14db32012-10-18 20:14:08 +00008979 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008980 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008981
8982 // C++0x [class.copy]p30:
8983 // The implicitly-defined or explicitly-defaulted copy assignment operator
8984 // for a non-union class X performs memberwise copy assignment of its
8985 // subobjects. The direct base classes of X are assigned first, in the
8986 // order of their declaration in the base-specifier-list, and then the
8987 // immediate non-static data members of X are assigned, in the order in
8988 // which they were declared in the class definition.
8989
8990 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008991 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008992
8993 // The parameter for the "other" object, which we are copying from.
8994 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8995 Qualifiers OtherQuals = Other->getType().getQualifiers();
8996 QualType OtherRefType = Other->getType();
8997 if (const LValueReferenceType *OtherRef
8998 = OtherRefType->getAs<LValueReferenceType>()) {
8999 OtherRefType = OtherRef->getPointeeType();
9000 OtherQuals = OtherRefType.getQualifiers();
9001 }
9002
9003 // Our location for everything implicitly-generated.
9004 SourceLocation Loc = CopyAssignOperator->getLocation();
9005
9006 // Construct a reference to the "other" object. We'll be using this
9007 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00009008 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00009009 assert(OtherRef && "Reference to parameter cannot fail!");
9010
9011 // Construct the "this" pointer. We'll be using this throughout the generated
9012 // ASTs.
9013 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9014 assert(This && "Reference to this cannot fail!");
9015
9016 // Assign base classes.
9017 bool Invalid = false;
9018 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9019 E = ClassDecl->bases_end(); Base != E; ++Base) {
9020 // Form the assignment:
9021 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9022 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00009023 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00009024 Invalid = true;
9025 continue;
9026 }
9027
John McCallf871d0c2010-08-07 06:22:56 +00009028 CXXCastPath BasePath;
9029 BasePath.push_back(Base);
9030
Douglas Gregor06a9f362010-05-01 20:49:11 +00009031 // Construct the "from" expression, which is an implicit cast to the
9032 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00009033 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00009034 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
9035 CK_UncheckedDerivedToBase,
9036 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00009037
9038 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00009039 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009040
9041 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00009042 To = ImpCastExprToType(To.take(),
9043 Context.getCVRQualifiedType(BaseType,
9044 CopyAssignOperator->getTypeQualifiers()),
9045 CK_UncheckedDerivedToBase,
9046 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009047
9048 // Build the copy.
Richard Smith8c889532012-11-14 00:50:40 +00009049 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00009050 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009051 /*CopyingBaseSubobject=*/true,
9052 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009053 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009054 Diag(CurrentLocation, diag::note_member_synthesized_at)
9055 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9056 CopyAssignOperator->setInvalidDecl();
9057 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009058 }
9059
9060 // Success! Record the copy.
9061 Statements.push_back(Copy.takeAs<Expr>());
9062 }
9063
Douglas Gregor06a9f362010-05-01 20:49:11 +00009064 // Assign non-static members.
9065 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9066 FieldEnd = ClassDecl->field_end();
9067 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009068 if (Field->isUnnamedBitfield())
9069 continue;
Eli Friedman8150da32013-06-07 01:48:56 +00009070
9071 if (Field->isInvalidDecl()) {
9072 Invalid = true;
9073 continue;
9074 }
9075
Douglas Gregor06a9f362010-05-01 20:49:11 +00009076 // Check for members of reference type; we can't copy those.
9077 if (Field->getType()->isReferenceType()) {
9078 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9079 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9080 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009081 Diag(CurrentLocation, diag::note_member_synthesized_at)
9082 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009083 Invalid = true;
9084 continue;
9085 }
9086
9087 // Check for members of const-qualified, non-class type.
9088 QualType BaseType = Context.getBaseElementType(Field->getType());
9089 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9090 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9091 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9092 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009093 Diag(CurrentLocation, diag::note_member_synthesized_at)
9094 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009095 Invalid = true;
9096 continue;
9097 }
John McCallb77115d2011-06-17 00:18:42 +00009098
9099 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009100 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9101 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009102
9103 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00009104 if (FieldType->isIncompleteArrayType()) {
9105 assert(ClassDecl->hasFlexibleArrayMember() &&
9106 "Incomplete array type is not valid");
9107 continue;
9108 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009109
9110 // Build references to the field in the object we're copying from and to.
9111 CXXScopeSpec SS; // Intentionally empty
9112 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9113 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009114 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009115 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00009116 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00009117 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009118 SS, SourceLocation(), 0,
9119 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00009120 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00009121 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009122 SS, SourceLocation(), 0,
9123 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009124 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9125 assert(!To.isInvalid() && "Implicit field reference cannot fail");
Douglas Gregor06a9f362010-05-01 20:49:11 +00009126
Douglas Gregor06a9f362010-05-01 20:49:11 +00009127 // Build the copy of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009128 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009129 To.get(), From.get(),
9130 /*CopyingBaseSubobject=*/false,
9131 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009132 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00009133 Diag(CurrentLocation, diag::note_member_synthesized_at)
9134 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9135 CopyAssignOperator->setInvalidDecl();
9136 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00009137 }
9138
9139 // Success! Record the copy.
9140 Statements.push_back(Copy.takeAs<Stmt>());
9141 }
9142
9143 if (!Invalid) {
9144 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00009145 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00009146
John McCall60d7b3a2010-08-24 06:29:42 +00009147 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00009148 if (Return.isInvalid())
9149 Invalid = true;
9150 else {
9151 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009152
9153 if (Trap.hasErrorOccurred()) {
9154 Diag(CurrentLocation, diag::note_member_synthesized_at)
9155 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9156 Invalid = true;
9157 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009158 }
9159 }
9160
9161 if (Invalid) {
9162 CopyAssignOperator->setInvalidDecl();
9163 return;
9164 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009165
9166 StmtResult Body;
9167 {
9168 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009169 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009170 /*isStmtExpr=*/false);
9171 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9172 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00009173 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009174
9175 if (ASTMutationListener *L = getASTMutationListener()) {
9176 L->CompletedImplicitDefinition(CopyAssignOperator);
9177 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00009178}
9179
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009180Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009181Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9182 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009183
Richard Smithb9d0b762012-07-27 04:22:15 +00009184 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009185 if (ClassDecl->isInvalidDecl())
9186 return ExceptSpec;
9187
9188 // C++0x [except.spec]p14:
9189 // An implicitly declared special member function (Clause 12) shall have an
9190 // exception-specification. [...]
9191
9192 // It is unspecified whether or not an implicit move assignment operator
9193 // attempts to deduplicate calls to assignment operators of virtual bases are
9194 // made. As such, this exception specification is effectively unspecified.
9195 // Based on a similar decision made for constness in C++0x, we're erring on
9196 // the side of assuming such calls to be made regardless of whether they
9197 // actually happen.
9198 // Note that a move constructor is not implicitly declared when there are
9199 // virtual bases, but it can still be user-declared and explicitly defaulted.
9200 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9201 BaseEnd = ClassDecl->bases_end();
9202 Base != BaseEnd; ++Base) {
9203 if (Base->isVirtual())
9204 continue;
9205
9206 CXXRecordDecl *BaseClassDecl
9207 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9208 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009209 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009210 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009211 }
9212
9213 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9214 BaseEnd = ClassDecl->vbases_end();
9215 Base != BaseEnd; ++Base) {
9216 CXXRecordDecl *BaseClassDecl
9217 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9218 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00009219 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009220 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009221 }
9222
9223 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9224 FieldEnd = ClassDecl->field_end();
9225 Field != FieldEnd;
9226 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009227 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009228 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009229 if (CXXMethodDecl *MoveAssign =
9230 LookupMovingAssignment(FieldClassDecl,
9231 FieldType.getCVRQualifiers(),
9232 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00009233 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009234 }
9235 }
9236
9237 return ExceptSpec;
9238}
9239
Richard Smith1c931be2012-04-02 18:40:40 +00009240/// Determine whether the class type has any direct or indirect virtual base
9241/// classes which have a non-trivial move assignment operator.
9242static bool
9243hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9244 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9245 BaseEnd = ClassDecl->vbases_end();
9246 Base != BaseEnd; ++Base) {
9247 CXXRecordDecl *BaseClass =
9248 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9249
9250 // Try to declare the move assignment. If it would be deleted, then the
9251 // class does not have a non-trivial move assignment.
9252 if (BaseClass->needsImplicitMoveAssignment())
9253 S.DeclareImplicitMoveAssignment(BaseClass);
9254
Richard Smith426391c2012-11-16 00:53:38 +00009255 if (BaseClass->hasNonTrivialMoveAssignment())
Richard Smith1c931be2012-04-02 18:40:40 +00009256 return true;
9257 }
9258
9259 return false;
9260}
9261
9262/// Determine whether the given type either has a move constructor or is
9263/// trivially copyable.
9264static bool
9265hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9266 Type = S.Context.getBaseElementType(Type);
9267
9268 // FIXME: Technically, non-trivially-copyable non-class types, such as
9269 // reference types, are supposed to return false here, but that appears
9270 // to be a standard defect.
9271 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Argyrios Kyrtzidisb5e4ace2012-10-10 16:14:06 +00009272 if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
Richard Smith1c931be2012-04-02 18:40:40 +00009273 return true;
9274
9275 if (Type.isTriviallyCopyableType(S.Context))
9276 return true;
9277
9278 if (IsConstructor) {
Richard Smithe5411b72012-12-01 02:35:44 +00009279 // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9280 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009281 if (ClassDecl->needsImplicitMoveConstructor())
9282 S.DeclareImplicitMoveConstructor(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009283 return ClassDecl->hasMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00009284 }
9285
Richard Smithe5411b72012-12-01 02:35:44 +00009286 // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9287 // give the right answer.
Richard Smith1c931be2012-04-02 18:40:40 +00009288 if (ClassDecl->needsImplicitMoveAssignment())
9289 S.DeclareImplicitMoveAssignment(ClassDecl);
Richard Smithe5411b72012-12-01 02:35:44 +00009290 return ClassDecl->hasMoveAssignment();
Richard Smith1c931be2012-04-02 18:40:40 +00009291}
9292
9293/// Determine whether all non-static data members and direct or virtual bases
9294/// of class \p ClassDecl have either a move operation, or are trivially
9295/// copyable.
9296static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9297 bool IsConstructor) {
9298 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9299 BaseEnd = ClassDecl->bases_end();
9300 Base != BaseEnd; ++Base) {
9301 if (Base->isVirtual())
9302 continue;
9303
9304 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9305 return false;
9306 }
9307
9308 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9309 BaseEnd = ClassDecl->vbases_end();
9310 Base != BaseEnd; ++Base) {
9311 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9312 return false;
9313 }
9314
9315 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9316 FieldEnd = ClassDecl->field_end();
9317 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009318 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00009319 return false;
9320 }
9321
9322 return true;
9323}
9324
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009325CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009326 // C++11 [class.copy]p20:
9327 // If the definition of a class X does not explicitly declare a move
9328 // assignment operator, one will be implicitly declared as defaulted
9329 // if and only if:
9330 //
9331 // - [first 4 bullets]
9332 assert(ClassDecl->needsImplicitMoveAssignment());
9333
Richard Smithafb49182012-11-29 01:34:07 +00009334 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9335 if (DSM.isAlreadyBeingDeclared())
9336 return 0;
9337
Richard Smith1c931be2012-04-02 18:40:40 +00009338 // [Checked after we build the declaration]
9339 // - the move assignment operator would not be implicitly defined as
9340 // deleted,
9341
9342 // [DR1402]:
9343 // - X has no direct or indirect virtual base class with a non-trivial
9344 // move assignment operator, and
9345 // - each of X's non-static data members and direct or virtual base classes
9346 // has a type that either has a move assignment operator or is trivially
9347 // copyable.
9348 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9349 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9350 ClassDecl->setFailedImplicitMoveAssignment();
9351 return 0;
9352 }
9353
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009354 // Note: The following rules are largely analoguous to the move
9355 // constructor rules.
9356
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009357 QualType ArgType = Context.getTypeDeclType(ClassDecl);
9358 QualType RetType = Context.getLValueReferenceType(ArgType);
9359 ArgType = Context.getRValueReferenceType(ArgType);
9360
Richard Smitha8942d72013-05-07 03:19:20 +00009361 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9362 CXXMoveAssignment,
9363 false);
9364
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009365 // An implicitly-declared move assignment operator is an inline public
9366 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009367 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9368 SourceLocation ClassLoc = ClassDecl->getLocation();
9369 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smitha8942d72013-05-07 03:19:20 +00009370 CXXMethodDecl *MoveAssignment =
9371 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9372 /*TInfo=*/0, /*StorageClass=*/SC_None,
9373 /*isInline=*/true, Constexpr, SourceLocation());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009374 MoveAssignment->setAccess(AS_public);
9375 MoveAssignment->setDefaulted();
9376 MoveAssignment->setImplicit();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009377
Richard Smithb9d0b762012-07-27 04:22:15 +00009378 // Build an exception specification pointing back at this member.
9379 FunctionProtoType::ExtProtoInfo EPI;
9380 EPI.ExceptionSpecType = EST_Unevaluated;
9381 EPI.ExceptionSpecDecl = MoveAssignment;
Jordan Rosebea522f2013-03-08 21:51:21 +00009382 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009383
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009384 // Add the parameter to the operator.
9385 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9386 ClassLoc, ClassLoc, /*Id=*/0,
9387 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009388 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009389 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009390
Richard Smithbc2a35d2012-12-08 08:32:28 +00009391 AddOverriddenMethods(ClassDecl, MoveAssignment);
9392
9393 MoveAssignment->setTrivial(
9394 ClassDecl->needsOverloadResolutionForMoveAssignment()
9395 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9396 : ClassDecl->hasTrivialMoveAssignment());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009397
9398 // C++0x [class.copy]p9:
9399 // If the definition of a class X does not explicitly declare a move
9400 // assignment operator, one will be implicitly declared as defaulted if and
9401 // only if:
9402 // [...]
9403 // - the move assignment operator would not be implicitly defined as
9404 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00009405 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009406 // Cache this result so that we don't try to generate this over and over
9407 // on every lookup, leaking memory and wasting time.
9408 ClassDecl->setFailedImplicitMoveAssignment();
9409 return 0;
9410 }
9411
Richard Smithbc2a35d2012-12-08 08:32:28 +00009412 // Note that we have added this copy-assignment operator.
9413 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9414
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009415 if (Scope *S = getScopeForContext(ClassDecl))
9416 PushOnScopeChains(MoveAssignment, S, false);
9417 ClassDecl->addDecl(MoveAssignment);
9418
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009419 return MoveAssignment;
9420}
9421
9422void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9423 CXXMethodDecl *MoveAssignOperator) {
9424 assert((MoveAssignOperator->isDefaulted() &&
9425 MoveAssignOperator->isOverloadedOperator() &&
9426 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00009427 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9428 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009429 "DefineImplicitMoveAssignment called for wrong function");
9430
9431 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9432
9433 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9434 MoveAssignOperator->setInvalidDecl();
9435 return;
9436 }
9437
9438 MoveAssignOperator->setUsed();
9439
Eli Friedman9a14db32012-10-18 20:14:08 +00009440 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009441 DiagnosticErrorTrap Trap(Diags);
9442
9443 // C++0x [class.copy]p28:
9444 // The implicitly-defined or move assignment operator for a non-union class
9445 // X performs memberwise move assignment of its subobjects. The direct base
9446 // classes of X are assigned first, in the order of their declaration in the
9447 // base-specifier-list, and then the immediate non-static data members of X
9448 // are assigned, in the order in which they were declared in the class
9449 // definition.
9450
9451 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009452 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009453
9454 // The parameter for the "other" object, which we are move from.
9455 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9456 QualType OtherRefType = Other->getType()->
9457 getAs<RValueReferenceType>()->getPointeeType();
David Blaikie7247c882013-05-15 07:37:26 +00009458 assert(!OtherRefType.getQualifiers() &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009459 "Bad argument type of defaulted move assignment");
9460
9461 // Our location for everything implicitly-generated.
9462 SourceLocation Loc = MoveAssignOperator->getLocation();
9463
9464 // Construct a reference to the "other" object. We'll be using this
9465 // throughout the generated ASTs.
9466 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9467 assert(OtherRef && "Reference to parameter cannot fail!");
9468 // Cast to rvalue.
9469 OtherRef = CastForMoving(*this, OtherRef);
9470
9471 // Construct the "this" pointer. We'll be using this throughout the generated
9472 // ASTs.
9473 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9474 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00009475
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009476 // Assign base classes.
9477 bool Invalid = false;
9478 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9479 E = ClassDecl->bases_end(); Base != E; ++Base) {
9480 // Form the assignment:
9481 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9482 QualType BaseType = Base->getType().getUnqualifiedType();
9483 if (!BaseType->isRecordType()) {
9484 Invalid = true;
9485 continue;
9486 }
9487
9488 CXXCastPath BasePath;
9489 BasePath.push_back(Base);
9490
9491 // Construct the "from" expression, which is an implicit cast to the
9492 // appropriately-qualified base type.
9493 Expr *From = OtherRef;
9494 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00009495 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009496
9497 // Dereference "this".
9498 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9499
9500 // Implicitly cast "this" to the appropriately-qualified base type.
9501 To = ImpCastExprToType(To.take(),
9502 Context.getCVRQualifiedType(BaseType,
9503 MoveAssignOperator->getTypeQualifiers()),
9504 CK_UncheckedDerivedToBase,
9505 VK_LValue, &BasePath);
9506
9507 // Build the move.
Richard Smith8c889532012-11-14 00:50:40 +00009508 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009509 To.get(), From,
9510 /*CopyingBaseSubobject=*/true,
9511 /*Copying=*/false);
9512 if (Move.isInvalid()) {
9513 Diag(CurrentLocation, diag::note_member_synthesized_at)
9514 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9515 MoveAssignOperator->setInvalidDecl();
9516 return;
9517 }
9518
9519 // Success! Record the move.
9520 Statements.push_back(Move.takeAs<Expr>());
9521 }
9522
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009523 // Assign non-static members.
9524 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9525 FieldEnd = ClassDecl->field_end();
9526 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00009527 if (Field->isUnnamedBitfield())
9528 continue;
9529
Eli Friedman8150da32013-06-07 01:48:56 +00009530 if (Field->isInvalidDecl()) {
9531 Invalid = true;
9532 continue;
9533 }
9534
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009535 // Check for members of reference type; we can't move those.
9536 if (Field->getType()->isReferenceType()) {
9537 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9538 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9539 Diag(Field->getLocation(), diag::note_declared_at);
9540 Diag(CurrentLocation, diag::note_member_synthesized_at)
9541 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9542 Invalid = true;
9543 continue;
9544 }
9545
9546 // Check for members of const-qualified, non-class type.
9547 QualType BaseType = Context.getBaseElementType(Field->getType());
9548 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9549 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9550 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9551 Diag(Field->getLocation(), diag::note_declared_at);
9552 Diag(CurrentLocation, diag::note_member_synthesized_at)
9553 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9554 Invalid = true;
9555 continue;
9556 }
9557
9558 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00009559 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9560 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009561
9562 QualType FieldType = Field->getType().getNonReferenceType();
9563 if (FieldType->isIncompleteArrayType()) {
9564 assert(ClassDecl->hasFlexibleArrayMember() &&
9565 "Incomplete array type is not valid");
9566 continue;
9567 }
9568
9569 // Build references to the field in the object we're copying from and to.
9570 CXXScopeSpec SS; // Intentionally empty
9571 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9572 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00009573 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009574 MemberLookup.resolveKind();
9575 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9576 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009577 SS, SourceLocation(), 0,
9578 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009579 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9580 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009581 SS, SourceLocation(), 0,
9582 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009583 assert(!From.isInvalid() && "Implicit field reference cannot fail");
9584 assert(!To.isInvalid() && "Implicit field reference cannot fail");
9585
9586 assert(!From.get()->isLValue() && // could be xvalue or prvalue
9587 "Member reference with rvalue base must be rvalue except for reference "
9588 "members, which aren't allowed for move assignment.");
9589
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009590 // Build the move of this field.
Richard Smith8c889532012-11-14 00:50:40 +00009591 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009592 To.get(), From.get(),
9593 /*CopyingBaseSubobject=*/false,
9594 /*Copying=*/false);
9595 if (Move.isInvalid()) {
9596 Diag(CurrentLocation, diag::note_member_synthesized_at)
9597 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9598 MoveAssignOperator->setInvalidDecl();
9599 return;
9600 }
Richard Smithe7ce7092012-11-12 23:33:00 +00009601
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009602 // Success! Record the copy.
9603 Statements.push_back(Move.takeAs<Stmt>());
9604 }
9605
9606 if (!Invalid) {
9607 // Add a "return *this;"
9608 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9609
9610 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9611 if (Return.isInvalid())
9612 Invalid = true;
9613 else {
9614 Statements.push_back(Return.takeAs<Stmt>());
9615
9616 if (Trap.hasErrorOccurred()) {
9617 Diag(CurrentLocation, diag::note_member_synthesized_at)
9618 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9619 Invalid = true;
9620 }
9621 }
9622 }
9623
9624 if (Invalid) {
9625 MoveAssignOperator->setInvalidDecl();
9626 return;
9627 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009628
9629 StmtResult Body;
9630 {
9631 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009632 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009633 /*isStmtExpr=*/false);
9634 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9635 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009636 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9637
9638 if (ASTMutationListener *L = getASTMutationListener()) {
9639 L->CompletedImplicitDefinition(MoveAssignOperator);
9640 }
9641}
9642
Richard Smithb9d0b762012-07-27 04:22:15 +00009643Sema::ImplicitExceptionSpecification
9644Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9645 CXXRecordDecl *ClassDecl = MD->getParent();
9646
9647 ImplicitExceptionSpecification ExceptSpec(*this);
9648 if (ClassDecl->isInvalidDecl())
9649 return ExceptSpec;
9650
9651 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9652 assert(T->getNumArgs() >= 1 && "not a copy ctor");
9653 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9654
Douglas Gregor0d405db2010-07-01 20:59:04 +00009655 // C++ [except.spec]p14:
9656 // An implicitly declared special member function (Clause 12) shall have an
9657 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00009658 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9659 BaseEnd = ClassDecl->bases_end();
9660 Base != BaseEnd;
9661 ++Base) {
9662 // Virtual bases are handled below.
9663 if (Base->isVirtual())
9664 continue;
9665
Douglas Gregor22584312010-07-02 23:41:54 +00009666 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009667 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009668 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009669 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009670 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009671 }
9672 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9673 BaseEnd = ClassDecl->vbases_end();
9674 Base != BaseEnd;
9675 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00009676 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00009677 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00009678 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00009679 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00009680 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009681 }
9682 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9683 FieldEnd = ClassDecl->field_end();
9684 Field != FieldEnd;
9685 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00009686 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00009687 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9688 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00009689 LookupCopyingConstructor(FieldClassDecl,
9690 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00009691 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00009692 }
9693 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00009694
Richard Smithb9d0b762012-07-27 04:22:15 +00009695 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00009696}
9697
9698CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9699 CXXRecordDecl *ClassDecl) {
9700 // C++ [class.copy]p4:
9701 // If the class definition does not explicitly declare a copy
9702 // constructor, one is declared implicitly.
Richard Smithe5411b72012-12-01 02:35:44 +00009703 assert(ClassDecl->needsImplicitCopyConstructor());
Sean Hunt49634cf2011-05-13 06:10:58 +00009704
Richard Smithafb49182012-11-29 01:34:07 +00009705 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9706 if (DSM.isAlreadyBeingDeclared())
9707 return 0;
9708
Sean Hunt49634cf2011-05-13 06:10:58 +00009709 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9710 QualType ArgType = ClassType;
Richard Smithacf796b2012-11-28 06:23:12 +00009711 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
Sean Hunt49634cf2011-05-13 06:10:58 +00009712 if (Const)
9713 ArgType = ArgType.withConst();
9714 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00009715
Richard Smith7756afa2012-06-10 05:43:50 +00009716 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9717 CXXCopyConstructor,
9718 Const);
9719
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009720 DeclarationName Name
9721 = Context.DeclarationNames.getCXXConstructorName(
9722 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009723 SourceLocation ClassLoc = ClassDecl->getLocation();
9724 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00009725
9726 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009727 // member of its class.
9728 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009729 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009730 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009731 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009732 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00009733 CopyConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009734
Richard Smithb9d0b762012-07-27 04:22:15 +00009735 // Build an exception specification pointing back at this member.
9736 FunctionProtoType::ExtProtoInfo EPI;
9737 EPI.ExceptionSpecType = EST_Unevaluated;
9738 EPI.ExceptionSpecDecl = CopyConstructor;
9739 CopyConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009740 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009741
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009742 // Add the parameter to the constructor.
9743 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009744 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009745 /*IdentifierInfo=*/0,
9746 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00009747 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009748 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00009749
Richard Smithbc2a35d2012-12-08 08:32:28 +00009750 CopyConstructor->setTrivial(
9751 ClassDecl->needsOverloadResolutionForCopyConstructor()
9752 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9753 : ClassDecl->hasTrivialCopyConstructor());
Sean Hunt71a682f2011-05-18 03:41:58 +00009754
Nico Weberafcc96a2012-01-23 03:19:29 +00009755 // C++11 [class.copy]p8:
9756 // ... If the class definition does not explicitly declare a copy
9757 // constructor, there is no user-declared move constructor, and there is no
9758 // user-declared move assignment operator, a copy constructor is implicitly
9759 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00009760 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Richard Smith0ab5b4c2013-04-02 19:38:47 +00009761 SetDeclDeleted(CopyConstructor, ClassLoc);
Richard Smith6c4c36c2012-03-30 20:53:28 +00009762
Richard Smithbc2a35d2012-12-08 08:32:28 +00009763 // Note that we have declared this constructor.
9764 ++ASTContext::NumImplicitCopyConstructorsDeclared;
9765
9766 if (Scope *S = getScopeForContext(ClassDecl))
9767 PushOnScopeChains(CopyConstructor, S, false);
9768 ClassDecl->addDecl(CopyConstructor);
9769
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00009770 return CopyConstructor;
9771}
9772
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009773void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00009774 CXXConstructorDecl *CopyConstructor) {
9775 assert((CopyConstructor->isDefaulted() &&
9776 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009777 !CopyConstructor->doesThisDeclarationHaveABody() &&
9778 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009779 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00009780
Anders Carlsson63010a72010-04-23 16:24:12 +00009781 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009782 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009783
Richard Smith36155c12013-06-13 03:23:42 +00009784 // C++11 [class.copy]p7:
9785 // The [definition of an implicitly declared copy constructro] is
9786 // deprecated if the class has a user-declared copy assignment operator
9787 // or a user-declared destructor.
9788 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9789 diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9790
Eli Friedman9a14db32012-10-18 20:14:08 +00009791 SynthesizedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00009792 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009793
David Blaikie93c86172013-01-17 05:26:25 +00009794 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00009795 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00009796 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009797 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00009798 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009799 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009800 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00009801 CopyConstructor->setBody(ActOnCompoundStmt(
9802 CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
9803 /*isStmtExpr=*/ false).takeAs<Stmt>());
Anders Carlsson8e142cc2010-04-25 00:52:09 +00009804 }
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00009805
Douglas Gregorfb8cc252010-05-05 05:51:00 +00009806 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00009807 if (ASTMutationListener *L = getASTMutationListener()) {
9808 L->CompletedImplicitDefinition(CopyConstructor);
9809 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00009810}
9811
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009812Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00009813Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9814 CXXRecordDecl *ClassDecl = MD->getParent();
9815
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009816 // C++ [except.spec]p14:
9817 // An implicitly declared special member function (Clause 12) shall have an
9818 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00009819 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009820 if (ClassDecl->isInvalidDecl())
9821 return ExceptSpec;
9822
9823 // Direct base-class constructors.
9824 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9825 BEnd = ClassDecl->bases_end();
9826 B != BEnd; ++B) {
9827 if (B->isVirtual()) // Handled below.
9828 continue;
9829
9830 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9831 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009832 CXXConstructorDecl *Constructor =
9833 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009834 // If this is a deleted function, add it anyway. This might be conformant
9835 // with the standard. This might not. I'm not sure. It might not matter.
9836 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009837 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009838 }
9839 }
9840
9841 // Virtual base-class constructors.
9842 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9843 BEnd = ClassDecl->vbases_end();
9844 B != BEnd; ++B) {
9845 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9846 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00009847 CXXConstructorDecl *Constructor =
9848 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009849 // If this is a deleted function, add it anyway. This might be conformant
9850 // with the standard. This might not. I'm not sure. It might not matter.
9851 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009852 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009853 }
9854 }
9855
9856 // Field constructors.
9857 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9858 FEnd = ClassDecl->field_end();
9859 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00009860 QualType FieldType = Context.getBaseElementType(F->getType());
9861 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9862 CXXConstructorDecl *Constructor =
9863 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009864 // If this is a deleted function, add it anyway. This might be conformant
9865 // with the standard. This might not. I'm not sure. It might not matter.
9866 // In particular, the problem is that this function never gets called. It
9867 // might just be ill-formed because this function attempts to refer to
9868 // a deleted function here.
9869 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00009870 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009871 }
9872 }
9873
9874 return ExceptSpec;
9875}
9876
9877CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9878 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00009879 // C++11 [class.copy]p9:
9880 // If the definition of a class X does not explicitly declare a move
9881 // constructor, one will be implicitly declared as defaulted if and only if:
9882 //
9883 // - [first 4 bullets]
9884 assert(ClassDecl->needsImplicitMoveConstructor());
9885
Richard Smithafb49182012-11-29 01:34:07 +00009886 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9887 if (DSM.isAlreadyBeingDeclared())
9888 return 0;
9889
Richard Smith1c931be2012-04-02 18:40:40 +00009890 // [Checked after we build the declaration]
9891 // - the move assignment operator would not be implicitly defined as
9892 // deleted,
9893
9894 // [DR1402]:
9895 // - each of X's non-static data members and direct or virtual base classes
9896 // has a type that either has a move constructor or is trivially copyable.
9897 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9898 ClassDecl->setFailedImplicitMoveConstructor();
9899 return 0;
9900 }
9901
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009902 QualType ClassType = Context.getTypeDeclType(ClassDecl);
9903 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009904
Richard Smith7756afa2012-06-10 05:43:50 +00009905 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9906 CXXMoveConstructor,
9907 false);
9908
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009909 DeclarationName Name
9910 = Context.DeclarationNames.getCXXConstructorName(
9911 Context.getCanonicalType(ClassType));
9912 SourceLocation ClassLoc = ClassDecl->getLocation();
9913 DeclarationNameInfo NameInfo(Name, ClassLoc);
9914
Richard Smitha8942d72013-05-07 03:19:20 +00009915 // C++11 [class.copy]p11:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009916 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00009917 // member of its class.
9918 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00009919 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00009920 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00009921 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009922 MoveConstructor->setAccess(AS_public);
9923 MoveConstructor->setDefaulted();
Richard Smith61802452011-12-22 02:22:31 +00009924
Richard Smithb9d0b762012-07-27 04:22:15 +00009925 // Build an exception specification pointing back at this member.
9926 FunctionProtoType::ExtProtoInfo EPI;
9927 EPI.ExceptionSpecType = EST_Unevaluated;
9928 EPI.ExceptionSpecDecl = MoveConstructor;
9929 MoveConstructor->setType(
Jordan Rosebea522f2013-03-08 21:51:21 +00009930 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
Richard Smithb9d0b762012-07-27 04:22:15 +00009931
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009932 // Add the parameter to the constructor.
9933 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9934 ClassLoc, ClassLoc,
9935 /*IdentifierInfo=*/0,
9936 ArgType, /*TInfo=*/0,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009937 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00009938 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009939
Richard Smithbc2a35d2012-12-08 08:32:28 +00009940 MoveConstructor->setTrivial(
9941 ClassDecl->needsOverloadResolutionForMoveConstructor()
9942 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9943 : ClassDecl->hasTrivialMoveConstructor());
9944
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009945 // C++0x [class.copy]p9:
9946 // If the definition of a class X does not explicitly declare a move
9947 // constructor, one will be implicitly declared as defaulted if and only if:
9948 // [...]
9949 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00009950 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009951 // Cache this result so that we don't try to generate this over and over
9952 // on every lookup, leaking memory and wasting time.
9953 ClassDecl->setFailedImplicitMoveConstructor();
9954 return 0;
9955 }
9956
9957 // Note that we have declared this constructor.
9958 ++ASTContext::NumImplicitMoveConstructorsDeclared;
9959
9960 if (Scope *S = getScopeForContext(ClassDecl))
9961 PushOnScopeChains(MoveConstructor, S, false);
9962 ClassDecl->addDecl(MoveConstructor);
9963
9964 return MoveConstructor;
9965}
9966
9967void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9968 CXXConstructorDecl *MoveConstructor) {
9969 assert((MoveConstructor->isDefaulted() &&
9970 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00009971 !MoveConstructor->doesThisDeclarationHaveABody() &&
9972 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009973 "DefineImplicitMoveConstructor - call it for implicit move ctor");
9974
9975 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9976 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9977
Eli Friedman9a14db32012-10-18 20:14:08 +00009978 SynthesizedFunctionScope Scope(*this, MoveConstructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009979 DiagnosticErrorTrap Trap(Diags);
9980
David Blaikie93c86172013-01-17 05:26:25 +00009981 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009982 Trap.hasErrorOccurred()) {
9983 Diag(CurrentLocation, diag::note_member_synthesized_at)
9984 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9985 MoveConstructor->setInvalidDecl();
9986 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00009987 Sema::CompoundScopeRAII CompoundScope(*this);
Robert Wilhelmc895f4d2013-08-19 20:51:20 +00009988 MoveConstructor->setBody(ActOnCompoundStmt(
9989 MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
9990 /*isStmtExpr=*/ false).takeAs<Stmt>());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00009991 }
9992
9993 MoveConstructor->setUsed();
9994
9995 if (ASTMutationListener *L = getASTMutationListener()) {
9996 L->CompletedImplicitDefinition(MoveConstructor);
9997 }
9998}
9999
Douglas Gregore4e68d42012-02-15 19:33:52 +000010000bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
Eli Friedmanc4ef9482013-07-18 23:29:14 +000010001 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010002}
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010003
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010004/// \brief Mark the call operator of the given lambda closure type as "used".
10005static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
10006 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +000010007 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +000010008 Lambda->lookup(
10009 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010010 CallOperator->setReferenced();
10011 CallOperator->setUsed();
10012}
10013
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010014void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10015 SourceLocation CurrentLocation,
10016 CXXConversionDecl *Conv)
10017{
Manuel Klimek152b4e42013-08-22 12:12:24 +000010018 CXXRecordDecl *Lambda = Conv->getParent();
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010019
10020 // Make sure that the lambda call operator is marked used.
Manuel Klimek152b4e42013-08-22 12:12:24 +000010021 markLambdaCallOperatorUsed(*this, Lambda);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010022
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010023 Conv->setUsed();
10024
Eli Friedman9a14db32012-10-18 20:14:08 +000010025 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010026 DiagnosticErrorTrap Trap(Diags);
10027
Manuel Klimek152b4e42013-08-22 12:12:24 +000010028 // Return the address of the __invoke function.
10029 DeclarationName InvokeName = &Context.Idents.get("__invoke");
10030 CXXMethodDecl *Invoke
10031 = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010032 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
10033 VK_LValue, Conv->getLocation()).take();
Manuel Klimek152b4e42013-08-22 12:12:24 +000010034 assert(FunctionRef && "Can't refer to __invoke function?");
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010035 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
Nico Weberd36aa352012-12-29 20:03:39 +000010036 Conv->setBody(new (Context) CompoundStmt(Context, Return,
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010037 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010038 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010039
Manuel Klimek152b4e42013-08-22 12:12:24 +000010040 // Fill in the __invoke function with a dummy implementation. IR generation
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010041 // will fill in the actual details.
10042 Invoke->setUsed();
10043 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +000010044 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010045
10046 if (ASTMutationListener *L = getASTMutationListener()) {
10047 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +000010048 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010049 }
10050}
10051
10052void Sema::DefineImplicitLambdaToBlockPointerConversion(
10053 SourceLocation CurrentLocation,
10054 CXXConversionDecl *Conv)
10055{
10056 Conv->setUsed();
10057
Eli Friedman9a14db32012-10-18 20:14:08 +000010058 SynthesizedFunctionScope Scope(*this, Conv);
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010059 DiagnosticErrorTrap Trap(Diags);
10060
Douglas Gregorac1303e2012-02-22 05:02:47 +000010061 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010062 Expr *This = ActOnCXXThis(CurrentLocation).take();
10063 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010064
Eli Friedman23f02672012-03-01 04:01:32 +000010065 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10066 Conv->getLocation(),
10067 Conv, DerefThis);
10068
10069 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10070 // behavior. Note that only the general conversion function does this
10071 // (since it's unusable otherwise); in the case where we inline the
10072 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +000010073 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +000010074 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10075 CK_CopyAndAutoreleaseBlockObject,
10076 BuildBlock.get(), 0, VK_RValue);
10077
10078 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010079 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +000010080 Conv->setInvalidDecl();
10081 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010082 }
Douglas Gregorac1303e2012-02-22 05:02:47 +000010083
Douglas Gregorac1303e2012-02-22 05:02:47 +000010084 // Create the return statement that returns the block from the conversion
10085 // function.
Eli Friedman23f02672012-03-01 04:01:32 +000010086 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +000010087 if (Return.isInvalid()) {
10088 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10089 Conv->setInvalidDecl();
10090 return;
10091 }
10092
10093 // Set the body of the conversion function.
10094 Stmt *ReturnS = Return.take();
Nico Weberd36aa352012-12-29 20:03:39 +000010095 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
Douglas Gregorac1303e2012-02-22 05:02:47 +000010096 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010097 Conv->getLocation()));
10098
Douglas Gregorac1303e2012-02-22 05:02:47 +000010099 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +000010100 if (ASTMutationListener *L = getASTMutationListener()) {
10101 L->CompletedImplicitDefinition(Conv);
10102 }
10103}
10104
Douglas Gregorf52757d2012-03-10 06:53:13 +000010105/// \brief Determine whether the given list arguments contains exactly one
10106/// "real" (non-default) argument.
10107static bool hasOneRealArgument(MultiExprArg Args) {
10108 switch (Args.size()) {
10109 case 0:
10110 return false;
10111
10112 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010113 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +000010114 return false;
10115
10116 // fall through
10117 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010118 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +000010119 }
10120
10121 return false;
10122}
10123
John McCall60d7b3a2010-08-24 06:29:42 +000010124ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010125Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +000010126 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +000010127 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010128 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010129 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010130 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010131 unsigned ConstructKind,
10132 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010133 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +000010134
Douglas Gregor2f599792010-04-02 18:24:57 +000010135 // C++0x [class.copy]p34:
10136 // When certain criteria are met, an implementation is allowed to
10137 // omit the copy/move construction of a class object, even if the
10138 // copy/move constructor and/or destructor for the object have
10139 // side effects. [...]
10140 // - when a temporary class object that has not been bound to a
10141 // reference (12.2) would be copied/moved to a class object
10142 // with the same cv-unqualified type, the copy/move operation
10143 // can be omitted by constructing the temporary object
10144 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +000010145 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +000010146 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +000010147 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +000010148 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010149 }
Mike Stump1eb44332009-09-09 15:08:12 +000010150
10151 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010152 Elidable, ExprArgs, HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010153 IsListInitialization, RequiresZeroInit,
10154 ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +000010155}
10156
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010157/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10158/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +000010159ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +000010160Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10161 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +000010162 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010163 bool HadMultipleCandidates,
Richard Smithc83c2302012-12-19 01:39:02 +000010164 bool IsListInitialization,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +000010165 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010166 unsigned ConstructKind,
10167 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010168 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +000010169 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010170 Constructor, Elidable, ExprArgs,
Richard Smithc83c2302012-12-19 01:39:02 +000010171 HadMultipleCandidates,
10172 IsListInitialization, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +000010173 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10174 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +000010175}
10176
John McCall68c6c9a2010-02-02 09:10:11 +000010177void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010178 if (VD->isInvalidDecl()) return;
10179
John McCall68c6c9a2010-02-02 09:10:11 +000010180 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010181 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +000010182 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010183 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +000010184
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010185 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010186 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010187 CheckDestructorAccess(VD->getLocation(), Destructor,
10188 PDiag(diag::err_access_dtor_var)
10189 << VD->getDeclName()
10190 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +000010191 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +000010192
Chandler Carruth1d71cbf2011-03-27 21:26:48 +000010193 if (!VD->hasGlobalStorage()) return;
10194
10195 // Emit warning for non-trivial dtor in global scope (a real global,
10196 // class-static, function-static).
10197 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10198
10199 // TODO: this should be re-enabled for static locals by !CXAAtExit
10200 if (!VD->isStaticLocal())
10201 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +000010202}
10203
Douglas Gregor39da0b82009-09-09 23:08:42 +000010204/// \brief Given a constructor and the set of arguments provided for the
10205/// constructor, convert the arguments and add any required default arguments
10206/// to form a proper call to this constructor.
10207///
10208/// \returns true if an error occurred, false otherwise.
10209bool
10210Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10211 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +000010212 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +000010213 SmallVectorImpl<Expr*> &ConvertedArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010214 bool AllowExplicit,
10215 bool IsListInitialization) {
Douglas Gregor39da0b82009-09-09 23:08:42 +000010216 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10217 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +000010218 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010219
10220 const FunctionProtoType *Proto
10221 = Constructor->getType()->getAs<FunctionProtoType>();
10222 assert(Proto && "Constructor without a prototype?");
10223 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +000010224
10225 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010226 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +000010227 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010228 else
Douglas Gregor39da0b82009-09-09 23:08:42 +000010229 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010230
10231 VariadicCallType CallType =
10232 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010233 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010234 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010235 Proto, 0,
10236 llvm::makeArrayRef(Args, NumArgs),
10237 AllArgs,
Richard Smitha4dc51b2013-02-05 05:52:24 +000010238 CallType, AllowExplicit,
10239 IsListInitialization);
Benjamin Kramer14c59822012-02-14 12:06:21 +000010240 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +000010241
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010242 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
Eli Friedmane61eb042012-02-18 04:48:30 +000010243
Dmitri Gribenko1c030e92013-01-13 20:46:02 +000010244 CheckConstructorCall(Constructor,
10245 llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10246 AllArgs.size()),
Richard Smith831421f2012-06-25 20:30:08 +000010247 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +000010248
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +000010249 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +000010250}
10251
Anders Carlsson20d45d22009-12-12 00:32:00 +000010252static inline bool
10253CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10254 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010255 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +000010256 if (isa<NamespaceDecl>(DC)) {
10257 return SemaRef.Diag(FnDecl->getLocation(),
10258 diag::err_operator_new_delete_declared_in_namespace)
10259 << FnDecl->getDeclName();
10260 }
10261
10262 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +000010263 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010264 return SemaRef.Diag(FnDecl->getLocation(),
10265 diag::err_operator_new_delete_declared_static)
10266 << FnDecl->getDeclName();
10267 }
10268
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +000010269 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +000010270}
10271
Anders Carlsson156c78e2009-12-13 17:53:43 +000010272static inline bool
10273CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10274 CanQualType ExpectedResultType,
10275 CanQualType ExpectedFirstParamType,
10276 unsigned DependentParamTypeDiag,
10277 unsigned InvalidParamTypeDiag) {
10278 QualType ResultType =
10279 FnDecl->getType()->getAs<FunctionType>()->getResultType();
10280
10281 // Check that the result type is not dependent.
10282 if (ResultType->isDependentType())
10283 return SemaRef.Diag(FnDecl->getLocation(),
10284 diag::err_operator_new_delete_dependent_result_type)
10285 << FnDecl->getDeclName() << ExpectedResultType;
10286
10287 // Check that the result type is what we expect.
10288 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10289 return SemaRef.Diag(FnDecl->getLocation(),
10290 diag::err_operator_new_delete_invalid_result_type)
10291 << FnDecl->getDeclName() << ExpectedResultType;
10292
10293 // A function template must have at least 2 parameters.
10294 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10295 return SemaRef.Diag(FnDecl->getLocation(),
10296 diag::err_operator_new_delete_template_too_few_parameters)
10297 << FnDecl->getDeclName();
10298
10299 // The function decl must have at least 1 parameter.
10300 if (FnDecl->getNumParams() == 0)
10301 return SemaRef.Diag(FnDecl->getLocation(),
10302 diag::err_operator_new_delete_too_few_parameters)
10303 << FnDecl->getDeclName();
10304
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +000010305 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010306 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10307 if (FirstParamType->isDependentType())
10308 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10309 << FnDecl->getDeclName() << ExpectedFirstParamType;
10310
10311 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +000010312 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +000010313 ExpectedFirstParamType)
10314 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10315 << FnDecl->getDeclName() << ExpectedFirstParamType;
10316
10317 return false;
10318}
10319
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010320static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +000010321CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +000010322 // C++ [basic.stc.dynamic.allocation]p1:
10323 // A program is ill-formed if an allocation function is declared in a
10324 // namespace scope other than global scope or declared static in global
10325 // scope.
10326 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10327 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +000010328
10329 CanQualType SizeTy =
10330 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10331
10332 // C++ [basic.stc.dynamic.allocation]p1:
10333 // The return type shall be void*. The first parameter shall have type
10334 // std::size_t.
10335 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10336 SizeTy,
10337 diag::err_operator_new_dependent_param_type,
10338 diag::err_operator_new_param_type))
10339 return true;
10340
10341 // C++ [basic.stc.dynamic.allocation]p1:
10342 // The first parameter shall not have an associated default argument.
10343 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +000010344 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +000010345 diag::err_operator_new_default_arg)
10346 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10347
10348 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +000010349}
10350
10351static bool
Richard Smith444d3842012-10-20 08:26:51 +000010352CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010353 // C++ [basic.stc.dynamic.deallocation]p1:
10354 // A program is ill-formed if deallocation functions are declared in a
10355 // namespace scope other than global scope or declared static in global
10356 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +000010357 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10358 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010359
10360 // C++ [basic.stc.dynamic.deallocation]p2:
10361 // Each deallocation function shall return void and its first parameter
10362 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +000010363 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10364 SemaRef.Context.VoidPtrTy,
10365 diag::err_operator_delete_dependent_param_type,
10366 diag::err_operator_delete_param_type))
10367 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010368
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010369 return false;
10370}
10371
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010372/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10373/// of this overloaded operator is well-formed. If so, returns false;
10374/// otherwise, emits appropriate diagnostics and returns true.
10375bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010376 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010377 "Expected an overloaded operator declaration");
10378
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010379 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10380
Mike Stump1eb44332009-09-09 15:08:12 +000010381 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010382 // The allocation and deallocation functions, operator new,
10383 // operator new[], operator delete and operator delete[], are
10384 // described completely in 3.7.3. The attributes and restrictions
10385 // found in the rest of this subclause do not apply to them unless
10386 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +000010387 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +000010388 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +000010389
Anders Carlssona3ccda52009-12-12 00:26:23 +000010390 if (Op == OO_New || Op == OO_Array_New)
10391 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010392
10393 // C++ [over.oper]p6:
10394 // An operator function shall either be a non-static member
10395 // function or be a non-member function and have at least one
10396 // parameter whose type is a class, a reference to a class, an
10397 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010398 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10399 if (MethodDecl->isStatic())
10400 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010401 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010402 } else {
10403 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010404 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10405 ParamEnd = FnDecl->param_end();
10406 Param != ParamEnd; ++Param) {
10407 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +000010408 if (ParamType->isDependentType() || ParamType->isRecordType() ||
10409 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010410 ClassOrEnumParam = true;
10411 break;
10412 }
10413 }
10414
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010415 if (!ClassOrEnumParam)
10416 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010417 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010418 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010419 }
10420
10421 // C++ [over.oper]p8:
10422 // An operator function cannot have default arguments (8.3.6),
10423 // except where explicitly stated below.
10424 //
Mike Stump1eb44332009-09-09 15:08:12 +000010425 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010426 // (C++ [over.call]p1).
10427 if (Op != OO_Call) {
10428 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10429 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +000010430 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +000010431 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +000010432 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +000010433 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010434 }
10435 }
10436
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010437 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10438 { false, false, false }
10439#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10440 , { Unary, Binary, MemberOnly }
10441#include "clang/Basic/OperatorKinds.def"
10442 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010443
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010444 bool CanBeUnaryOperator = OperatorUses[Op][0];
10445 bool CanBeBinaryOperator = OperatorUses[Op][1];
10446 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010447
10448 // C++ [over.oper]p8:
10449 // [...] Operator functions cannot have more or fewer parameters
10450 // than the number required for the corresponding operator, as
10451 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +000010452 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010453 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010454 if (Op != OO_Call &&
10455 ((NumParams == 1 && !CanBeUnaryOperator) ||
10456 (NumParams == 2 && !CanBeBinaryOperator) ||
10457 (NumParams < 1) || (NumParams > 2))) {
10458 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +000010459 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010460 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010461 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010462 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +000010463 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010464 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010465 assert(CanBeBinaryOperator &&
10466 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +000010467 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +000010468 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010469
Chris Lattner416e46f2008-11-21 07:57:12 +000010470 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010471 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010472 }
Sebastian Redl64b45f72009-01-05 20:52:13 +000010473
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010474 // Overloaded operators other than operator() cannot be variadic.
10475 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +000010476 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010477 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010478 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010479 }
10480
10481 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010482 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10483 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +000010484 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +000010485 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010486 }
10487
10488 // C++ [over.inc]p1:
10489 // The user-defined function called operator++ implements the
10490 // prefix and postfix ++ operator. If this function is a member
10491 // function with no parameters, or a non-member function with one
10492 // parameter of class or enumeration type, it defines the prefix
10493 // increment operator ++ for objects of that type. If the function
10494 // is a member function with one parameter (which shall be of type
10495 // int) or a non-member function with two parameters (the second
10496 // of which shall be of type int), it defines the postfix
10497 // increment operator ++ for objects of that type.
10498 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10499 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10500 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +000010501 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010502 ParamIsInt = BT->getKind() == BuiltinType::Int;
10503
Chris Lattneraf7ae4e2008-11-21 07:50:02 +000010504 if (!ParamIsInt)
10505 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +000010506 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +000010507 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010508 }
10509
Douglas Gregor43c7bad2008-11-17 16:14:12 +000010510 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +000010511}
Chris Lattner5a003a42008-12-17 07:09:26 +000010512
Sean Hunta6c058d2010-01-13 09:01:02 +000010513/// CheckLiteralOperatorDeclaration - Check whether the declaration
10514/// of this literal operator function is well-formed. If so, returns
10515/// false; otherwise, emits appropriate diagnostics and returns true.
10516bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +000010517 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010518 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10519 << FnDecl->getDeclName();
10520 return true;
10521 }
10522
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010523 if (FnDecl->isExternC()) {
10524 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10525 return true;
10526 }
10527
Sean Hunta6c058d2010-01-13 09:01:02 +000010528 bool Valid = false;
10529
Richard Smith36f5cfe2012-03-09 08:00:36 +000010530 // This might be the definition of a literal operator template.
10531 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10532 // This might be a specialization of a literal operator template.
10533 if (!TpDecl)
10534 TpDecl = FnDecl->getPrimaryTemplate();
10535
Sean Hunt216c2782010-04-07 23:11:06 +000010536 // template <char...> type operator "" name() is the only valid template
10537 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +000010538 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010539 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +000010540 // Must have only one template parameter
10541 TemplateParameterList *Params = TpDecl->getTemplateParameters();
10542 if (Params->size() == 1) {
10543 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +000010544 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +000010545
Sean Hunt216c2782010-04-07 23:11:06 +000010546 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +000010547 if (PmDecl && PmDecl->isTemplateParameterPack() &&
10548 Context.hasSameType(PmDecl->getType(), Context.CharTy))
10549 Valid = true;
10550 }
10551 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010552 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +000010553 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +000010554 FunctionDecl::param_iterator Param = FnDecl->param_begin();
10555
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010556 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +000010557
Sean Hunt30019c02010-04-07 22:57:35 +000010558 // unsigned long long int, long double, and any character type are allowed
10559 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +000010560 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10561 Context.hasSameType(T, Context.LongDoubleTy) ||
10562 Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010563 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010564 Context.hasSameType(T, Context.Char16Ty) ||
10565 Context.hasSameType(T, Context.Char32Ty)) {
10566 if (++Param == FnDecl->param_end())
10567 Valid = true;
10568 goto FinishedParams;
10569 }
10570
Sean Hunt30019c02010-04-07 22:57:35 +000010571 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +000010572 const PointerType *PT = T->getAs<PointerType>();
10573 if (!PT)
10574 goto FinishedParams;
10575 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +000010576 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +000010577 goto FinishedParams;
10578 T = T.getUnqualifiedType();
10579
10580 // Move on to the second parameter;
10581 ++Param;
10582
10583 // If there is no second parameter, the first must be a const char *
10584 if (Param == FnDecl->param_end()) {
10585 if (Context.hasSameType(T, Context.CharTy))
10586 Valid = true;
10587 goto FinishedParams;
10588 }
10589
10590 // const char *, const wchar_t*, const char16_t*, and const char32_t*
10591 // are allowed as the first parameter to a two-parameter function
10592 if (!(Context.hasSameType(T, Context.CharTy) ||
Hans Wennborg15f92ba2013-05-10 10:08:40 +000010593 Context.hasSameType(T, Context.WideCharTy) ||
Sean Hunta6c058d2010-01-13 09:01:02 +000010594 Context.hasSameType(T, Context.Char16Ty) ||
10595 Context.hasSameType(T, Context.Char32Ty)))
10596 goto FinishedParams;
10597
10598 // The second and final parameter must be an std::size_t
10599 T = (*Param)->getType().getUnqualifiedType();
10600 if (Context.hasSameType(T, Context.getSizeType()) &&
10601 ++Param == FnDecl->param_end())
10602 Valid = true;
10603 }
10604
10605 // FIXME: This diagnostic is absolutely terrible.
10606FinishedParams:
10607 if (!Valid) {
10608 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10609 << FnDecl->getDeclName();
10610 return true;
10611 }
10612
Richard Smitha9e88b22012-03-09 08:16:22 +000010613 // A parameter-declaration-clause containing a default argument is not
10614 // equivalent to any of the permitted forms.
10615 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10616 ParamEnd = FnDecl->param_end();
10617 Param != ParamEnd; ++Param) {
10618 if ((*Param)->hasDefaultArg()) {
10619 Diag((*Param)->getDefaultArgRange().getBegin(),
10620 diag::err_literal_operator_default_argument)
10621 << (*Param)->getDefaultArgRange();
10622 break;
10623 }
10624 }
10625
Richard Smith2fb4ae32012-03-08 02:39:21 +000010626 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +000010627 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10628 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +000010629 // C++11 [usrlit.suffix]p1:
10630 // Literal suffix identifiers that do not start with an underscore
10631 // are reserved for future standardization.
Richard Smith4ac537b2013-07-23 08:14:48 +000010632 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10633 << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
Douglas Gregor1155c422011-08-30 22:40:35 +000010634 }
Richard Smith2fb4ae32012-03-08 02:39:21 +000010635
Sean Hunta6c058d2010-01-13 09:01:02 +000010636 return false;
10637}
10638
Douglas Gregor074149e2009-01-05 19:45:36 +000010639/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10640/// linkage specification, including the language and (if present)
10641/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10642/// the location of the language string literal, which is provided
10643/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10644/// the '{' brace. Otherwise, this linkage specification does not
10645/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +000010646Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10647 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +000010648 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +000010649 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +000010650 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010651 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010652 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +000010653 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +000010654 Language = LinkageSpecDecl::lang_cxx;
10655 else {
Douglas Gregor074149e2009-01-05 19:45:36 +000010656 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +000010657 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010658 }
Mike Stump1eb44332009-09-09 15:08:12 +000010659
Chris Lattnercc98eac2008-12-17 07:13:27 +000010660 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +000010661
Douglas Gregor074149e2009-01-05 19:45:36 +000010662 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Rafael Espindolae5e575d2013-04-26 01:30:23 +000010663 ExternLoc, LangLoc, Language,
10664 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010665 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +000010666 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +000010667 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +000010668}
10669
Abramo Bagnara35f9a192010-07-30 16:47:02 +000010670/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +000010671/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10672/// valid, it's the position of the closing '}' brace in a linkage
10673/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +000010674Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010675 Decl *LinkageSpec,
10676 SourceLocation RBraceLoc) {
10677 if (LinkageSpec) {
10678 if (RBraceLoc.isValid()) {
10679 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10680 LSDecl->setRBraceLoc(RBraceLoc);
10681 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010682 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +000010683 }
Douglas Gregor074149e2009-01-05 19:45:36 +000010684 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +000010685}
10686
Michael Han684aa732013-02-22 17:15:32 +000010687Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10688 AttributeList *AttrList,
10689 SourceLocation SemiLoc) {
10690 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10691 // Attribute declarations appertain to empty declaration so we handle
10692 // them here.
10693 if (AttrList)
10694 ProcessDeclAttributeList(S, ED, AttrList);
Richard Smith6b3d3e52013-02-20 19:22:51 +000010695
Michael Han684aa732013-02-22 17:15:32 +000010696 CurContext->addDecl(ED);
10697 return ED;
Richard Smith6b3d3e52013-02-20 19:22:51 +000010698}
10699
Douglas Gregord308e622009-05-18 20:51:54 +000010700/// \brief Perform semantic analysis for the variable declaration that
10701/// occurs within a C++ catch clause, returning the newly-created
10702/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010703VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +000010704 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010705 SourceLocation StartLoc,
10706 SourceLocation Loc,
10707 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +000010708 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +000010709 QualType ExDeclType = TInfo->getType();
10710
Sebastian Redl4b07b292008-12-22 19:15:10 +000010711 // Arrays and functions decay.
10712 if (ExDeclType->isArrayType())
10713 ExDeclType = Context.getArrayDecayedType(ExDeclType);
10714 else if (ExDeclType->isFunctionType())
10715 ExDeclType = Context.getPointerType(ExDeclType);
10716
10717 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10718 // The exception-declaration shall not denote a pointer or reference to an
10719 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010720 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +000010721 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +000010722 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010723 Invalid = true;
10724 }
Douglas Gregord308e622009-05-18 20:51:54 +000010725
Sebastian Redl4b07b292008-12-22 19:15:10 +000010726 QualType BaseType = ExDeclType;
10727 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +000010728 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +000010729 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010730 BaseType = Ptr->getPointeeType();
10731 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010732 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +000010733 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010734 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010735 BaseType = Ref->getPointeeType();
10736 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +000010737 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010738 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +000010739 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +000010740 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +000010741 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010742
Mike Stump1eb44332009-09-09 15:08:12 +000010743 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +000010744 RequireNonAbstractType(Loc, ExDeclType,
10745 diag::err_abstract_type_in_decl,
10746 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +000010747 Invalid = true;
10748
John McCall5a180392010-07-24 00:37:23 +000010749 // Only the non-fragile NeXT runtime currently supports C++ catches
10750 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +000010751 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +000010752 QualType T = ExDeclType;
10753 if (const ReferenceType *RT = T->getAs<ReferenceType>())
10754 T = RT->getPointeeType();
10755
10756 if (T->isObjCObjectType()) {
10757 Diag(Loc, diag::err_objc_object_catch);
10758 Invalid = true;
10759 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +000010760 // FIXME: should this be a test for macosx-fragile specifically?
10761 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +000010762 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +000010763 }
10764 }
10765
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010766 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +000010767 ExDeclType, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +000010768 ExDecl->setExceptionVariable(true);
10769
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010770 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +000010771 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +000010772 Invalid = true;
10773
Douglas Gregorc41b8782011-07-06 18:14:43 +000010774 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +000010775 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
John McCallb760f112013-03-22 02:10:40 +000010776 // Insulate this from anything else we might currently be parsing.
10777 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10778
Douglas Gregor6d182892010-03-05 23:38:39 +000010779 // C++ [except.handle]p16:
10780 // The object declared in an exception-declaration or, if the
10781 // exception-declaration does not specify a name, a temporary (12.2) is
10782 // copy-initialized (8.5) from the exception object. [...]
10783 // The object is destroyed when the handler exits, after the destruction
10784 // of any automatic objects initialized within the handler.
10785 //
10786 // We just pretend to initialize the object with itself, then make sure
10787 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +000010788 QualType initType = ExDeclType;
10789
10790 InitializedEntity entity =
10791 InitializedEntity::InitializeVariable(ExDecl);
10792 InitializationKind initKind =
10793 InitializationKind::CreateCopy(Loc, SourceLocation());
10794
10795 Expr *opaqueValue =
10796 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +000010797 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10798 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
John McCalle996ffd2011-02-16 08:02:54 +000010799 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +000010800 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +000010801 else {
10802 // If the constructor used was non-trivial, set this as the
10803 // "initializer".
10804 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10805 if (!construct->getConstructor()->isTrivial()) {
10806 Expr *init = MaybeCreateExprWithCleanups(construct);
10807 ExDecl->setInit(init);
10808 }
10809
10810 // And make sure it's destructable.
10811 FinalizeVarWithDestructor(ExDecl, recordType);
10812 }
Douglas Gregor6d182892010-03-05 23:38:39 +000010813 }
10814 }
10815
Douglas Gregord308e622009-05-18 20:51:54 +000010816 if (Invalid)
10817 ExDecl->setInvalidDecl();
10818
10819 return ExDecl;
10820}
10821
10822/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10823/// handler.
John McCalld226f652010-08-21 09:40:31 +000010824Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +000010825 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +000010826 bool Invalid = D.isInvalidType();
10827
10828 // Check for unexpanded parameter packs.
Jordan Rose41f3f3a2013-03-05 01:27:54 +000010829 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10830 UPPC_ExceptionType)) {
Douglas Gregora669c532010-12-16 17:48:04 +000010831 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10832 D.getIdentifierLoc());
10833 Invalid = true;
10834 }
10835
Sebastian Redl4b07b292008-12-22 19:15:10 +000010836 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +000010837 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +000010838 LookupOrdinaryName,
10839 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010840 // The scope should be freshly made just for us. There is just no way
10841 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +000010842 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +000010843 if (PrevDecl->isTemplateParameter()) {
10844 // Maybe we will complain about the shadowed template parameter.
10845 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +000010846 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010847 }
10848 }
10849
Chris Lattnereaaebc72009-04-25 08:06:05 +000010850 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +000010851 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10852 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +000010853 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010854 }
10855
Douglas Gregor83cb9422010-09-09 17:09:21 +000010856 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +000010857 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +000010858 D.getIdentifierLoc(),
10859 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +000010860 if (Invalid)
10861 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000010862
Sebastian Redl4b07b292008-12-22 19:15:10 +000010863 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +000010864 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +000010865 PushOnScopeChains(ExDecl, S);
10866 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010867 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +000010868
Douglas Gregor9cdda0c2009-06-17 21:51:59 +000010869 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +000010870 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +000010871}
Anders Carlssonfb311762009-03-14 00:25:26 +000010872
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010873Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010874 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +000010875 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010876 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +000010877 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +000010878
Richard Smithe3f470a2012-07-11 22:37:56 +000010879 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10880 return 0;
10881
10882 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10883 AssertMessage, RParenLoc, false);
10884}
10885
10886Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10887 Expr *AssertExpr,
10888 StringLiteral *AssertMessage,
10889 SourceLocation RParenLoc,
10890 bool Failed) {
10891 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10892 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +000010893 // In a static_assert-declaration, the constant-expression shall be a
10894 // constant expression that can be contextually converted to bool.
10895 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10896 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010897 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +000010898
Richard Smithdaaefc52011-12-14 23:32:26 +000010899 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +000010900 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +000010901 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +000010902 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +000010903 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +000010904
Richard Smithe3f470a2012-07-11 22:37:56 +000010905 if (!Failed && !Cond) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010906 SmallString<256> MsgBuffer;
Richard Smith0cc323c2012-03-05 23:20:05 +000010907 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +000010908 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010909 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +000010910 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +000010911 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +000010912 }
Anders Carlssonc3082412009-03-14 00:33:21 +000010913 }
Mike Stump1eb44332009-09-09 15:08:12 +000010914
Abramo Bagnaraa2026c92011-03-08 16:41:52 +000010915 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +000010916 AssertExpr, AssertMessage, RParenLoc,
10917 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +000010918
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000010919 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +000010920 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +000010921}
Sebastian Redl50de12f2009-03-24 22:27:57 +000010922
Douglas Gregor1d869352010-04-07 16:53:43 +000010923/// \brief Perform semantic analysis of the given friend type declaration.
10924///
10925/// \returns A friend declaration that.
Richard Smithd6f80da2012-09-20 01:31:00 +000010926FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
Abramo Bagnara0216df82011-10-29 20:52:52 +000010927 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010928 TypeSourceInfo *TSInfo) {
10929 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10930
10931 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +000010932 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +000010933
Richard Smith6b130222011-10-18 21:39:00 +000010934 // C++03 [class.friend]p2:
10935 // An elaborated-type-specifier shall be used in a friend declaration
10936 // for a class.*
10937 //
10938 // * The class-key of the elaborated-type-specifier is required.
10939 if (!ActiveTemplateInstantiations.empty()) {
10940 // Do not complain about the form of friend template types during
10941 // template instantiation; we will already have complained when the
10942 // template was declared.
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010943 } else {
10944 if (!T->isElaboratedTypeSpecifier()) {
10945 // If we evaluated the type to a record type, suggest putting
10946 // a tag in front.
10947 if (const RecordType *RT = T->getAs<RecordType>()) {
10948 RecordDecl *RD = RT->getDecl();
Richard Smith6b130222011-10-18 21:39:00 +000010949
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010950 std::string InsertionText = std::string(" ") + RD->getKindName();
Richard Smith6b130222011-10-18 21:39:00 +000010951
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010952 Diag(TypeRange.getBegin(),
10953 getLangOpts().CPlusPlus11 ?
10954 diag::warn_cxx98_compat_unelaborated_friend_type :
10955 diag::ext_unelaborated_friend_type)
10956 << (unsigned) RD->getTagKind()
10957 << T
10958 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10959 InsertionText);
10960 } else {
10961 Diag(FriendLoc,
10962 getLangOpts().CPlusPlus11 ?
10963 diag::warn_cxx98_compat_nonclass_type_friend :
10964 diag::ext_nonclass_type_friend)
10965 << T
10966 << TypeRange;
10967 }
10968 } else if (T->getAs<EnumType>()) {
Richard Smith6b130222011-10-18 21:39:00 +000010969 Diag(FriendLoc,
Richard Smith80ad52f2013-01-02 11:42:31 +000010970 getLangOpts().CPlusPlus11 ?
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010971 diag::warn_cxx98_compat_enum_friend :
10972 diag::ext_enum_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +000010973 << T
Richard Smithd6f80da2012-09-20 01:31:00 +000010974 << TypeRange;
Douglas Gregor1d869352010-04-07 16:53:43 +000010975 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010976
Nick Lewyckyce6a10e2013-02-06 05:59:33 +000010977 // C++11 [class.friend]p3:
10978 // A friend declaration that does not declare a function shall have one
10979 // of the following forms:
10980 // friend elaborated-type-specifier ;
10981 // friend simple-type-specifier ;
10982 // friend typename-specifier ;
10983 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10984 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10985 }
Richard Smithd6f80da2012-09-20 01:31:00 +000010986
Douglas Gregor06245bf2010-04-07 17:57:12 +000010987 // If the type specifier in a friend declaration designates a (possibly
Richard Smithd6f80da2012-09-20 01:31:00 +000010988 // cv-qualified) class type, that class is declared as a friend; otherwise,
Douglas Gregor06245bf2010-04-07 17:57:12 +000010989 // the friend declaration is ignored.
Richard Smithd6f80da2012-09-20 01:31:00 +000010990 return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010991}
10992
John McCall9a34edb2010-10-19 01:40:49 +000010993/// Handle a friend tag declaration where the scope specifier was
10994/// templated.
10995Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10996 unsigned TagSpec, SourceLocation TagLoc,
10997 CXXScopeSpec &SS,
Enea Zaffanella8c840282013-01-31 09:54:08 +000010998 IdentifierInfo *Name,
10999 SourceLocation NameLoc,
John McCall9a34edb2010-10-19 01:40:49 +000011000 AttributeList *Attr,
11001 MultiTemplateParamsArg TempParamLists) {
11002 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11003
11004 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000011005 bool Invalid = false;
11006
Robert Wilhelm1169e2f2013-07-21 15:20:44 +000011007 if (TemplateParameterList *TemplateParams =
11008 MatchTemplateParametersToScopeSpecifier(
11009 TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11010 isExplicitSpecialization, Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000011011 if (TemplateParams->size() > 0) {
11012 // This is a declaration of a class template.
11013 if (Invalid)
11014 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000011015
Eric Christopher4110e132011-07-21 05:34:24 +000011016 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11017 SS, Name, NameLoc, Attr,
11018 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000011019 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000011020 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011021 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +000011022 } else {
11023 // The "template<>" header is extraneous.
11024 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11025 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11026 isExplicitSpecialization = true;
11027 }
11028 }
11029
11030 if (Invalid) return 0;
11031
John McCall9a34edb2010-10-19 01:40:49 +000011032 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000011033 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011034 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +000011035 isAllExplicitSpecializations = false;
11036 break;
11037 }
11038 }
11039
11040 // FIXME: don't ignore attributes.
11041
11042 // If it's explicit specializations all the way down, just forget
11043 // about the template header and build an appropriate non-templated
11044 // friend. TODO: for source fidelity, remember the headers.
11045 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011046 if (SS.isEmpty()) {
11047 bool Owned = false;
11048 bool IsDependent = false;
11049 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11050 Attr, AS_public,
11051 /*ModulePrivateLoc=*/SourceLocation(),
11052 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000011053 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011054 /*ScopedEnumUsesClassTag=*/false,
11055 /*UnderlyingType=*/TypeResult());
11056 }
11057
Douglas Gregor2494dd02011-03-01 01:34:45 +000011058 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000011059 ElaboratedTypeKeyword Keyword
11060 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011061 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000011062 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011063 if (T.isNull())
11064 return 0;
11065
11066 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11067 if (isa<DependentNameType>(T)) {
David Blaikie39e6ab42013-02-18 22:06:02 +000011068 DependentNameTypeLoc TL =
11069 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011070 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011071 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011072 TL.setNameLoc(NameLoc);
11073 } else {
David Blaikie39e6ab42013-02-18 22:06:02 +000011074 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011075 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000011076 TL.setQualifierLoc(QualifierLoc);
David Blaikie39e6ab42013-02-18 22:06:02 +000011077 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000011078 }
11079
11080 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011081 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011082 Friend->setAccess(AS_public);
11083 CurContext->addDecl(Friend);
11084 return Friend;
11085 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000011086
11087 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11088
11089
John McCall9a34edb2010-10-19 01:40:49 +000011090
11091 // Handle the case of a templated-scope friend class. e.g.
11092 // template <class T> class A<T>::B;
11093 // FIXME: we don't support these right now.
11094 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11095 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11096 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
David Blaikie39e6ab42013-02-18 22:06:02 +000011097 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
Abramo Bagnara38a42912012-02-06 19:09:27 +000011098 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000011099 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000011100 TL.setNameLoc(NameLoc);
11101
11102 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
Enea Zaffanella8c840282013-01-31 09:54:08 +000011103 TSI, FriendLoc, TempParamLists);
John McCall9a34edb2010-10-19 01:40:49 +000011104 Friend->setAccess(AS_public);
11105 Friend->setUnsupportedFriend(true);
11106 CurContext->addDecl(Friend);
11107 return Friend;
11108}
11109
11110
John McCalldd4a3b02009-09-16 22:47:08 +000011111/// Handle a friend type declaration. This works in tandem with
11112/// ActOnTag.
11113///
11114/// Notes on friend class templates:
11115///
11116/// We generally treat friend class declarations as if they were
11117/// declaring a class. So, for example, the elaborated type specifier
11118/// in a friend declaration is required to obey the restrictions of a
11119/// class-head (i.e. no typedefs in the scope chain), template
11120/// parameters are required to match up with simple template-ids, &c.
11121/// However, unlike when declaring a template specialization, it's
11122/// okay to refer to a template specialization without an empty
11123/// template parameter declaration, e.g.
11124/// friend class A<T>::B<unsigned>;
11125/// We permit this as a special case; if there are any template
11126/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000011127/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000011128Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000011129 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000011130 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000011131
11132 assert(DS.isFriendSpecified());
11133 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11134
John McCalldd4a3b02009-09-16 22:47:08 +000011135 // Try to convert the decl specifier to a type. This works for
11136 // friend templates because ActOnTag never produces a ClassTemplateDecl
11137 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000011138 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000011139 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11140 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000011141 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000011142 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011143
Douglas Gregor6ccab972010-12-16 01:14:37 +000011144 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11145 return 0;
11146
John McCalldd4a3b02009-09-16 22:47:08 +000011147 // This is definitely an error in C++98. It's probably meant to
11148 // be forbidden in C++0x, too, but the specification is just
11149 // poorly written.
11150 //
11151 // The problem is with declarations like the following:
11152 // template <T> friend A<T>::foo;
11153 // where deciding whether a class C is a friend or not now hinges
11154 // on whether there exists an instantiation of A that causes
11155 // 'foo' to equal C. There are restrictions on class-heads
11156 // (which we declare (by fiat) elaborated friend declarations to
11157 // be) that makes this tractable.
11158 //
11159 // FIXME: handle "template <> friend class A<T>;", which
11160 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000011161 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000011162 Diag(Loc, diag::err_tagless_friend_type_template)
11163 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000011164 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000011165 }
Douglas Gregor1d869352010-04-07 16:53:43 +000011166
John McCall02cace72009-08-28 07:59:38 +000011167 // C++98 [class.friend]p1: A friend of a class is a function
11168 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000011169 // This is fixed in DR77, which just barely didn't make the C++03
11170 // deadline. It's also a very silly restriction that seriously
11171 // affects inner classes and which nobody else seems to implement;
11172 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000011173 //
11174 // But note that we could warn about it: it's always useless to
11175 // friend one of your own members (it's not, however, worthless to
11176 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000011177
John McCalldd4a3b02009-09-16 22:47:08 +000011178 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000011179 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000011180 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000011181 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000011182 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000011183 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000011184 DS.getFriendSpecLoc());
11185 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000011186 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000011187
11188 if (!D)
John McCalld226f652010-08-21 09:40:31 +000011189 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000011190
John McCalldd4a3b02009-09-16 22:47:08 +000011191 D->setAccess(AS_public);
11192 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000011193
John McCalld226f652010-08-21 09:40:31 +000011194 return D;
John McCall02cace72009-08-28 07:59:38 +000011195}
11196
Rafael Espindolafc35cbc2013-01-08 20:44:06 +000011197NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11198 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000011199 const DeclSpec &DS = D.getDeclSpec();
11200
11201 assert(DS.isFriendSpecified());
11202 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11203
11204 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000011205 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000011206
11207 // C++ [class.friend]p1
11208 // A friend of a class is a function or class....
11209 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000011210 // It *doesn't* see through dependent types, which is correct
11211 // according to [temp.arg.type]p3:
11212 // If a declaration acquires a function type through a
11213 // type dependent on a template-parameter and this causes
11214 // a declaration that does not use the syntactic form of a
11215 // function declarator to have a function type, the program
11216 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011217 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000011218 Diag(Loc, diag::err_unexpected_friend);
11219
11220 // It might be worthwhile to try to recover by creating an
11221 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000011222 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011223 }
11224
11225 // C++ [namespace.memdef]p3
11226 // - If a friend declaration in a non-local class first declares a
11227 // class or function, the friend class or function is a member
11228 // of the innermost enclosing namespace.
11229 // - The name of the friend is not found by simple name lookup
11230 // until a matching declaration is provided in that namespace
11231 // scope (either before or after the class declaration granting
11232 // friendship).
11233 // - If a friend function is called, its name may be found by the
11234 // name lookup that considers functions from namespaces and
11235 // classes associated with the types of the function arguments.
11236 // - When looking for a prior declaration of a class or a function
11237 // declared as a friend, scopes outside the innermost enclosing
11238 // namespace scope are not considered.
11239
John McCall337ec3d2010-10-12 23:13:28 +000011240 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000011241 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11242 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000011243 assert(Name);
11244
Douglas Gregor6ccab972010-12-16 01:14:37 +000011245 // Check for unexpanded parameter packs.
11246 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11247 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11248 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11249 return 0;
11250
John McCall67d1a672009-08-06 02:15:43 +000011251 // The context we found the declaration in, or in which we should
11252 // create the declaration.
11253 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000011254 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000011255 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000011256 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000011257
Richard Smith4e9686b2013-08-09 04:35:01 +000011258 // There are five cases here.
11259 // - There's no scope specifier and we're in a local class. Only look
11260 // for functions declared in the immediately-enclosing block scope.
11261 // We recover from invalid scope qualifiers as if they just weren't there.
11262 FunctionDecl *FunctionContainingLocalClass = 0;
11263 if ((SS.isInvalid() || !SS.isSet()) &&
11264 (FunctionContainingLocalClass =
11265 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11266 // C++11 [class.friend]p11:
John McCall29ae6e52010-10-13 05:45:15 +000011267 // If a friend declaration appears in a local class and the name
11268 // specified is an unqualified name, a prior declaration is
11269 // looked up without considering scopes that are outside the
11270 // innermost enclosing non-class scope. For a friend function
11271 // declaration, if there is no prior declaration, the program is
11272 // ill-formed.
Richard Smith4e9686b2013-08-09 04:35:01 +000011273
11274 // Find the innermost enclosing non-class scope. This is the block
11275 // scope containing the local class definition (or for a nested class,
11276 // the outer local class).
11277 DCScope = S->getFnParent();
11278
11279 // Look up the function name in the scope.
11280 Previous.clear(LookupLocalFriendName);
11281 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11282
11283 if (!Previous.empty()) {
11284 // All possible previous declarations must have the same context:
11285 // either they were declared at block scope or they are members of
11286 // one of the enclosing local classes.
11287 DC = Previous.getRepresentativeDecl()->getDeclContext();
11288 } else {
11289 // This is ill-formed, but provide the context that we would have
11290 // declared the function in, if we were permitted to, for error recovery.
11291 DC = FunctionContainingLocalClass;
11292 }
11293
11294 // C++ [class.friend]p6:
11295 // A function can be defined in a friend declaration of a class if and
11296 // only if the class is a non-local class (9.8), the function name is
11297 // unqualified, and the function has namespace scope.
11298 if (D.isFunctionDefinition()) {
11299 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11300 }
11301
11302 // - There's no scope specifier, in which case we just go to the
11303 // appropriate scope and look for a function or function template
11304 // there as appropriate.
11305 } else if (SS.isInvalid() || !SS.isSet()) {
11306 // C++11 [namespace.memdef]p3:
11307 // If the name in a friend declaration is neither qualified nor
11308 // a template-id and the declaration is a function or an
11309 // elaborated-type-specifier, the lookup to determine whether
11310 // the entity has been previously declared shall not consider
11311 // any scopes outside the innermost enclosing namespace.
John McCall8a407372010-10-14 22:22:28 +000011312 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000011313
John McCall29ae6e52010-10-13 05:45:15 +000011314 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000011315 DC = CurContext;
John McCall67d1a672009-08-06 02:15:43 +000011316
Rafael Espindola11dc6342013-04-25 20:12:36 +000011317 // Skip class contexts. If someone can cite chapter and verse
11318 // for this behavior, that would be nice --- it's what GCC and
11319 // EDG do, and it seems like a reasonable intent, but the spec
11320 // really only says that checks for unqualified existing
11321 // declarations should stop at the nearest enclosing namespace,
11322 // not that they should only consider the nearest enclosing
11323 // namespace.
11324 while (DC->isRecord())
11325 DC = DC->getParent();
11326
11327 DeclContext *LookupDC = DC;
11328 while (LookupDC->isTransparentContext())
11329 LookupDC = LookupDC->getParent();
11330
11331 while (true) {
11332 LookupQualifiedName(Previous, LookupDC);
John McCall67d1a672009-08-06 02:15:43 +000011333
Rafael Espindola11dc6342013-04-25 20:12:36 +000011334 if (!Previous.empty()) {
11335 DC = LookupDC;
11336 break;
John McCall8a407372010-10-14 22:22:28 +000011337 }
Rafael Espindola11dc6342013-04-25 20:12:36 +000011338
11339 if (isTemplateId) {
11340 if (isa<TranslationUnitDecl>(LookupDC)) break;
11341 } else {
11342 if (LookupDC->isFileContext()) break;
11343 }
11344 LookupDC = LookupDC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000011345 }
11346
John McCall380aaa42010-10-13 06:22:15 +000011347 DCScope = getScopeForDeclContext(S, DC);
Richard Smith4e9686b2013-08-09 04:35:01 +000011348
John McCall337ec3d2010-10-12 23:13:28 +000011349 // - There's a non-dependent scope specifier, in which case we
11350 // compute it and do a previous lookup there for a function
11351 // or function template.
11352 } else if (!SS.getScopeRep()->isDependent()) {
11353 DC = computeDeclContext(SS);
11354 if (!DC) return 0;
11355
11356 if (RequireCompleteDeclContext(SS, DC)) return 0;
11357
11358 LookupQualifiedName(Previous, DC);
11359
11360 // Ignore things found implicitly in the wrong scope.
11361 // TODO: better diagnostics for this case. Suggesting the right
11362 // qualified scope would be nice...
11363 LookupResult::Filter F = Previous.makeFilter();
11364 while (F.hasNext()) {
11365 NamedDecl *D = F.next();
11366 if (!DC->InEnclosingNamespaceSetOf(
11367 D->getDeclContext()->getRedeclContext()))
11368 F.erase();
11369 }
11370 F.done();
11371
11372 if (Previous.empty()) {
11373 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011374 Diag(Loc, diag::err_qualified_friend_not_found)
11375 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000011376 return 0;
11377 }
11378
11379 // C++ [class.friend]p1: A friend of a class is a function or
11380 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000011381 if (DC->Equals(CurContext))
11382 Diag(DS.getFriendSpecLoc(),
Richard Smith80ad52f2013-01-02 11:42:31 +000011383 getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +000011384 diag::warn_cxx98_compat_friend_is_member :
11385 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000011386
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011387 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011388 // C++ [class.friend]p6:
11389 // A function can be defined in a friend declaration of a class if and
11390 // only if the class is a non-local class (9.8), the function name is
11391 // unqualified, and the function has namespace scope.
11392 SemaDiagnosticBuilder DB
11393 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11394
11395 DB << SS.getScopeRep();
11396 if (DC->isFileContext())
11397 DB << FixItHint::CreateRemoval(SS.getRange());
11398 SS.clear();
11399 }
John McCall337ec3d2010-10-12 23:13:28 +000011400
11401 // - There's a scope specifier that does not match any template
11402 // parameter lists, in which case we use some arbitrary context,
11403 // create a method or method template, and wait for instantiation.
11404 // - There's a scope specifier that does match some template
11405 // parameter lists, which we don't handle right now.
11406 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011407 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000011408 // C++ [class.friend]p6:
11409 // A function can be defined in a friend declaration of a class if and
11410 // only if the class is a non-local class (9.8), the function name is
11411 // unqualified, and the function has namespace scope.
11412 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11413 << SS.getScopeRep();
11414 }
11415
John McCall337ec3d2010-10-12 23:13:28 +000011416 DC = CurContext;
11417 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000011418 }
Douglas Gregor883af832011-10-10 01:11:59 +000011419
John McCall29ae6e52010-10-13 05:45:15 +000011420 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000011421 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011422 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11423 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11424 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000011425 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000011426 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11427 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000011428 return 0;
John McCall67d1a672009-08-06 02:15:43 +000011429 }
John McCall67d1a672009-08-06 02:15:43 +000011430 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011431
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000011432 // FIXME: This is an egregious hack to cope with cases where the scope stack
11433 // does not contain the declaration context, i.e., in an out-of-line
11434 // definition of a class.
11435 Scope FakeDCScope(S, Scope::DeclScope, Diags);
11436 if (!DCScope) {
11437 FakeDCScope.setEntity(DC);
11438 DCScope = &FakeDCScope;
11439 }
Richard Smith4e9686b2013-08-09 04:35:01 +000011440
Francois Pichetaf0f4d02011-08-14 03:52:19 +000011441 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000011442 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011443 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000011444 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000011445
Douglas Gregor182ddf02009-09-28 00:08:27 +000011446 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000011447
Richard Smith4e9686b2013-08-09 04:35:01 +000011448 // If we performed typo correction, we might have added a scope specifier
11449 // and changed the decl context.
11450 DC = ND->getDeclContext();
11451
John McCallab88d972009-08-31 22:39:49 +000011452 // Add the function declaration to the appropriate lookup tables,
11453 // adjusting the redeclarations list as necessary. We don't
11454 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000011455 //
John McCallab88d972009-08-31 22:39:49 +000011456 // Also update the scope-based lookup if the target context's
11457 // lookup context is in lexical scope.
11458 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000011459 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000011460 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000011461 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000011462 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000011463 }
John McCall02cace72009-08-28 07:59:38 +000011464
11465 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000011466 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000011467 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000011468 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000011469 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000011470
John McCall1f2e1a92012-08-10 03:15:35 +000011471 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000011472 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000011473 } else {
11474 if (DC->isRecord()) CheckFriendAccess(ND);
11475
John McCall6102ca12010-10-16 06:59:13 +000011476 FunctionDecl *FD;
11477 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11478 FD = FTD->getTemplatedDecl();
11479 else
11480 FD = cast<FunctionDecl>(ND);
11481
David Majnemerf6a144f2013-06-25 23:09:30 +000011482 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11483 // default argument expression, that declaration shall be a definition
11484 // and shall be the only declaration of the function or function
11485 // template in the translation unit.
11486 if (functionDeclHasDefaultArgument(FD)) {
11487 if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11488 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11489 Diag(OldFD->getLocation(), diag::note_previous_declaration);
11490 } else if (!D.isFunctionDefinition())
11491 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11492 }
11493
John McCall6102ca12010-10-16 06:59:13 +000011494 // Mark templated-scope function declarations as unsupported.
11495 if (FD->getNumTemplateParameterLists())
11496 FrD->setUnsupportedFriend(true);
11497 }
John McCall337ec3d2010-10-12 23:13:28 +000011498
John McCalld226f652010-08-21 09:40:31 +000011499 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000011500}
11501
John McCalld226f652010-08-21 09:40:31 +000011502void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11503 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000011504
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011505 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
Sebastian Redl50de12f2009-03-24 22:27:57 +000011506 if (!Fn) {
11507 Diag(DelLoc, diag::err_deleted_non_function);
11508 return;
11509 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011510
Douglas Gregoref96ee02012-01-14 16:38:05 +000011511 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011512 // Don't consider the implicit declaration we generate for explicit
11513 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000011514 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11515 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000011516 Diag(DelLoc, diag::err_deleted_decl_not_first);
11517 Diag(Prev->getLocation(), diag::note_previous_declaration);
11518 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000011519 // If the declaration wasn't the first, we delete the function anyway for
11520 // recovery.
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011521 Fn = Fn->getCanonicalDecl();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011522 }
Richard Smith0ab5b4c2013-04-02 19:38:47 +000011523
11524 if (Fn->isDeleted())
11525 return;
11526
11527 // See if we're deleting a function which is already known to override a
11528 // non-deleted virtual function.
11529 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11530 bool IssuedDiagnostic = false;
11531 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11532 E = MD->end_overridden_methods();
11533 I != E; ++I) {
11534 if (!(*MD->begin_overridden_methods())->isDeleted()) {
11535 if (!IssuedDiagnostic) {
11536 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11537 IssuedDiagnostic = true;
11538 }
11539 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11540 }
11541 }
11542 }
11543
Sean Hunt10620eb2011-05-06 20:44:56 +000011544 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000011545}
Sebastian Redl13e88542009-04-27 21:33:24 +000011546
Sean Hunte4246a62011-05-12 06:15:49 +000011547void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
Aaron Ballmanafb7ce32013-01-16 23:39:10 +000011548 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
Sean Hunte4246a62011-05-12 06:15:49 +000011549
11550 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000011551 if (MD->getParent()->isDependentType()) {
11552 MD->setDefaulted();
11553 MD->setExplicitlyDefaulted();
11554 return;
11555 }
11556
Sean Hunte4246a62011-05-12 06:15:49 +000011557 CXXSpecialMember Member = getSpecialMember(MD);
11558 if (Member == CXXInvalid) {
Eli Friedmanfcb5a252013-07-11 23:55:07 +000011559 if (!MD->isInvalidDecl())
11560 Diag(DefaultLoc, diag::err_default_special_members);
Sean Hunte4246a62011-05-12 06:15:49 +000011561 return;
11562 }
11563
11564 MD->setDefaulted();
11565 MD->setExplicitlyDefaulted();
11566
Sean Huntcd10dec2011-05-23 23:14:04 +000011567 // If this definition appears within the record, do the checking when
11568 // the record is complete.
11569 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000011570 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000011571 // Find the uninstantiated declaration that actually had the '= default'
11572 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000011573 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000011574
Richard Smith12fef492013-03-27 00:22:47 +000011575 // If the method was defaulted on its first declaration, we will have
11576 // already performed the checking in CheckCompletedCXXClass. Such a
11577 // declaration doesn't trigger an implicit definition.
Sean Huntcd10dec2011-05-23 23:14:04 +000011578 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000011579 return;
11580
Richard Smithb9d0b762012-07-27 04:22:15 +000011581 CheckExplicitlyDefaultedSpecialMember(MD);
11582
Richard Smith1d28caf2012-12-11 01:14:52 +000011583 // The exception specification is needed because we are defining the
11584 // function.
11585 ResolveExceptionSpec(DefaultLoc,
11586 MD->getType()->castAs<FunctionProtoType>());
11587
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011588 if (MD->isInvalidDecl())
11589 return;
11590
Sean Hunte4246a62011-05-12 06:15:49 +000011591 switch (Member) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011592 case CXXDefaultConstructor:
11593 DefineImplicitDefaultConstructor(DefaultLoc,
11594 cast<CXXConstructorDecl>(MD));
Sean Hunt49634cf2011-05-13 06:10:58 +000011595 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011596 case CXXCopyConstructor:
11597 DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunte4246a62011-05-12 06:15:49 +000011598 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011599 case CXXCopyAssignment:
11600 DefineImplicitCopyAssignment(DefaultLoc, MD);
Sean Hunt2b188082011-05-14 05:23:28 +000011601 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011602 case CXXDestructor:
11603 DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
Sean Huntcb45a0f2011-05-12 22:46:25 +000011604 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011605 case CXXMoveConstructor:
11606 DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
Sean Hunt82713172011-05-25 23:16:36 +000011607 break;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011608 case CXXMoveAssignment:
11609 DefineImplicitMoveAssignment(DefaultLoc, MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011610 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000011611 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000011612 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000011613 }
11614 } else {
11615 Diag(DefaultLoc, diag::err_default_special_members);
11616 }
11617}
11618
Sebastian Redl13e88542009-04-27 21:33:24 +000011619static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000011620 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000011621 Stmt *SubStmt = *CI;
11622 if (!SubStmt)
11623 continue;
11624 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000011625 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000011626 diag::err_return_in_constructor_handler);
11627 if (!isa<Expr>(SubStmt))
11628 SearchForReturnInStmt(Self, SubStmt);
11629 }
11630}
11631
11632void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11633 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11634 CXXCatchStmt *Handler = TryBlock->getHandler(I);
11635 SearchForReturnInStmt(*this, Handler);
11636 }
11637}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011638
David Blaikie299adab2013-01-18 23:03:15 +000011639bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
Aaron Ballmanfff32482012-12-09 17:45:41 +000011640 const CXXMethodDecl *Old) {
11641 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11642 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11643
11644 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11645
11646 // If the calling conventions match, everything is fine
11647 if (NewCC == OldCC)
11648 return false;
11649
11650 // If either of the calling conventions are set to "default", we need to pick
11651 // something more sensible based on the target. This supports code where the
11652 // one method explicitly sets thiscall, and another has no explicit calling
11653 // convention.
11654 CallingConv Default =
11655 Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11656 if (NewCC == CC_Default)
11657 NewCC = Default;
11658 if (OldCC == CC_Default)
11659 OldCC = Default;
11660
11661 // If the calling conventions still don't match, then report the error
11662 if (NewCC != OldCC) {
David Blaikie299adab2013-01-18 23:03:15 +000011663 Diag(New->getLocation(),
11664 diag::err_conflicting_overriding_cc_attributes)
11665 << New->getDeclName() << New->getType() << Old->getType();
11666 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11667 return true;
Aaron Ballmanfff32482012-12-09 17:45:41 +000011668 }
11669
11670 return false;
11671}
11672
Mike Stump1eb44332009-09-09 15:08:12 +000011673bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011674 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000011675 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11676 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011677
Chandler Carruth73857792010-02-15 11:53:20 +000011678 if (Context.hasSameType(NewTy, OldTy) ||
11679 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011680 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000011681
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011682 // Check if the return types are covariant
11683 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000011684
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011685 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011686 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11687 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011688 NewClassTy = NewPT->getPointeeType();
11689 OldClassTy = OldPT->getPointeeType();
11690 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011691 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11692 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11693 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11694 NewClassTy = NewRT->getPointeeType();
11695 OldClassTy = OldRT->getPointeeType();
11696 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011697 }
11698 }
Mike Stump1eb44332009-09-09 15:08:12 +000011699
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011700 // The return types aren't either both pointers or references to a class type.
11701 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000011702 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011703 diag::err_different_return_type_for_overriding_virtual_function)
11704 << New->getDeclName() << NewTy << OldTy;
11705 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000011706
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011707 return true;
11708 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011709
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011710 // C++ [class.virtual]p6:
11711 // If the return type of D::f differs from the return type of B::f, the
11712 // class type in the return type of D::f shall be complete at the point of
11713 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000011714 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11715 if (!RT->isBeingDefined() &&
11716 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000011717 diag::err_covariant_return_incomplete,
11718 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011719 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000011720 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000011721
Douglas Gregora4923eb2009-11-16 21:35:15 +000011722 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011723 // Check if the new class derives from the old class.
11724 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11725 Diag(New->getLocation(),
11726 diag::err_covariant_return_not_derived)
11727 << New->getDeclName() << NewTy << OldTy;
11728 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11729 return true;
11730 }
Mike Stump1eb44332009-09-09 15:08:12 +000011731
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011732 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000011733 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000011734 diag::err_covariant_return_inaccessible_base,
11735 diag::err_covariant_return_ambiguous_derived_to_base_conv,
11736 // FIXME: Should this point to the return type?
11737 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000011738 // FIXME: this note won't trigger for delayed access control
11739 // diagnostics, and it's impossible to get an undelayed error
11740 // here from access control during the original parse because
11741 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011742 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11743 return true;
11744 }
11745 }
Mike Stump1eb44332009-09-09 15:08:12 +000011746
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011747 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000011748 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011749 Diag(New->getLocation(),
11750 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011751 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011752 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11753 return true;
11754 };
Mike Stump1eb44332009-09-09 15:08:12 +000011755
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011756
11757 // The new class type must have the same or less qualifiers as the old type.
11758 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11759 Diag(New->getLocation(),
11760 diag::err_covariant_return_type_class_type_more_qualified)
11761 << New->getDeclName() << NewTy << OldTy;
11762 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11763 return true;
11764 };
Mike Stump1eb44332009-09-09 15:08:12 +000011765
Anders Carlssonc3a68b22009-05-14 19:52:19 +000011766 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000011767}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011768
Douglas Gregor4ba31362009-12-01 17:24:26 +000011769/// \brief Mark the given method pure.
11770///
11771/// \param Method the method to be marked pure.
11772///
11773/// \param InitRange the source range that covers the "0" initializer.
11774bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000011775 SourceLocation EndLoc = InitRange.getEnd();
11776 if (EndLoc.isValid())
11777 Method->setRangeEnd(EndLoc);
11778
Douglas Gregor4ba31362009-12-01 17:24:26 +000011779 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11780 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000011781 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000011782 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000011783
11784 if (!Method->isInvalidDecl())
11785 Diag(Method->getLocation(), diag::err_non_virtual_pure)
11786 << Method->getDeclName() << InitRange;
11787 return true;
11788}
11789
Douglas Gregor552e2992012-02-21 02:22:07 +000011790/// \brief Determine whether the given declaration is a static data member.
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011791static bool isStaticDataMember(const Decl *D) {
11792 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
11793 return Var->isStaticDataMember();
11794
11795 return false;
Douglas Gregor552e2992012-02-21 02:22:07 +000011796}
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000011797
John McCall731ad842009-12-19 09:28:58 +000011798/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11799/// an initializer for the out-of-line declaration 'Dcl'. The scope
11800/// is a fresh scope pushed for just this purpose.
11801///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011802/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11803/// static data member of class X, names should be looked up in the scope of
11804/// class X.
John McCalld226f652010-08-21 09:40:31 +000011805void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011806 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011807 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011808
John McCall731ad842009-12-19 09:28:58 +000011809 // We should only get called for declarations with scope specifiers, like:
11810 // int foo::bar;
11811 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011812 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000011813
11814 // If we are parsing the initializer for a static data member, push a
11815 // new expression evaluation context that is associated with this static
11816 // data member.
11817 if (isStaticDataMember(D))
11818 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011819}
11820
11821/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000011822/// initializer for the out-of-line declaration 'D'.
11823void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011824 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000011825 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011826
Douglas Gregor552e2992012-02-21 02:22:07 +000011827 if (isStaticDataMember(D))
11828 PopExpressionEvaluationContext();
11829
John McCall731ad842009-12-19 09:28:58 +000011830 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000011831 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000011832}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011833
11834/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11835/// C++ if/switch/while/for statement.
11836/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000011837DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011838 // C++ 6.4p2:
11839 // The declarator shall not specify a function or an array.
11840 // The type-specifier-seq shall not contain typedef and shall not declare a
11841 // new class or enumeration.
11842 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11843 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011844
11845 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000011846 if (!Dcl)
11847 return true;
11848
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000011849 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11850 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011851 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000011852 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011853 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011854
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000011855 return Dcl;
11856}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000011857
Douglas Gregordfe65432011-07-28 19:11:31 +000011858void Sema::LoadExternalVTableUses() {
11859 if (!ExternalSource)
11860 return;
11861
11862 SmallVector<ExternalVTableUse, 4> VTables;
11863 ExternalSource->ReadUsedVTables(VTables);
11864 SmallVector<VTableUse, 4> NewUses;
11865 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11866 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11867 = VTablesUsed.find(VTables[I].Record);
11868 // Even if a definition wasn't required before, it may be required now.
11869 if (Pos != VTablesUsed.end()) {
11870 if (!Pos->second && VTables[I].DefinitionRequired)
11871 Pos->second = true;
11872 continue;
11873 }
11874
11875 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11876 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11877 }
11878
11879 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11880}
11881
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011882void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11883 bool DefinitionRequired) {
11884 // Ignore any vtable uses in unevaluated operands or for classes that do
11885 // not have a vtable.
11886 if (!Class->isDynamicClass() || Class->isDependentContext() ||
John McCallaeeacf72013-05-03 00:10:13 +000011887 CurContext->isDependentContext() || isUnevaluatedContext())
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000011888 return;
11889
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011890 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000011891 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011892 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11893 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11894 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11895 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000011896 // If we already had an entry, check to see if we are promoting this vtable
11897 // to required a definition. If so, we need to reappend to the VTableUses
11898 // list, since we may have already processed the first entry.
11899 if (DefinitionRequired && !Pos.first->second) {
11900 Pos.first->second = true;
11901 } else {
11902 // Otherwise, we can early exit.
11903 return;
11904 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011905 }
11906
11907 // Local classes need to have their virtual members marked
11908 // immediately. For all other classes, we mark their virtual members
11909 // at the end of the translation unit.
11910 if (Class->isLocalClass())
11911 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000011912 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011913 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000011914}
11915
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011916bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000011917 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011918 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000011919 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000011920
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011921 // Note: The VTableUses vector could grow as a result of marking
11922 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000011923 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011924 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000011925 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011926 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000011927 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011928 if (!Class)
11929 continue;
11930
11931 SourceLocation Loc = VTableUses[I].second;
11932
Richard Smithb9d0b762012-07-27 04:22:15 +000011933 bool DefineVTable = true;
11934
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011935 // If this class has a key function, but that key function is
11936 // defined in another translation unit, we don't need to emit the
11937 // vtable even though we're using it.
John McCalld5617ee2013-01-25 22:31:03 +000011938 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000011939 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011940 switch (KeyFunction->getTemplateSpecializationKind()) {
11941 case TSK_Undeclared:
11942 case TSK_ExplicitSpecialization:
11943 case TSK_ExplicitInstantiationDeclaration:
11944 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000011945 DefineVTable = false;
11946 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011947
11948 case TSK_ExplicitInstantiationDefinition:
11949 case TSK_ImplicitInstantiation:
11950 // We will be instantiating the key function.
11951 break;
11952 }
11953 } else if (!KeyFunction) {
11954 // If we have a class with no key function that is the subject
11955 // of an explicit instantiation declaration, suppress the
11956 // vtable; it will live with the explicit instantiation
11957 // definition.
11958 bool IsExplicitInstantiationDeclaration
11959 = Class->getTemplateSpecializationKind()
11960 == TSK_ExplicitInstantiationDeclaration;
11961 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11962 REnd = Class->redecls_end();
11963 R != REnd; ++R) {
11964 TemplateSpecializationKind TSK
11965 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11966 if (TSK == TSK_ExplicitInstantiationDeclaration)
11967 IsExplicitInstantiationDeclaration = true;
11968 else if (TSK == TSK_ExplicitInstantiationDefinition) {
11969 IsExplicitInstantiationDeclaration = false;
11970 break;
11971 }
11972 }
11973
11974 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000011975 DefineVTable = false;
11976 }
11977
11978 // The exception specifications for all virtual members may be needed even
11979 // if we are not providing an authoritative form of the vtable in this TU.
11980 // We may choose to emit it available_externally anyway.
11981 if (!DefineVTable) {
11982 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11983 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011984 }
11985
11986 // Mark all of the virtual members of this class as referenced, so
11987 // that we can build a vtable. Then, tell the AST consumer that a
11988 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000011989 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011990 MarkVirtualMembersReferenced(Loc, Class);
11991 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11992 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11993
11994 // Optionally warn if we're emitting a weak vtable.
Rafael Espindola181e3ec2013-05-13 00:12:11 +000011995 if (Class->isExternallyVisible() &&
Douglas Gregor6fb745b2010-05-13 16:44:06 +000011996 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000011997 const FunctionDecl *KeyFunctionDef = 0;
11998 if (!KeyFunction ||
11999 (KeyFunction->hasBody(KeyFunctionDef) &&
12000 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000012001 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12002 TSK_ExplicitInstantiationDefinition
12003 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12004 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012005 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012006 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000012007 VTableUses.clear();
12008
Douglas Gregor78844032011-04-22 22:25:37 +000012009 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000012010}
Anders Carlssond6a637f2009-12-07 08:24:59 +000012011
Richard Smithb9d0b762012-07-27 04:22:15 +000012012void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12013 const CXXRecordDecl *RD) {
12014 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12015 E = RD->method_end(); I != E; ++I)
12016 if ((*I)->isVirtual() && !(*I)->isPure())
12017 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12018}
12019
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012020void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12021 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000012022 // Mark all functions which will appear in RD's vtable as used.
12023 CXXFinalOverriderMap FinalOverriders;
12024 RD->getFinalOverriders(FinalOverriders);
12025 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12026 E = FinalOverriders.end();
12027 I != E; ++I) {
12028 for (OverridingMethods::const_iterator OI = I->second.begin(),
12029 OE = I->second.end();
12030 OI != OE; ++OI) {
12031 assert(OI->second.size() > 0 && "no final overrider");
12032 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000012033
Richard Smithff817f72012-07-07 06:59:51 +000012034 // C++ [basic.def.odr]p2:
12035 // [...] A virtual member function is used if it is not pure. [...]
12036 if (!Overrider->isPure())
12037 MarkFunctionReferenced(Loc, Overrider);
12038 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012039 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012040
12041 // Only classes that have virtual bases need a VTT.
12042 if (RD->getNumVBases() == 0)
12043 return;
12044
12045 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12046 e = RD->bases_end(); i != e; ++i) {
12047 const CXXRecordDecl *Base =
12048 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000012049 if (Base->getNumVBases() == 0)
12050 continue;
12051 MarkVirtualMembersReferenced(Loc, Base);
12052 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000012053}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012054
12055/// SetIvarInitializers - This routine builds initialization ASTs for the
12056/// Objective-C implementation whose ivars need be initialized.
12057void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000012058 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012059 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000012060 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000012061 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012062 CollectIvarsToConstructOrDestruct(OID, ivars);
12063 if (ivars.empty())
12064 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000012065 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012066 for (unsigned i = 0; i < ivars.size(); i++) {
12067 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012068 if (Field->isInvalidDecl())
12069 continue;
12070
Sean Huntcbb67482011-01-08 20:30:50 +000012071 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012072 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12073 InitializationKind InitKind =
12074 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000012075
12076 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12077 ExprResult MemberInit =
12078 InitSeq.Perform(*this, InitEntity, InitKind, None);
Douglas Gregor53c374f2010-12-07 00:41:46 +000012079 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012080 // Note, MemberInit could actually come back empty if no initialization
12081 // is required (e.g., because it would call a trivial default constructor)
12082 if (!MemberInit.get() || MemberInit.isInvalid())
12083 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000012084
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012085 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000012086 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12087 SourceLocation(),
12088 MemberInit.takeAs<Expr>(),
12089 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012090 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012091
12092 // Be sure that the destructor is accessible and is marked as referenced.
12093 if (const RecordType *RecordTy
12094 = Context.getBaseElementType(Field->getType())
12095 ->getAs<RecordType>()) {
12096 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000012097 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000012098 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000012099 CheckDestructorAccess(Field->getLocation(), Destructor,
12100 PDiag(diag::err_access_dtor_ivar)
12101 << Context.getBaseElementType(Field->getType()));
12102 }
12103 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000012104 }
12105 ObjCImplementation->setIvarInitializers(Context,
12106 AllToInit.data(), AllToInit.size());
12107 }
12108}
Sean Huntfe57eef2011-05-04 05:57:24 +000012109
Sean Huntebcbe1d2011-05-04 23:29:54 +000012110static
12111void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12112 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12113 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12114 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12115 Sema &S) {
Sean Huntebcbe1d2011-05-04 23:29:54 +000012116 if (Ctor->isInvalidDecl())
12117 return;
12118
Richard Smitha8eaf002012-08-23 06:16:52 +000012119 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12120
12121 // Target may not be determinable yet, for instance if this is a dependent
12122 // call in an uninstantiated template.
12123 if (Target) {
12124 const FunctionDecl *FNTarget = 0;
12125 (void)Target->hasBody(FNTarget);
12126 Target = const_cast<CXXConstructorDecl*>(
12127 cast_or_null<CXXConstructorDecl>(FNTarget));
12128 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000012129
12130 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12131 // Avoid dereferencing a null pointer here.
12132 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12133
12134 if (!Current.insert(Canonical))
12135 return;
12136
12137 // We know that beyond here, we aren't chaining into a cycle.
12138 if (!Target || !Target->isDelegatingConstructor() ||
12139 Target->isInvalidDecl() || Valid.count(TCanonical)) {
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012140 Valid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012141 Current.clear();
12142 // We've hit a cycle.
12143 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12144 Current.count(TCanonical)) {
12145 // If we haven't diagnosed this cycle yet, do so now.
12146 if (!Invalid.count(TCanonical)) {
12147 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000012148 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012149 << Ctor;
12150
Richard Smitha8eaf002012-08-23 06:16:52 +000012151 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000012152 if (TCanonical != Canonical)
12153 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12154
12155 CXXConstructorDecl *C = Target;
12156 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000012157 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000012158 (void)C->getTargetConstructor()->hasBody(FNTarget);
12159 assert(FNTarget && "Ctor cycle through bodiless function");
12160
Richard Smitha8eaf002012-08-23 06:16:52 +000012161 C = const_cast<CXXConstructorDecl*>(
12162 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000012163 S.Diag(C->getLocation(), diag::note_which_delegates_to);
12164 }
12165 }
12166
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012167 Invalid.insert(Current.begin(), Current.end());
Sean Huntebcbe1d2011-05-04 23:29:54 +000012168 Current.clear();
12169 } else {
12170 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12171 }
12172}
12173
12174
Sean Huntfe57eef2011-05-04 05:57:24 +000012175void Sema::CheckDelegatingCtorCycles() {
12176 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12177
Douglas Gregor0129b562011-07-27 21:57:17 +000012178 for (DelegatingCtorDeclsType::iterator
12179 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000012180 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000012181 I != E; ++I)
12182 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000012183
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012184 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12185 CE = Invalid.end();
12186 CI != CE; ++CI)
Sean Huntebcbe1d2011-05-04 23:29:54 +000012187 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000012188}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012189
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012190namespace {
12191 /// \brief AST visitor that finds references to the 'this' expression.
12192 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12193 Sema &S;
12194
12195 public:
12196 explicit FindCXXThisExpr(Sema &S) : S(S) { }
12197
12198 bool VisitCXXThisExpr(CXXThisExpr *E) {
12199 S.Diag(E->getLocation(), diag::err_this_static_member_func)
12200 << E->isImplicit();
12201 return false;
12202 }
12203 };
12204}
12205
12206bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12207 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12208 if (!TSInfo)
12209 return false;
12210
12211 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012212 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012213 if (!ProtoTL)
12214 return false;
12215
12216 // C++11 [expr.prim.general]p3:
12217 // [The expression this] shall not appear before the optional
12218 // cv-qualifier-seq and it shall not appear within the declaration of a
12219 // static member function (although its type and value category are defined
12220 // within a static member function as they are within a non-static member
12221 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000012222 // until the complete declarator is known. - end note ]
David Blaikie39e6ab42013-02-18 22:06:02 +000012223 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012224 FindCXXThisExpr Finder(*this);
12225
12226 // If the return type came after the cv-qualifier-seq, check it now.
12227 if (Proto->hasTrailingReturn() &&
David Blaikie39e6ab42013-02-18 22:06:02 +000012228 !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012229 return true;
12230
12231 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012232 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12233 return true;
12234
12235 return checkThisInStaticMemberFunctionAttributes(Method);
12236}
12237
12238bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12239 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12240 if (!TSInfo)
12241 return false;
12242
12243 TypeLoc TL = TSInfo->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +000012244 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012245 if (!ProtoTL)
12246 return false;
12247
David Blaikie39e6ab42013-02-18 22:06:02 +000012248 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012249 FindCXXThisExpr Finder(*this);
12250
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012251 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000012252 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000012253 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012254 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012255 case EST_DynamicNone:
12256 case EST_MSAny:
12257 case EST_None:
12258 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012259
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012260 case EST_ComputedNoexcept:
12261 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12262 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012263
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012264 case EST_Dynamic:
12265 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012266 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012267 E != EEnd; ++E) {
12268 if (!Finder.TraverseType(*E))
12269 return true;
12270 }
12271 break;
12272 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012273
12274 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000012275}
12276
12277bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12278 FindCXXThisExpr Finder(*this);
12279
12280 // Check attributes.
12281 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12282 A != AEnd; ++A) {
12283 // FIXME: This should be emitted by tblgen.
12284 Expr *Arg = 0;
12285 ArrayRef<Expr *> Args;
12286 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12287 Arg = G->getArg();
12288 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12289 Arg = G->getArg();
12290 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12291 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12292 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12293 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12294 else if (ExclusiveLockFunctionAttr *ELF
12295 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12296 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12297 else if (SharedLockFunctionAttr *SLF
12298 = dyn_cast<SharedLockFunctionAttr>(*A))
12299 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12300 else if (ExclusiveTrylockFunctionAttr *ETLF
12301 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12302 Arg = ETLF->getSuccessValue();
12303 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12304 } else if (SharedTrylockFunctionAttr *STLF
12305 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12306 Arg = STLF->getSuccessValue();
12307 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12308 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12309 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12310 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12311 Arg = LR->getArg();
12312 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12313 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12314 else if (ExclusiveLocksRequiredAttr *ELR
12315 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12316 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12317 else if (SharedLocksRequiredAttr *SLR
12318 = dyn_cast<SharedLocksRequiredAttr>(*A))
12319 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12320
12321 if (Arg && !Finder.TraverseStmt(Arg))
12322 return true;
12323
12324 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12325 if (!Finder.TraverseStmt(Args[I]))
12326 return true;
12327 }
12328 }
12329
12330 return false;
12331}
12332
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012333void
12334Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12335 ArrayRef<ParsedType> DynamicExceptions,
12336 ArrayRef<SourceRange> DynamicExceptionRanges,
12337 Expr *NoexceptExpr,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000012338 SmallVectorImpl<QualType> &Exceptions,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012339 FunctionProtoType::ExtProtoInfo &EPI) {
12340 Exceptions.clear();
12341 EPI.ExceptionSpecType = EST;
12342 if (EST == EST_Dynamic) {
12343 Exceptions.reserve(DynamicExceptions.size());
12344 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12345 // FIXME: Preserve type source info.
12346 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12347
12348 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12349 collectUnexpandedParameterPacks(ET, Unexpanded);
12350 if (!Unexpanded.empty()) {
12351 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12352 UPPC_ExceptionType,
12353 Unexpanded);
12354 continue;
12355 }
12356
12357 // Check that the type is valid for an exception spec, and
12358 // drop it if not.
12359 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12360 Exceptions.push_back(ET);
12361 }
12362 EPI.NumExceptions = Exceptions.size();
12363 EPI.Exceptions = Exceptions.data();
12364 return;
12365 }
12366
12367 if (EST == EST_ComputedNoexcept) {
12368 // If an error occurred, there's no expression here.
12369 if (NoexceptExpr) {
12370 assert((NoexceptExpr->isTypeDependent() ||
12371 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12372 Context.BoolTy) &&
12373 "Parser should have made sure that the expression is boolean");
12374 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12375 EPI.ExceptionSpecType = EST_BasicNoexcept;
12376 return;
12377 }
12378
12379 if (!NoexceptExpr->isValueDependent())
12380 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000012381 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000012382 /*AllowFold*/ false).take();
12383 EPI.NoexceptExpr = NoexceptExpr;
12384 }
12385 return;
12386 }
12387}
12388
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012389/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12390Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12391 // Implicitly declared functions (e.g. copy constructors) are
12392 // __host__ __device__
12393 if (D->isImplicit())
12394 return CFT_HostDevice;
12395
12396 if (D->hasAttr<CUDAGlobalAttr>())
12397 return CFT_Global;
12398
12399 if (D->hasAttr<CUDADeviceAttr>()) {
12400 if (D->hasAttr<CUDAHostAttr>())
12401 return CFT_HostDevice;
Benjamin Kramer4c7736e2013-07-24 15:28:33 +000012402 return CFT_Device;
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000012403 }
12404
12405 return CFT_Host;
12406}
12407
12408bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12409 CUDAFunctionTarget CalleeTarget) {
12410 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12411 // Callable from the device only."
12412 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12413 return true;
12414
12415 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12416 // Callable from the host only."
12417 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12418 // Callable from the host only."
12419 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12420 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12421 return true;
12422
12423 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12424 return true;
12425
12426 return false;
12427}
John McCall76da55d2013-04-16 07:28:30 +000012428
12429/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12430///
12431MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12432 SourceLocation DeclStart,
12433 Declarator &D, Expr *BitWidth,
12434 InClassInitStyle InitStyle,
12435 AccessSpecifier AS,
12436 AttributeList *MSPropertyAttr) {
12437 IdentifierInfo *II = D.getIdentifier();
12438 if (!II) {
12439 Diag(DeclStart, diag::err_anonymous_property);
12440 return NULL;
12441 }
12442 SourceLocation Loc = D.getIdentifierLoc();
12443
12444 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12445 QualType T = TInfo->getType();
12446 if (getLangOpts().CPlusPlus) {
12447 CheckExtraCXXDefaultArguments(D);
12448
12449 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12450 UPPC_DataMemberType)) {
12451 D.setInvalidType();
12452 T = Context.IntTy;
12453 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12454 }
12455 }
12456
12457 DiagnoseFunctionSpecifiers(D.getDeclSpec());
12458
12459 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12460 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12461 diag::err_invalid_thread)
12462 << DeclSpec::getSpecifierName(TSCS);
12463
12464 // Check to see if this name was declared as a member previously
12465 NamedDecl *PrevDecl = 0;
12466 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12467 LookupName(Previous, S);
12468 switch (Previous.getResultKind()) {
12469 case LookupResult::Found:
12470 case LookupResult::FoundUnresolvedValue:
12471 PrevDecl = Previous.getAsSingle<NamedDecl>();
12472 break;
12473
12474 case LookupResult::FoundOverloaded:
12475 PrevDecl = Previous.getRepresentativeDecl();
12476 break;
12477
12478 case LookupResult::NotFound:
12479 case LookupResult::NotFoundInCurrentInstantiation:
12480 case LookupResult::Ambiguous:
12481 break;
12482 }
12483
12484 if (PrevDecl && PrevDecl->isTemplateParameter()) {
12485 // Maybe we will complain about the shadowed template parameter.
12486 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12487 // Just pretend that we didn't see the previous declaration.
12488 PrevDecl = 0;
12489 }
12490
12491 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12492 PrevDecl = 0;
12493
12494 SourceLocation TSSL = D.getLocStart();
12495 MSPropertyDecl *NewPD;
12496 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12497 NewPD = new (Context) MSPropertyDecl(Record, Loc,
12498 II, T, TInfo, TSSL,
12499 Data.GetterId, Data.SetterId);
12500 ProcessDeclAttributes(TUScope, NewPD, D);
12501 NewPD->setAccess(AS);
12502
12503 if (NewPD->isInvalidDecl())
12504 Record->setInvalidDecl();
12505
12506 if (D.getDeclSpec().isModulePrivateSpecified())
12507 NewPD->setModulePrivate();
12508
12509 if (NewPD->isInvalidDecl() && PrevDecl) {
12510 // Don't introduce NewFD into scope; there's already something
12511 // with the same name in the same scope.
12512 } else if (II) {
12513 PushOnScopeChains(NewPD, S);
12514 } else
12515 Record->addDecl(NewPD);
12516
12517 return NewPD;
12518}