blob: 2d7ca95f08f3e3cac658f38c46eff53a7ec85070 [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"
John McCall5f1e0942010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Eli Friedman7badd242012-02-09 20:13:14 +000019#include "clang/Sema/ScopeInfo.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000021#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000023#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000025#include "clang/AST/DeclVisitor.h"
Richard Trieude5e75c2012-06-14 23:11:34 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000027#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000028#include "clang/AST/RecordLayout.h"
Douglas Gregorcefc3af2012-04-16 07:05:22 +000029#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000030#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000031#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000032#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000033#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000035#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000036#include "clang/Lex/Preprocessor.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000037#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000038#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000039#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000040#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000041
42using namespace clang;
43
Chris Lattner8123a952008-04-10 02:22:51 +000044//===----------------------------------------------------------------------===//
45// CheckDefaultArgumentVisitor
46//===----------------------------------------------------------------------===//
47
Chris Lattner9e979552008-04-12 23:52:44 +000048namespace {
49 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
50 /// the default argument of a parameter to determine whether it
51 /// contains any ill-formed subexpressions. For example, this will
52 /// diagnose the use of local variables or parameters within the
53 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000054 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000055 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000056 Expr *DefaultArg;
57 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000058
Chris Lattner9e979552008-04-12 23:52:44 +000059 public:
Mike Stump1eb44332009-09-09 15:08:12 +000060 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000061 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000062
Chris Lattner9e979552008-04-12 23:52:44 +000063 bool VisitExpr(Expr *Node);
64 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000065 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Douglas Gregorf0459f82012-02-10 23:30:22 +000066 bool VisitLambdaExpr(LambdaExpr *Lambda);
Chris Lattner9e979552008-04-12 23:52:44 +000067 };
Chris Lattner8123a952008-04-10 02:22:51 +000068
Chris Lattner9e979552008-04-12 23:52:44 +000069 /// VisitExpr - Visit all of the children of this expression.
70 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
71 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000072 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000073 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000074 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000075 }
76
Chris Lattner9e979552008-04-12 23:52:44 +000077 /// VisitDeclRefExpr - Visit a reference to a declaration, to
78 /// determine whether this declaration can be used in the default
79 /// argument expression.
80 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000081 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000082 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
83 // C++ [dcl.fct.default]p9
84 // Default arguments are evaluated each time the function is
85 // called. The order of evaluation of function arguments is
86 // unspecified. Consequently, parameters of a function shall not
87 // be used in default argument expressions, even if they are not
88 // evaluated. Parameters of a function declared before a default
89 // argument expression are in scope and can hide namespace and
90 // class member names.
Daniel Dunbar96a00142012-03-09 18:35:03 +000091 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000093 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000094 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000095 // C++ [dcl.fct.default]p7
96 // Local variables shall not be used in default argument
97 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000098 if (VDecl->isLocalVarDecl())
Daniel Dunbar96a00142012-03-09 18:35:03 +000099 return S->Diag(DRE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +0000101 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000102 }
Chris Lattner8123a952008-04-10 02:22:51 +0000103
Douglas Gregor3996f232008-11-04 13:41:56 +0000104 return false;
105 }
Chris Lattner9e979552008-04-12 23:52:44 +0000106
Douglas Gregor796da182008-11-04 14:32:21 +0000107 /// VisitCXXThisExpr - Visit a C++ "this" expression.
108 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
109 // C++ [dcl.fct.default]p8:
110 // The keyword this shall not be used in a default argument of a
111 // member function.
Daniel Dunbar96a00142012-03-09 18:35:03 +0000112 return S->Diag(ThisE->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000113 diag::err_param_default_argument_references_this)
114 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000115 }
Douglas Gregorf0459f82012-02-10 23:30:22 +0000116
117 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
118 // C++11 [expr.lambda.prim]p13:
119 // A lambda-expression appearing in a default argument shall not
120 // implicitly or explicitly capture any entity.
121 if (Lambda->capture_begin() == Lambda->capture_end())
122 return false;
123
124 return S->Diag(Lambda->getLocStart(),
125 diag::err_lambda_capture_default_arg);
126 }
Chris Lattner8123a952008-04-10 02:22:51 +0000127}
128
Richard Smithe6975e92012-04-17 00:58:00 +0000129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
130 CXXMethodDecl *Method) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000131 // If we have an MSAny spec already, don't bother.
132 if (!Method || ComputedEST == EST_MSAny)
Sean Hunt001cad92011-05-10 00:49:42 +0000133 return;
134
135 const FunctionProtoType *Proto
136 = Method->getType()->getAs<FunctionProtoType>();
Richard Smithe6975e92012-04-17 00:58:00 +0000137 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
138 if (!Proto)
139 return;
Sean Hunt001cad92011-05-10 00:49:42 +0000140
141 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
142
143 // If this function can throw any exceptions, make a note of that.
Richard Smithb9d0b762012-07-27 04:22:15 +0000144 if (EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000145 ClearExceptions();
146 ComputedEST = EST;
147 return;
148 }
149
Richard Smith7a614d82011-06-11 17:19:42 +0000150 // FIXME: If the call to this decl is using any of its default arguments, we
151 // need to search them for potentially-throwing calls.
152
Sean Hunt001cad92011-05-10 00:49:42 +0000153 // If this function has a basic noexcept, it doesn't affect the outcome.
154 if (EST == EST_BasicNoexcept)
155 return;
156
157 // If we have a throw-all spec at this point, ignore the function.
158 if (ComputedEST == EST_None)
159 return;
160
161 // If we're still at noexcept(true) and there's a nothrow() callee,
162 // change to that specification.
163 if (EST == EST_DynamicNone) {
164 if (ComputedEST == EST_BasicNoexcept)
165 ComputedEST = EST_DynamicNone;
166 return;
167 }
168
169 // Check out noexcept specs.
170 if (EST == EST_ComputedNoexcept) {
Richard Smithe6975e92012-04-17 00:58:00 +0000171 FunctionProtoType::NoexceptResult NR =
172 Proto->getNoexceptSpec(Self->Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000173 assert(NR != FunctionProtoType::NR_NoNoexcept &&
174 "Must have noexcept result for EST_ComputedNoexcept.");
175 assert(NR != FunctionProtoType::NR_Dependent &&
176 "Should not generate implicit declarations for dependent cases, "
177 "and don't know how to handle them anyway.");
178
179 // noexcept(false) -> no spec on the new function
180 if (NR == FunctionProtoType::NR_Throw) {
181 ClearExceptions();
182 ComputedEST = EST_None;
183 }
184 // noexcept(true) won't change anything either.
185 return;
186 }
187
188 assert(EST == EST_Dynamic && "EST case not considered earlier.");
189 assert(ComputedEST != EST_None &&
190 "Shouldn't collect exceptions when throw-all is guaranteed.");
191 ComputedEST = EST_Dynamic;
192 // Record the exceptions in this function's exception specification.
193 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
194 EEnd = Proto->exception_end();
195 E != EEnd; ++E)
Richard Smithe6975e92012-04-17 00:58:00 +0000196 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000197 Exceptions.push_back(*E);
198}
199
Richard Smith7a614d82011-06-11 17:19:42 +0000200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
Richard Smithb9d0b762012-07-27 04:22:15 +0000201 if (!E || ComputedEST == EST_MSAny)
Richard Smith7a614d82011-06-11 17:19:42 +0000202 return;
203
204 // FIXME:
205 //
206 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000207 // [An] implicit exception-specification specifies the type-id T if and
208 // only if T is allowed by the exception-specification of a function directly
209 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000210 // function it directly invokes allows all exceptions, and f shall allow no
211 // exceptions if every function it directly invokes allows no exceptions.
212 //
213 // Note in particular that if an implicit exception-specification is generated
214 // for a function containing a throw-expression, that specification can still
215 // be noexcept(true).
216 //
217 // Note also that 'directly invoked' is not defined in the standard, and there
218 // is no indication that we should only consider potentially-evaluated calls.
219 //
220 // Ultimately we should implement the intent of the standard: the exception
221 // specification should be the set of exceptions which can be thrown by the
222 // implicit definition. For now, we assume that any non-nothrow expression can
223 // throw any exception.
224
Richard Smithe6975e92012-04-17 00:58:00 +0000225 if (Self->canThrow(E))
Richard Smith7a614d82011-06-11 17:19:42 +0000226 ComputedEST = EST_None;
227}
228
Anders Carlssoned961f92009-08-25 02:29:20 +0000229bool
John McCall9ae2f072010-08-23 23:25:46 +0000230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000231 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000232 if (RequireCompleteType(Param->getLocation(), Param->getType(),
233 diag::err_typecheck_decl_incomplete_type)) {
234 Param->setInvalidDecl();
235 return true;
236 }
237
Anders Carlssoned961f92009-08-25 02:29:20 +0000238 // C++ [dcl.fct.default]p5
239 // A default argument expression is implicitly converted (clause
240 // 4) to the parameter type. The default argument expression has
241 // the same semantic constraints as the initializer expression in
242 // a declaration of a variable of the parameter type, using the
243 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000246 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
247 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000248 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
Benjamin Kramer5354e772012-08-23 23:38:35 +0000249 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000250 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000251 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000252 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000253
John McCallb4eb64d2010-10-08 02:01:28 +0000254 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000255 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Anders Carlssoned961f92009-08-25 02:29:20 +0000257 // Okay: add the default argument to the parameter
258 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000260 // We have already instantiated this parameter; provide each of the
261 // instantiations with the uninstantiated default argument.
262 UnparsedDefaultArgInstantiationsMap::iterator InstPos
263 = UnparsedDefaultArgInstantiations.find(Param);
264 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
265 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
266 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
267
268 // We're done tracking this parameter's instantiations.
269 UnparsedDefaultArgInstantiations.erase(InstPos);
270 }
271
Anders Carlsson9351c172009-08-25 03:18:48 +0000272 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000273}
274
Chris Lattner8123a952008-04-10 02:22:51 +0000275/// ActOnParamDefaultArgument - Check whether the default argument
276/// provided for a function parameter is well-formed. If so, attach it
277/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000278void
John McCalld226f652010-08-21 09:40:31 +0000279Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000280 Expr *DefaultArg) {
281 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000282 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000283
John McCalld226f652010-08-21 09:40:31 +0000284 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000285 UnparsedDefaultArgLocs.erase(Param);
286
Chris Lattner3d1cee32008-04-08 05:04:30 +0000287 // Default arguments are only permitted in C++
David Blaikie4e4d0842012-03-11 07:00:24 +0000288 if (!getLangOpts().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000289 Diag(EqualLoc, diag::err_param_default_argument)
290 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000291 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000292 return;
293 }
294
Douglas Gregor6f526752010-12-16 08:48:57 +0000295 // Check for unexpanded parameter packs.
296 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
297 Param->setInvalidDecl();
298 return;
299 }
300
Anders Carlsson66e30672009-08-25 01:02:06 +0000301 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000302 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
303 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000304 Param->setInvalidDecl();
305 return;
306 }
Mike Stump1eb44332009-09-09 15:08:12 +0000307
John McCall9ae2f072010-08-23 23:25:46 +0000308 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000309}
310
Douglas Gregor61366e92008-12-24 00:01:03 +0000311/// ActOnParamUnparsedDefaultArgument - We've seen a default
312/// argument for a function parameter, but we can't parse it yet
313/// because we're inside a class definition. Note that this default
314/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000315void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000316 SourceLocation EqualLoc,
317 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000318 if (!param)
319 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000320
John McCalld226f652010-08-21 09:40:31 +0000321 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000322 if (Param)
323 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Anders Carlsson5e300d12009-06-12 16:51:40 +0000325 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000326}
327
Douglas Gregor72b505b2008-12-16 21:30:33 +0000328/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
329/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000330void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000331 if (!param)
332 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
John McCalld226f652010-08-21 09:40:31 +0000334 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Anders Carlsson5e300d12009-06-12 16:51:40 +0000336 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Anders Carlsson5e300d12009-06-12 16:51:40 +0000338 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000339}
340
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000341/// CheckExtraCXXDefaultArguments - Check for any extra default
342/// arguments in the declarator, which is not a function declaration
343/// or definition and therefore is not permitted to have default
344/// arguments. This routine should be invoked for every declarator
345/// that is not a function declaration or definition.
346void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
347 // C++ [dcl.fct.default]p3
348 // A default argument expression shall be specified only in the
349 // parameter-declaration-clause of a function declaration or in a
350 // template-parameter (14.1). It shall not be specified for a
351 // parameter pack. If it is specified in a
352 // parameter-declaration-clause, it shall not occur within a
353 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000354 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000355 DeclaratorChunk &chunk = D.getTypeObject(i);
356 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000357 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
358 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000359 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000360 if (Param->hasUnparsedDefaultArg()) {
361 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000362 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
363 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
364 delete Toks;
365 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000366 } else if (Param->getDefaultArg()) {
367 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
368 << Param->getDefaultArg()->getSourceRange();
369 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000370 }
371 }
372 }
373 }
374}
375
Chris Lattner3d1cee32008-04-08 05:04:30 +0000376// MergeCXXFunctionDecl - Merge two declarations of the same C++
377// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000378// type. Subroutine of MergeFunctionDecl. Returns true if there was an
379// error, false otherwise.
James Molloy9cda03f2012-03-13 08:55:35 +0000380bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
381 Scope *S) {
Douglas Gregorcda9c672009-02-16 17:45:42 +0000382 bool Invalid = false;
383
Chris Lattner3d1cee32008-04-08 05:04:30 +0000384 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000385 // For non-template functions, default arguments can be added in
386 // later declarations of a function in the same
387 // scope. Declarations in different scopes have completely
388 // distinct sets of default arguments. That is, declarations in
389 // inner scopes do not acquire default arguments from
390 // declarations in outer scopes, and vice versa. In a given
391 // function declaration, all parameters subsequent to a
392 // parameter with a default argument shall have default
393 // arguments supplied in this or previous declarations. A
394 // default argument shall not be redefined by a later
395 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000396 //
397 // C++ [dcl.fct.default]p6:
398 // Except for member functions of class templates, the default arguments
399 // in a member function definition that appears outside of the class
400 // definition are added to the set of default arguments provided by the
401 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000402 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
403 ParmVarDecl *OldParam = Old->getParamDecl(p);
404 ParmVarDecl *NewParam = New->getParamDecl(p);
405
James Molloy9cda03f2012-03-13 08:55:35 +0000406 bool OldParamHasDfl = OldParam->hasDefaultArg();
407 bool NewParamHasDfl = NewParam->hasDefaultArg();
408
409 NamedDecl *ND = Old;
410 if (S && !isDeclInScope(ND, New->getDeclContext(), S))
411 // Ignore default parameters of old decl if they are not in
412 // the same scope.
413 OldParamHasDfl = false;
414
415 if (OldParamHasDfl && NewParamHasDfl) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000416
Francois Pichet8d051e02011-04-10 03:03:52 +0000417 unsigned DiagDefaultParamID =
418 diag::err_param_default_argument_redefinition;
419
420 // MSVC accepts that default parameters be redefined for member functions
421 // of template class. The new default parameter's value is ignored.
422 Invalid = true;
David Blaikie4e4d0842012-03-11 07:00:24 +0000423 if (getLangOpts().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000424 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
425 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000426 // Merge the old default argument into the new parameter.
427 NewParam->setHasInheritedDefaultArg();
428 if (OldParam->hasUninstantiatedDefaultArg())
429 NewParam->setUninstantiatedDefaultArg(
430 OldParam->getUninstantiatedDefaultArg());
431 else
432 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000433 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000434 Invalid = false;
435 }
436 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000437
Francois Pichet8cf90492011-04-10 04:58:30 +0000438 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
439 // hint here. Alternatively, we could walk the type-source information
440 // for NewParam to find the last source location in the type... but it
441 // isn't worth the effort right now. This is the kind of test case that
442 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000443 // int f(int);
444 // void g(int (*fp)(int) = f);
445 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000446 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000447 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000448
449 // Look for the function declaration where the default argument was
450 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000451 for (FunctionDecl *Older = Old->getPreviousDecl();
452 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000453 if (!Older->getParamDecl(p)->hasDefaultArg())
454 break;
455
456 OldParam = Older->getParamDecl(p);
457 }
458
459 Diag(OldParam->getLocation(), diag::note_previous_definition)
460 << OldParam->getDefaultArgRange();
James Molloy9cda03f2012-03-13 08:55:35 +0000461 } else if (OldParamHasDfl) {
John McCall3d6c1782010-05-04 01:53:42 +0000462 // Merge the old default argument into the new parameter.
463 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000464 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000465 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000466 if (OldParam->hasUninstantiatedDefaultArg())
467 NewParam->setUninstantiatedDefaultArg(
468 OldParam->getUninstantiatedDefaultArg());
469 else
John McCall3d6c1782010-05-04 01:53:42 +0000470 NewParam->setDefaultArg(OldParam->getInit());
James Molloy9cda03f2012-03-13 08:55:35 +0000471 } else if (NewParamHasDfl) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000472 if (New->getDescribedFunctionTemplate()) {
473 // Paragraph 4, quoted above, only applies to non-template functions.
474 Diag(NewParam->getLocation(),
475 diag::err_param_default_argument_template_redecl)
476 << NewParam->getDefaultArgRange();
477 Diag(Old->getLocation(), diag::note_template_prev_declaration)
478 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000479 } else if (New->getTemplateSpecializationKind()
480 != TSK_ImplicitInstantiation &&
481 New->getTemplateSpecializationKind() != TSK_Undeclared) {
482 // C++ [temp.expr.spec]p21:
483 // Default function arguments shall not be specified in a declaration
484 // or a definition for one of the following explicit specializations:
485 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000486 // - the explicit specialization of a member function template;
487 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000488 // template where the class template specialization to which the
489 // member function specialization belongs is implicitly
490 // instantiated.
491 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
492 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
493 << New->getDeclName()
494 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000495 } else if (New->getDeclContext()->isDependentContext()) {
496 // C++ [dcl.fct.default]p6 (DR217):
497 // Default arguments for a member function of a class template shall
498 // be specified on the initial declaration of the member function
499 // within the class template.
500 //
501 // Reading the tea leaves a bit in DR217 and its reference to DR205
502 // leads me to the conclusion that one cannot add default function
503 // arguments for an out-of-line definition of a member function of a
504 // dependent type.
505 int WhichKind = 2;
506 if (CXXRecordDecl *Record
507 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
508 if (Record->getDescribedClassTemplate())
509 WhichKind = 0;
510 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
511 WhichKind = 1;
512 else
513 WhichKind = 2;
514 }
515
516 Diag(NewParam->getLocation(),
517 diag::err_param_default_argument_member_template_redecl)
518 << WhichKind
519 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000520 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
521 CXXSpecialMember NewSM = getSpecialMember(Ctor),
522 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
523 if (NewSM != OldSM) {
524 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
525 << NewParam->getDefaultArgRange() << NewSM;
526 Diag(Old->getLocation(), diag::note_previous_declaration_special)
527 << OldSM;
528 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000529 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000530 }
531 }
532
Richard Smithff234882012-02-20 23:28:05 +0000533 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
Richard Smith9f569cc2011-10-01 02:31:28 +0000534 // template has a constexpr specifier then all its declarations shall
Richard Smithff234882012-02-20 23:28:05 +0000535 // contain the constexpr specifier.
Richard Smith9f569cc2011-10-01 02:31:28 +0000536 if (New->isConstexpr() != Old->isConstexpr()) {
537 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
538 << New << New->isConstexpr();
539 Diag(Old->getLocation(), diag::note_previous_declaration);
540 Invalid = true;
541 }
542
Douglas Gregore13ad832010-02-12 07:32:17 +0000543 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000544 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000545
Douglas Gregorcda9c672009-02-16 17:45:42 +0000546 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000547}
548
Sebastian Redl60618fa2011-03-12 11:50:43 +0000549/// \brief Merge the exception specifications of two variable declarations.
550///
551/// This is called when there's a redeclaration of a VarDecl. The function
552/// checks if the redeclaration might have an exception specification and
553/// validates compatibility and merges the specs if necessary.
554void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
555 // Shortcut if exceptions are disabled.
David Blaikie4e4d0842012-03-11 07:00:24 +0000556 if (!getLangOpts().CXXExceptions)
Sebastian Redl60618fa2011-03-12 11:50:43 +0000557 return;
558
559 assert(Context.hasSameType(New->getType(), Old->getType()) &&
560 "Should only be called if types are otherwise the same.");
561
562 QualType NewType = New->getType();
563 QualType OldType = Old->getType();
564
565 // We're only interested in pointers and references to functions, as well
566 // as pointers to member functions.
567 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
568 NewType = R->getPointeeType();
569 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
570 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
571 NewType = P->getPointeeType();
572 OldType = OldType->getAs<PointerType>()->getPointeeType();
573 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
574 NewType = M->getPointeeType();
575 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
576 }
577
578 if (!NewType->isFunctionProtoType())
579 return;
580
581 // There's lots of special cases for functions. For function pointers, system
582 // libraries are hopefully not as broken so that we don't need these
583 // workarounds.
584 if (CheckEquivalentExceptionSpec(
585 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
586 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
587 New->setInvalidDecl();
588 }
589}
590
Chris Lattner3d1cee32008-04-08 05:04:30 +0000591/// CheckCXXDefaultArguments - Verify that the default arguments for a
592/// function declaration are well-formed according to C++
593/// [dcl.fct.default].
594void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
595 unsigned NumParams = FD->getNumParams();
596 unsigned p;
597
Douglas Gregorc6889e72012-02-14 22:28:59 +0000598 bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
599 isa<CXXMethodDecl>(FD) &&
600 cast<CXXMethodDecl>(FD)->getParent()->isLambda();
601
Chris Lattner3d1cee32008-04-08 05:04:30 +0000602 // Find first parameter with a default argument
603 for (p = 0; p < NumParams; ++p) {
604 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000605 if (Param->hasDefaultArg()) {
606 // C++11 [expr.prim.lambda]p5:
607 // [...] Default arguments (8.3.6) shall not be specified in the
608 // parameter-declaration-clause of a lambda-declarator.
609 //
610 // FIXME: Core issue 974 strikes this sentence, we only provide an
611 // extension warning.
612 if (IsLambda)
613 Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
614 << Param->getDefaultArgRange();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000615 break;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000616 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000617 }
618
619 // C++ [dcl.fct.default]p4:
620 // In a given function declaration, all parameters
621 // subsequent to a parameter with a default argument shall
622 // have default arguments supplied in this or previous
623 // declarations. A default argument shall not be redefined
624 // by a later declaration (not even to the same value).
625 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000626 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000627 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000628 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000629 if (Param->isInvalidDecl())
630 /* We already complained about this parameter. */;
631 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000632 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000633 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000634 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000635 else
Mike Stump1eb44332009-09-09 15:08:12 +0000636 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000637 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Chris Lattner3d1cee32008-04-08 05:04:30 +0000639 LastMissingDefaultArg = p;
640 }
641 }
642
643 if (LastMissingDefaultArg > 0) {
644 // Some default arguments were missing. Clear out all of the
645 // default arguments up to (and including) the last missing
646 // default argument, so that we leave the function parameters
647 // in a semantically valid state.
648 for (p = 0; p <= LastMissingDefaultArg; ++p) {
649 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000650 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000651 Param->setDefaultArg(0);
652 }
653 }
654 }
655}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000656
Richard Smith9f569cc2011-10-01 02:31:28 +0000657// CheckConstexprParameterTypes - Check whether a function's parameter types
658// are all literal types. If so, return true. If not, produce a suitable
Richard Smith86c3ae42012-02-13 03:54:03 +0000659// diagnostic and return false.
660static bool CheckConstexprParameterTypes(Sema &SemaRef,
661 const FunctionDecl *FD) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000662 unsigned ArgIndex = 0;
663 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
664 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
665 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
666 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
667 SourceLocation ParamLoc = PD->getLocation();
668 if (!(*i)->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000669 SemaRef.RequireLiteralType(ParamLoc, *i,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000670 diag::err_constexpr_non_literal_param,
671 ArgIndex+1, PD->getSourceRange(),
672 isa<CXXConstructorDecl>(FD)))
Richard Smith9f569cc2011-10-01 02:31:28 +0000673 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000674 }
Joao Matos17d35c32012-08-31 22:18:20 +0000675 return true;
676}
677
678/// \brief Get diagnostic %select index for tag kind for
679/// record diagnostic message.
680/// WARNING: Indexes apply to particular diagnostics only!
681///
682/// \returns diagnostic %select index.
Joao Matosf143ae92012-09-01 00:13:24 +0000683static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
Joao Matos17d35c32012-08-31 22:18:20 +0000684 switch (Tag) {
Joao Matosf143ae92012-09-01 00:13:24 +0000685 case TTK_Struct: return 0;
686 case TTK_Interface: return 1;
687 case TTK_Class: return 2;
688 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
Joao Matos17d35c32012-08-31 22:18:20 +0000689 }
Joao Matos17d35c32012-08-31 22:18:20 +0000690}
691
692// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
693// the requirements of a constexpr function definition or a constexpr
694// constructor definition. If so, return true. If not, produce appropriate
Richard Smith86c3ae42012-02-13 03:54:03 +0000695// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000696//
Richard Smith86c3ae42012-02-13 03:54:03 +0000697// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
698bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000699 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
700 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000701 // C++11 [dcl.constexpr]p4:
702 // The definition of a constexpr constructor shall satisfy the following
703 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000704 // - the class shall not have any virtual base classes;
Joao Matos17d35c32012-08-31 22:18:20 +0000705 const CXXRecordDecl *RD = MD->getParent();
706 if (RD->getNumVBases()) {
707 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
708 << isa<CXXConstructorDecl>(NewFD)
709 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
710 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
711 E = RD->vbases_end(); I != E; ++I)
712 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000713 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000714 return false;
715 }
Richard Smith35340502012-01-13 04:54:00 +0000716 }
717
718 if (!isa<CXXConstructorDecl>(NewFD)) {
719 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000720 // The definition of a constexpr function shall satisfy the following
721 // constraints:
722 // - it shall not be virtual;
723 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
724 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000725 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000726
Richard Smith86c3ae42012-02-13 03:54:03 +0000727 // If it's not obvious why this function is virtual, find an overridden
728 // function which uses the 'virtual' keyword.
729 const CXXMethodDecl *WrittenVirtual = Method;
730 while (!WrittenVirtual->isVirtualAsWritten())
731 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
732 if (WrittenVirtual != Method)
733 Diag(WrittenVirtual->getLocation(),
734 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000735 return false;
736 }
737
738 // - its return type shall be a literal type;
739 QualType RT = NewFD->getResultType();
740 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000741 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000742 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000743 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000744 }
745
Richard Smith35340502012-01-13 04:54:00 +0000746 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000747 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000748 return false;
749
Richard Smith9f569cc2011-10-01 02:31:28 +0000750 return true;
751}
752
753/// Check the given declaration statement is legal within a constexpr function
754/// body. C++0x [dcl.constexpr]p3,p4.
755///
756/// \return true if the body is OK, false if we have diagnosed a problem.
757static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
758 DeclStmt *DS) {
759 // C++0x [dcl.constexpr]p3 and p4:
760 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
761 // contain only
762 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
763 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
764 switch ((*DclIt)->getKind()) {
765 case Decl::StaticAssert:
766 case Decl::Using:
767 case Decl::UsingShadow:
768 case Decl::UsingDirective:
769 case Decl::UnresolvedUsingTypename:
770 // - static_assert-declarations
771 // - using-declarations,
772 // - using-directives,
773 continue;
774
775 case Decl::Typedef:
776 case Decl::TypeAlias: {
777 // - typedef declarations and alias-declarations that do not define
778 // classes or enumerations,
779 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
780 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
781 // Don't allow variably-modified types in constexpr functions.
782 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
783 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
784 << TL.getSourceRange() << TL.getType()
785 << isa<CXXConstructorDecl>(Dcl);
786 return false;
787 }
788 continue;
789 }
790
791 case Decl::Enum:
792 case Decl::CXXRecord:
793 // As an extension, we allow the declaration (but not the definition) of
794 // classes and enumerations in all declarations, not just in typedef and
795 // alias declarations.
796 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
797 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
798 << isa<CXXConstructorDecl>(Dcl);
799 return false;
800 }
801 continue;
802
803 case Decl::Var:
804 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
805 << isa<CXXConstructorDecl>(Dcl);
806 return false;
807
808 default:
809 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
810 << isa<CXXConstructorDecl>(Dcl);
811 return false;
812 }
813 }
814
815 return true;
816}
817
818/// Check that the given field is initialized within a constexpr constructor.
819///
820/// \param Dcl The constexpr constructor being checked.
821/// \param Field The field being checked. This may be a member of an anonymous
822/// struct or union nested within the class being checked.
823/// \param Inits All declarations, including anonymous struct/union members and
824/// indirect members, for which any initialization was provided.
825/// \param Diagnosed Set to true if an error is produced.
826static void CheckConstexprCtorInitializer(Sema &SemaRef,
827 const FunctionDecl *Dcl,
828 FieldDecl *Field,
829 llvm::SmallSet<Decl*, 16> &Inits,
830 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000831 if (Field->isUnnamedBitfield())
832 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000833
834 if (Field->isAnonymousStructOrUnion() &&
835 Field->getType()->getAsCXXRecordDecl()->isEmpty())
836 return;
837
Richard Smith9f569cc2011-10-01 02:31:28 +0000838 if (!Inits.count(Field)) {
839 if (!Diagnosed) {
840 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
841 Diagnosed = true;
842 }
843 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
844 } else if (Field->isAnonymousStructOrUnion()) {
845 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
846 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
847 I != E; ++I)
848 // If an anonymous union contains an anonymous struct of which any member
849 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000850 if (!RD->isUnion() || Inits.count(*I))
851 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000852 }
853}
854
855/// Check the body for the given constexpr function declaration only contains
856/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
857///
858/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000859bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000860 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000861 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000862 // The definition of a constexpr function shall satisfy the following
863 // constraints: [...]
864 // - its function-body shall be = delete, = default, or a
865 // compound-statement
866 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000867 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000868 // In the definition of a constexpr constructor, [...]
869 // - its function-body shall not be a function-try-block;
870 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
871 << isa<CXXConstructorDecl>(Dcl);
872 return false;
873 }
874
875 // - its function-body shall be [...] a compound-statement that contains only
876 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
877
878 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
879 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
880 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
881 switch ((*BodyIt)->getStmtClass()) {
882 case Stmt::NullStmtClass:
883 // - null statements,
884 continue;
885
886 case Stmt::DeclStmtClass:
887 // - static_assert-declarations
888 // - using-declarations,
889 // - using-directives,
890 // - typedef declarations and alias-declarations that do not define
891 // classes or enumerations,
892 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
893 return false;
894 continue;
895
896 case Stmt::ReturnStmtClass:
897 // - and exactly one return statement;
898 if (isa<CXXConstructorDecl>(Dcl))
899 break;
900
901 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000902 continue;
903
904 default:
905 break;
906 }
907
908 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
909 << isa<CXXConstructorDecl>(Dcl);
910 return false;
911 }
912
913 if (const CXXConstructorDecl *Constructor
914 = dyn_cast<CXXConstructorDecl>(Dcl)) {
915 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000916 // DR1359:
917 // - every non-variant non-static data member and base class sub-object
918 // shall be initialized;
919 // - if the class is a non-empty union, or for each non-empty anonymous
920 // union member of a non-union class, exactly one non-static data member
921 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000922 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000923 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000924 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
925 return false;
926 }
Richard Smith6e433752011-10-10 16:38:04 +0000927 } else if (!Constructor->isDependentContext() &&
928 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000929 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
930
931 // Skip detailed checking if we have enough initializers, and we would
932 // allow at most one initializer per member.
933 bool AnyAnonStructUnionMembers = false;
934 unsigned Fields = 0;
935 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
936 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000937 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000938 AnyAnonStructUnionMembers = true;
939 break;
940 }
941 }
942 if (AnyAnonStructUnionMembers ||
943 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
944 // Check initialization of non-static data members. Base classes are
945 // always initialized so do not need to be checked. Dependent bases
946 // might not have initializers in the member initializer list.
947 llvm::SmallSet<Decl*, 16> Inits;
948 for (CXXConstructorDecl::init_const_iterator
949 I = Constructor->init_begin(), E = Constructor->init_end();
950 I != E; ++I) {
951 if (FieldDecl *FD = (*I)->getMember())
952 Inits.insert(FD);
953 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
954 Inits.insert(ID->chain_begin(), ID->chain_end());
955 }
956
957 bool Diagnosed = false;
958 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
959 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000960 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000961 if (Diagnosed)
962 return false;
963 }
964 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000965 } else {
966 if (ReturnStmts.empty()) {
967 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
968 return false;
969 }
970 if (ReturnStmts.size() > 1) {
971 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
972 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
973 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
974 return false;
975 }
976 }
977
Richard Smith5ba73e12012-02-04 00:33:54 +0000978 // C++11 [dcl.constexpr]p5:
979 // if no function argument values exist such that the function invocation
980 // substitution would produce a constant expression, the program is
981 // ill-formed; no diagnostic required.
982 // C++11 [dcl.constexpr]p3:
983 // - every constructor call and implicit conversion used in initializing the
984 // return value shall be one of those allowed in a constant expression.
985 // C++11 [dcl.constexpr]p4:
986 // - every constructor involved in initializing non-static data members and
987 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000988 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000989 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000990 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
991 << isa<CXXConstructorDecl>(Dcl);
992 for (size_t I = 0, N = Diags.size(); I != N; ++I)
993 Diag(Diags[I].first, Diags[I].second);
994 return false;
995 }
996
Richard Smith9f569cc2011-10-01 02:31:28 +0000997 return true;
998}
999
Douglas Gregorb48fe382008-10-31 09:07:45 +00001000/// isCurrentClassName - Determine whether the identifier II is the
1001/// name of the class type currently being defined. In the case of
1002/// nested classes, this will only return true if II is the name of
1003/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001004bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1005 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001006 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001007
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001008 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001009 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001010 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001011 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1012 } else
1013 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1014
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001015 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001016 return &II == CurDecl->getIdentifier();
1017 else
1018 return false;
1019}
1020
Mike Stump1eb44332009-09-09 15:08:12 +00001021/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001022///
1023/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1024/// and returns NULL otherwise.
1025CXXBaseSpecifier *
1026Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1027 SourceRange SpecifierRange,
1028 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001029 TypeSourceInfo *TInfo,
1030 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001031 QualType BaseType = TInfo->getType();
1032
Douglas Gregor2943aed2009-03-03 04:44:36 +00001033 // C++ [class.union]p1:
1034 // A union shall not have base classes.
1035 if (Class->isUnion()) {
1036 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1037 << SpecifierRange;
1038 return 0;
1039 }
1040
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001041 if (EllipsisLoc.isValid() &&
1042 !TInfo->getType()->containsUnexpandedParameterPack()) {
1043 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1044 << TInfo->getTypeLoc().getSourceRange();
1045 EllipsisLoc = SourceLocation();
1046 }
1047
Douglas Gregor2943aed2009-03-03 04:44:36 +00001048 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001049 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001050 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001051 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001052
1053 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001054
1055 // Base specifiers must be record types.
1056 if (!BaseType->isRecordType()) {
1057 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1058 return 0;
1059 }
1060
1061 // C++ [class.union]p1:
1062 // A union shall not be used as a base class.
1063 if (BaseType->isUnionType()) {
1064 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1065 return 0;
1066 }
1067
1068 // C++ [class.derived]p2:
1069 // The class-name in a base-specifier shall not be an incompletely
1070 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001071 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001072 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001073 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001074 return 0;
John McCall572fc622010-08-17 07:23:57 +00001075 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001076
Eli Friedman1d954f62009-08-15 21:55:26 +00001077 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001078 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001079 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001080 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001081 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001082 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1083 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001084
Anders Carlsson1d209272011-03-25 14:55:14 +00001085 // C++ [class]p3:
1086 // If a class is marked final and it appears as a base-type-specifier in
1087 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001088 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001089 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1090 << CXXBaseDecl->getDeclName();
1091 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1092 << CXXBaseDecl->getDeclName();
1093 return 0;
1094 }
1095
John McCall572fc622010-08-17 07:23:57 +00001096 if (BaseDecl->isInvalidDecl())
1097 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001098
1099 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001100 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001101 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001102 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001103}
1104
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001105/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1106/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001107/// example:
1108/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001109/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001110BaseResult
John McCalld226f652010-08-21 09:40:31 +00001111Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001112 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001113 ParsedType basetype, SourceLocation BaseLoc,
1114 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001115 if (!classdecl)
1116 return true;
1117
Douglas Gregor40808ce2009-03-09 23:48:35 +00001118 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001119 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001120 if (!Class)
1121 return true;
1122
Nick Lewycky56062202010-07-26 16:56:01 +00001123 TypeSourceInfo *TInfo = 0;
1124 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001125
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001126 if (EllipsisLoc.isInvalid() &&
1127 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001128 UPPC_BaseType))
1129 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001130
Douglas Gregor2943aed2009-03-03 04:44:36 +00001131 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001132 Virtual, Access, TInfo,
1133 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001134 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001135 else
1136 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Douglas Gregor2943aed2009-03-03 04:44:36 +00001138 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001139}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001140
Douglas Gregor2943aed2009-03-03 04:44:36 +00001141/// \brief Performs the actual work of attaching the given base class
1142/// specifiers to a C++ class.
1143bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1144 unsigned NumBases) {
1145 if (NumBases == 0)
1146 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001147
1148 // Used to keep track of which base types we have already seen, so
1149 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001150 // that the key is always the unqualified canonical type of the base
1151 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001152 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1153
1154 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001155 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001156 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001157 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001158 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001159 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001160 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001161
1162 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1163 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001164 // C++ [class.mi]p3:
1165 // A class shall not be specified as a direct base class of a
1166 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001167 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001168 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001169 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001170 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001171
1172 // Delete the duplicate base class specifier; we're going to
1173 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001174 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001175
1176 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001177 } else {
1178 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001179 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001180 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001181 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001182 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1183 if (RD->hasAttr<WeakAttr>())
1184 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001185 }
1186 }
1187
1188 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001189 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001190
1191 // Delete the remaining (good) base class specifiers, since their
1192 // data has been copied into the CXXRecordDecl.
1193 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001194 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001195
1196 return Invalid;
1197}
1198
1199/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1200/// class, after checking whether there are any duplicate base
1201/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001202void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001203 unsigned NumBases) {
1204 if (!ClassDecl || !Bases || !NumBases)
1205 return;
1206
1207 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001208 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001209 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001210}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001211
John McCall3cb0ebd2010-03-10 03:28:59 +00001212static CXXRecordDecl *GetClassForType(QualType T) {
1213 if (const RecordType *RT = T->getAs<RecordType>())
1214 return cast<CXXRecordDecl>(RT->getDecl());
1215 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1216 return ICT->getDecl();
1217 else
1218 return 0;
1219}
1220
Douglas Gregora8f32e02009-10-06 17:59:45 +00001221/// \brief Determine whether the type \p Derived is a C++ class that is
1222/// derived from the type \p Base.
1223bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001224 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001225 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001226
1227 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1228 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001229 return false;
1230
John McCall3cb0ebd2010-03-10 03:28:59 +00001231 CXXRecordDecl *BaseRD = GetClassForType(Base);
1232 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001233 return false;
1234
John McCall86ff3082010-02-04 22:26:26 +00001235 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1236 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001237}
1238
1239/// \brief Determine whether the type \p Derived is a C++ class that is
1240/// derived from the type \p Base.
1241bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001242 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001243 return false;
1244
John McCall3cb0ebd2010-03-10 03:28:59 +00001245 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1246 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001247 return false;
1248
John McCall3cb0ebd2010-03-10 03:28:59 +00001249 CXXRecordDecl *BaseRD = GetClassForType(Base);
1250 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001251 return false;
1252
Douglas Gregora8f32e02009-10-06 17:59:45 +00001253 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1254}
1255
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001256void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001257 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001258 assert(BasePathArray.empty() && "Base path array must be empty!");
1259 assert(Paths.isRecordingPaths() && "Must record paths!");
1260
1261 const CXXBasePath &Path = Paths.front();
1262
1263 // We first go backward and check if we have a virtual base.
1264 // FIXME: It would be better if CXXBasePath had the base specifier for
1265 // the nearest virtual base.
1266 unsigned Start = 0;
1267 for (unsigned I = Path.size(); I != 0; --I) {
1268 if (Path[I - 1].Base->isVirtual()) {
1269 Start = I - 1;
1270 break;
1271 }
1272 }
1273
1274 // Now add all bases.
1275 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001276 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001277}
1278
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001279/// \brief Determine whether the given base path includes a virtual
1280/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001281bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1282 for (CXXCastPath::const_iterator B = BasePath.begin(),
1283 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001284 B != BEnd; ++B)
1285 if ((*B)->isVirtual())
1286 return true;
1287
1288 return false;
1289}
1290
Douglas Gregora8f32e02009-10-06 17:59:45 +00001291/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1292/// conversion (where Derived and Base are class types) is
1293/// well-formed, meaning that the conversion is unambiguous (and
1294/// that all of the base classes are accessible). Returns true
1295/// and emits a diagnostic if the code is ill-formed, returns false
1296/// otherwise. Loc is the location where this routine should point to
1297/// if there is an error, and Range is the source range to highlight
1298/// if there is an error.
1299bool
1300Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001301 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001302 unsigned AmbigiousBaseConvID,
1303 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001304 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001305 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001306 // First, determine whether the path from Derived to Base is
1307 // ambiguous. This is slightly more expensive than checking whether
1308 // the Derived to Base conversion exists, because here we need to
1309 // explore multiple paths to determine if there is an ambiguity.
1310 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1311 /*DetectVirtual=*/false);
1312 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1313 assert(DerivationOkay &&
1314 "Can only be used with a derived-to-base conversion");
1315 (void)DerivationOkay;
1316
1317 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001318 if (InaccessibleBaseID) {
1319 // Check that the base class can be accessed.
1320 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1321 InaccessibleBaseID)) {
1322 case AR_inaccessible:
1323 return true;
1324 case AR_accessible:
1325 case AR_dependent:
1326 case AR_delayed:
1327 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001328 }
John McCall6b2accb2010-02-10 09:31:12 +00001329 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001330
1331 // Build a base path if necessary.
1332 if (BasePath)
1333 BuildBasePathArray(Paths, *BasePath);
1334 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001335 }
1336
1337 // We know that the derived-to-base conversion is ambiguous, and
1338 // we're going to produce a diagnostic. Perform the derived-to-base
1339 // search just one more time to compute all of the possible paths so
1340 // that we can print them out. This is more expensive than any of
1341 // the previous derived-to-base checks we've done, but at this point
1342 // performance isn't as much of an issue.
1343 Paths.clear();
1344 Paths.setRecordingPaths(true);
1345 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1346 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1347 (void)StillOkay;
1348
1349 // Build up a textual representation of the ambiguous paths, e.g.,
1350 // D -> B -> A, that will be used to illustrate the ambiguous
1351 // conversions in the diagnostic. We only print one of the paths
1352 // to each base class subobject.
1353 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1354
1355 Diag(Loc, AmbigiousBaseConvID)
1356 << Derived << Base << PathDisplayStr << Range << Name;
1357 return true;
1358}
1359
1360bool
1361Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001362 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001363 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001364 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001365 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001366 IgnoreAccess ? 0
1367 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001368 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001369 Loc, Range, DeclarationName(),
1370 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001371}
1372
1373
1374/// @brief Builds a string representing ambiguous paths from a
1375/// specific derived class to different subobjects of the same base
1376/// class.
1377///
1378/// This function builds a string that can be used in error messages
1379/// to show the different paths that one can take through the
1380/// inheritance hierarchy to go from the derived class to different
1381/// subobjects of a base class. The result looks something like this:
1382/// @code
1383/// struct D -> struct B -> struct A
1384/// struct D -> struct C -> struct A
1385/// @endcode
1386std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1387 std::string PathDisplayStr;
1388 std::set<unsigned> DisplayedPaths;
1389 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1390 Path != Paths.end(); ++Path) {
1391 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1392 // We haven't displayed a path to this particular base
1393 // class subobject yet.
1394 PathDisplayStr += "\n ";
1395 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1396 for (CXXBasePath::const_iterator Element = Path->begin();
1397 Element != Path->end(); ++Element)
1398 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1399 }
1400 }
1401
1402 return PathDisplayStr;
1403}
1404
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001405//===----------------------------------------------------------------------===//
1406// C++ class member Handling
1407//===----------------------------------------------------------------------===//
1408
Abramo Bagnara6206d532010-06-05 05:09:32 +00001409/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001410bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1411 SourceLocation ASLoc,
1412 SourceLocation ColonLoc,
1413 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001414 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001415 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001416 ASLoc, ColonLoc);
1417 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001418 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001419}
1420
Richard Smitha4b39652012-08-06 03:25:17 +00001421/// CheckOverrideControl - Check C++11 override control semantics.
1422void Sema::CheckOverrideControl(Decl *D) {
Richard Smithcddbc1d2012-09-06 18:32:18 +00001423 if (D->isInvalidDecl())
1424 return;
1425
Chris Lattner5f9e2722011-07-23 10:55:15 +00001426 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001427
Richard Smitha4b39652012-08-06 03:25:17 +00001428 // Do we know which functions this declaration might be overriding?
1429 bool OverridesAreKnown = !MD ||
1430 (!MD->getParent()->hasAnyDependentBases() &&
1431 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001432
Richard Smitha4b39652012-08-06 03:25:17 +00001433 if (!MD || !MD->isVirtual()) {
1434 if (OverridesAreKnown) {
1435 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1436 Diag(OA->getLocation(),
1437 diag::override_keyword_only_allowed_on_virtual_member_functions)
1438 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1439 D->dropAttr<OverrideAttr>();
1440 }
1441 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1442 Diag(FA->getLocation(),
1443 diag::override_keyword_only_allowed_on_virtual_member_functions)
1444 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1445 D->dropAttr<FinalAttr>();
1446 }
1447 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001448 return;
1449 }
Richard Smitha4b39652012-08-06 03:25:17 +00001450
1451 if (!OverridesAreKnown)
1452 return;
1453
1454 // C++11 [class.virtual]p5:
1455 // If a virtual function is marked with the virt-specifier override and
1456 // does not override a member function of a base class, the program is
1457 // ill-formed.
1458 bool HasOverriddenMethods =
1459 MD->begin_overridden_methods() != MD->end_overridden_methods();
1460 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1461 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1462 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001463}
1464
Richard Smitha4b39652012-08-06 03:25:17 +00001465/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001466/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001467/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001468bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1469 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001470 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001471 return false;
1472
1473 Diag(New->getLocation(), diag::err_final_function_overridden)
1474 << New->getDeclName();
1475 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1476 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001477}
1478
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001479static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001480 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1481 // FIXME: Destruction of ObjC lifetime types has side-effects.
1482 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1483 return !RD->isCompleteDefinition() ||
1484 !RD->hasTrivialDefaultConstructor() ||
1485 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001486 return false;
1487}
1488
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001489/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1490/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001491/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001492/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1493/// present (but parsing it has been deferred).
John McCalld226f652010-08-21 09:40:31 +00001494Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001495Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001496 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001497 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001498 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001499 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001500 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1501 DeclarationName Name = NameInfo.getName();
1502 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001503
1504 // For anonymous bitfields, the location should point to the type.
1505 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001506 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001507
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001508 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001509
John McCall4bde1e12010-06-04 08:34:12 +00001510 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001511 assert(!DS.isFriendSpecified());
1512
Richard Smith1ab0d902011-06-25 02:28:38 +00001513 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001514
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001515 // C++ 9.2p6: A member shall not be declared to have automatic storage
1516 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001517 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1518 // data members and cannot be applied to names declared const or static,
1519 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001520 switch (DS.getStorageClassSpec()) {
1521 case DeclSpec::SCS_unspecified:
1522 case DeclSpec::SCS_typedef:
1523 case DeclSpec::SCS_static:
1524 // FALL THROUGH.
1525 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001526 case DeclSpec::SCS_mutable:
1527 if (isFunc) {
1528 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001529 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001530 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001531 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Sebastian Redla11f42f2008-11-17 23:24:37 +00001533 // FIXME: It would be nicer if the keyword was ignored only for this
1534 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001535 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001536 }
1537 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001538 default:
1539 if (DS.getStorageClassSpecLoc().isValid())
1540 Diag(DS.getStorageClassSpecLoc(),
1541 diag::err_storageclass_invalid_for_member);
1542 else
1543 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1544 D.getMutableDeclSpec().ClearStorageClassSpecs();
1545 }
1546
Sebastian Redl669d5d72008-11-14 23:42:31 +00001547 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1548 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001549 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001550
1551 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001552 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001553 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001554
1555 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001556 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001557 Diag(Loc, diag::err_bad_variable_name)
1558 << Name;
1559 return 0;
1560 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001561
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001562 IdentifierInfo *II = Name.getAsIdentifierInfo();
1563
Douglas Gregorf2503652011-09-21 14:40:46 +00001564 // Member field could not be with "template" keyword.
1565 // So TemplateParameterLists should be empty in this case.
1566 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001567 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001568 if (TemplateParams->size()) {
1569 // There is no such thing as a member field template.
1570 Diag(D.getIdentifierLoc(), diag::err_template_member)
1571 << II
1572 << SourceRange(TemplateParams->getTemplateLoc(),
1573 TemplateParams->getRAngleLoc());
1574 } else {
1575 // There is an extraneous 'template<>' for this member.
1576 Diag(TemplateParams->getTemplateLoc(),
1577 diag::err_template_member_noparams)
1578 << II
1579 << SourceRange(TemplateParams->getTemplateLoc(),
1580 TemplateParams->getRAngleLoc());
1581 }
1582 return 0;
1583 }
1584
Douglas Gregor922fff22010-10-13 22:19:53 +00001585 if (SS.isSet() && !SS.isInvalid()) {
1586 // The user provided a superfluous scope specifier inside a class
1587 // definition:
1588 //
1589 // class X {
1590 // int X::member;
1591 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001592 if (DeclContext *DC = computeDeclContext(SS, false))
1593 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001594 else
1595 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1596 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001597
Douglas Gregor922fff22010-10-13 22:19:53 +00001598 SS.clear();
1599 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001600
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001601 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001602 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001603 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001604 } else {
Richard Smithca523302012-06-10 03:12:00 +00001605 assert(InitStyle == ICIS_NoInit);
Richard Smith7a614d82011-06-11 17:19:42 +00001606
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001607 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001608 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001609 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001610 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001611
1612 // Non-instance-fields can't have a bitfield.
1613 if (BitWidth) {
1614 if (Member->isInvalidDecl()) {
1615 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001616 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001617 // C++ 9.6p3: A bit-field shall not be a static member.
1618 // "static member 'A' cannot be a bit-field"
1619 Diag(Loc, diag::err_static_not_bitfield)
1620 << Name << BitWidth->getSourceRange();
1621 } else if (isa<TypedefDecl>(Member)) {
1622 // "typedef member 'x' cannot be a bit-field"
1623 Diag(Loc, diag::err_typedef_not_bitfield)
1624 << Name << BitWidth->getSourceRange();
1625 } else {
1626 // A function typedef ("typedef int f(); f a;").
1627 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1628 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001629 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001630 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001631 }
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Chris Lattner8b963ef2009-03-05 23:01:03 +00001633 BitWidth = 0;
1634 Member->setInvalidDecl();
1635 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001636
1637 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Douglas Gregor37b372b2009-08-20 22:52:58 +00001639 // If we have declared a member function template, set the access of the
1640 // templated declaration as well.
1641 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1642 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001643 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001644
Richard Smitha4b39652012-08-06 03:25:17 +00001645 if (VS.isOverrideSpecified())
1646 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1647 if (VS.isFinalSpecified())
1648 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001649
Douglas Gregorf5251602011-03-08 17:10:18 +00001650 if (VS.getLastLocation().isValid()) {
1651 // Update the end location of a method that has a virt-specifiers.
1652 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1653 MD->setRangeEnd(VS.getLastLocation());
1654 }
Richard Smitha4b39652012-08-06 03:25:17 +00001655
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001656 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001657
Douglas Gregor10bd3682008-11-17 22:58:34 +00001658 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001659
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001660 if (isInstField) {
1661 FieldDecl *FD = cast<FieldDecl>(Member);
1662 FieldCollector->Add(FD);
1663
1664 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1665 FD->getLocation())
1666 != DiagnosticsEngine::Ignored) {
1667 // Remember all explicit private FieldDecls that have a name, no side
1668 // effects and are not part of a dependent type declaration.
1669 if (!FD->isImplicit() && FD->getDeclName() &&
1670 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001671 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001672 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001673 !InitializationHasSideEffects(*FD))
1674 UnusedPrivateFields.insert(FD);
1675 }
1676 }
1677
John McCalld226f652010-08-21 09:40:31 +00001678 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001679}
1680
Richard Smith7a614d82011-06-11 17:19:42 +00001681/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001682/// in-class initializer for a non-static C++ class member, and after
1683/// instantiating an in-class initializer in a class template. Such actions
1684/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001685void
Richard Smithca523302012-06-10 03:12:00 +00001686Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001687 Expr *InitExpr) {
1688 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001689 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1690 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001691
1692 if (!InitExpr) {
1693 FD->setInvalidDecl();
1694 FD->removeInClassInitializer();
1695 return;
1696 }
1697
Peter Collingbournefef21892011-10-23 18:59:44 +00001698 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1699 FD->setInvalidDecl();
1700 FD->removeInClassInitializer();
1701 return;
1702 }
1703
Richard Smith7a614d82011-06-11 17:19:42 +00001704 ExprResult Init = InitExpr;
Douglas Gregordd084272012-09-14 04:20:37 +00001705 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent() &&
1706 !FD->getDeclContext()->isDependentContext()) {
1707 // Note: We don't type-check when we're in a dependent context, because
1708 // the initialization-substitution code does not properly handle direct
1709 // list initialization. We have the same hackaround for ctor-initializers.
Sebastian Redl772291a2012-02-19 16:31:05 +00001710 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001711 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001712 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1713 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001714 Expr **Inits = &InitExpr;
1715 unsigned NumInits = 1;
1716 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001717 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001718 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001719 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001720 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1721 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001722 if (Init.isInvalid()) {
1723 FD->setInvalidDecl();
1724 return;
1725 }
1726
Richard Smithca523302012-06-10 03:12:00 +00001727 CheckImplicitConversions(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001728 }
1729
1730 // C++0x [class.base.init]p7:
1731 // The initialization of each base and member constitutes a
1732 // full-expression.
1733 Init = MaybeCreateExprWithCleanups(Init);
1734 if (Init.isInvalid()) {
1735 FD->setInvalidDecl();
1736 return;
1737 }
1738
1739 InitExpr = Init.release();
1740
1741 FD->setInClassInitializer(InitExpr);
1742}
1743
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001744/// \brief Find the direct and/or virtual base specifiers that
1745/// correspond to the given base type, for use in base initialization
1746/// within a constructor.
1747static bool FindBaseInitializer(Sema &SemaRef,
1748 CXXRecordDecl *ClassDecl,
1749 QualType BaseType,
1750 const CXXBaseSpecifier *&DirectBaseSpec,
1751 const CXXBaseSpecifier *&VirtualBaseSpec) {
1752 // First, check for a direct base class.
1753 DirectBaseSpec = 0;
1754 for (CXXRecordDecl::base_class_const_iterator Base
1755 = ClassDecl->bases_begin();
1756 Base != ClassDecl->bases_end(); ++Base) {
1757 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1758 // We found a direct base of this type. That's what we're
1759 // initializing.
1760 DirectBaseSpec = &*Base;
1761 break;
1762 }
1763 }
1764
1765 // Check for a virtual base class.
1766 // FIXME: We might be able to short-circuit this if we know in advance that
1767 // there are no virtual bases.
1768 VirtualBaseSpec = 0;
1769 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1770 // We haven't found a base yet; search the class hierarchy for a
1771 // virtual base class.
1772 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1773 /*DetectVirtual=*/false);
1774 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1775 BaseType, Paths)) {
1776 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1777 Path != Paths.end(); ++Path) {
1778 if (Path->back().Base->isVirtual()) {
1779 VirtualBaseSpec = Path->back().Base;
1780 break;
1781 }
1782 }
1783 }
1784 }
1785
1786 return DirectBaseSpec || VirtualBaseSpec;
1787}
1788
Sebastian Redl6df65482011-09-24 17:48:25 +00001789/// \brief Handle a C++ member initializer using braced-init-list syntax.
1790MemInitResult
1791Sema::ActOnMemInitializer(Decl *ConstructorD,
1792 Scope *S,
1793 CXXScopeSpec &SS,
1794 IdentifierInfo *MemberOrBase,
1795 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001796 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001797 SourceLocation IdLoc,
1798 Expr *InitList,
1799 SourceLocation EllipsisLoc) {
1800 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001801 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001802 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001803}
1804
1805/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001806MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001807Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001808 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001809 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001810 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001811 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001812 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001813 SourceLocation IdLoc,
1814 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001815 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001816 SourceLocation RParenLoc,
1817 SourceLocation EllipsisLoc) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001818 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
1819 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001820 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001821 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001822 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001823}
1824
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001825namespace {
1826
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001827// Callback to only accept typo corrections that can be a valid C++ member
1828// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001829class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1830 public:
1831 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1832 : ClassDecl(ClassDecl) {}
1833
1834 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1835 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1836 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1837 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1838 else
1839 return isa<TypeDecl>(ND);
1840 }
1841 return false;
1842 }
1843
1844 private:
1845 CXXRecordDecl *ClassDecl;
1846};
1847
1848}
1849
Sebastian Redl6df65482011-09-24 17:48:25 +00001850/// \brief Handle a C++ member initializer.
1851MemInitResult
1852Sema::BuildMemInitializer(Decl *ConstructorD,
1853 Scope *S,
1854 CXXScopeSpec &SS,
1855 IdentifierInfo *MemberOrBase,
1856 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001857 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001858 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001859 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001860 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001861 if (!ConstructorD)
1862 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001864 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001865
1866 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001867 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001868 if (!Constructor) {
1869 // The user wrote a constructor initializer on a function that is
1870 // not a C++ constructor. Ignore the error for now, because we may
1871 // have more member initializers coming; we'll diagnose it just
1872 // once in ActOnMemInitializers.
1873 return true;
1874 }
1875
1876 CXXRecordDecl *ClassDecl = Constructor->getParent();
1877
1878 // C++ [class.base.init]p2:
1879 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001880 // constructor's class and, if not found in that scope, are looked
1881 // up in the scope containing the constructor's definition.
1882 // [Note: if the constructor's class contains a member with the
1883 // same name as a direct or virtual base class of the class, a
1884 // mem-initializer-id naming the member or base class and composed
1885 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001886 // mem-initializer-id for the hidden base class may be specified
1887 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001888 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001889 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001890 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001891 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001892 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001893 ValueDecl *Member;
1894 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1895 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001896 if (EllipsisLoc.isValid())
1897 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001898 << MemberOrBase
1899 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001900
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001901 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001902 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001903 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001904 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001905 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001906 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001907 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001908
1909 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001910 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001911 } else if (DS.getTypeSpecType() == TST_decltype) {
1912 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001913 } else {
1914 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1915 LookupParsedName(R, S, &SS);
1916
1917 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1918 if (!TyD) {
1919 if (R.isAmbiguous()) return true;
1920
John McCallfd225442010-04-09 19:01:14 +00001921 // We don't want access-control diagnostics here.
1922 R.suppressDiagnostics();
1923
Douglas Gregor7a886e12010-01-19 06:46:48 +00001924 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1925 bool NotUnknownSpecialization = false;
1926 DeclContext *DC = computeDeclContext(SS, false);
1927 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1928 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1929
1930 if (!NotUnknownSpecialization) {
1931 // When the scope specifier can refer to a member of an unknown
1932 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001933 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1934 SS.getWithLocInContext(Context),
1935 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001936 if (BaseType.isNull())
1937 return true;
1938
Douglas Gregor7a886e12010-01-19 06:46:48 +00001939 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001940 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001941 }
1942 }
1943
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001944 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001945 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001946 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001947 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001948 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001949 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001950 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1951 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001952 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001953 // We have found a non-static data member with a similar
1954 // name to what was typed; complain and initialize that
1955 // member.
1956 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1957 << MemberOrBase << true << CorrectedQuotedStr
1958 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1959 Diag(Member->getLocation(), diag::note_previous_decl)
1960 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001961
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001962 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001963 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001964 const CXXBaseSpecifier *DirectBaseSpec;
1965 const CXXBaseSpecifier *VirtualBaseSpec;
1966 if (FindBaseInitializer(*this, ClassDecl,
1967 Context.getTypeDeclType(Type),
1968 DirectBaseSpec, VirtualBaseSpec)) {
1969 // We have found a direct or virtual base class with a
1970 // similar name to what was typed; complain and initialize
1971 // that base class.
1972 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001973 << MemberOrBase << false << CorrectedQuotedStr
1974 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001975
1976 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1977 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001978 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001979 diag::note_base_class_specified_here)
1980 << BaseSpec->getType()
1981 << BaseSpec->getSourceRange();
1982
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001983 TyD = Type;
1984 }
1985 }
1986 }
1987
Douglas Gregor7a886e12010-01-19 06:46:48 +00001988 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001989 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001990 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001991 return true;
1992 }
John McCall2b194412009-12-21 10:41:20 +00001993 }
1994
Douglas Gregor7a886e12010-01-19 06:46:48 +00001995 if (BaseType.isNull()) {
1996 BaseType = Context.getTypeDeclType(TyD);
1997 if (SS.isSet()) {
1998 NestedNameSpecifier *Qualifier =
1999 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00002000
Douglas Gregor7a886e12010-01-19 06:46:48 +00002001 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002002 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00002003 }
John McCall2b194412009-12-21 10:41:20 +00002004 }
2005 }
Mike Stump1eb44332009-09-09 15:08:12 +00002006
John McCalla93c9342009-12-07 02:54:59 +00002007 if (!TInfo)
2008 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002009
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002010 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00002011}
2012
Chandler Carruth81c64772011-09-03 01:14:15 +00002013/// Checks a member initializer expression for cases where reference (or
2014/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00002015static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2016 Expr *Init,
2017 SourceLocation IdLoc) {
2018 QualType MemberTy = Member->getType();
2019
2020 // We only handle pointers and references currently.
2021 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2022 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2023 return;
2024
2025 const bool IsPointer = MemberTy->isPointerType();
2026 if (IsPointer) {
2027 if (const UnaryOperator *Op
2028 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2029 // The only case we're worried about with pointers requires taking the
2030 // address.
2031 if (Op->getOpcode() != UO_AddrOf)
2032 return;
2033
2034 Init = Op->getSubExpr();
2035 } else {
2036 // We only handle address-of expression initializers for pointers.
2037 return;
2038 }
2039 }
2040
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002041 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2042 // Taking the address of a temporary will be diagnosed as a hard error.
2043 if (IsPointer)
2044 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002045
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002046 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2047 << Member << Init->getSourceRange();
2048 } else if (const DeclRefExpr *DRE
2049 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2050 // We only warn when referring to a non-reference parameter declaration.
2051 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2052 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002053 return;
2054
2055 S.Diag(Init->getExprLoc(),
2056 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2057 : diag::warn_bind_ref_member_to_parameter)
2058 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002059 } else {
2060 // Other initializers are fine.
2061 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002062 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002063
2064 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2065 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002066}
2067
Richard Trieude5e75c2012-06-14 23:11:34 +00002068namespace {
2069 class UninitializedFieldVisitor
2070 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2071 Sema &S;
2072 ValueDecl *VD;
2073 public:
2074 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2075 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2076 S(S), VD(VD) {
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002077 }
2078
Richard Trieude5e75c2012-06-14 23:11:34 +00002079 void HandleExpr(Expr *E) {
2080 if (!E) return;
2081
2082 // Expressions like x(x) sometimes lack the surrounding expressions
2083 // but need to be checked anyways.
2084 HandleValue(E);
2085 Visit(E);
2086 }
2087
2088 void HandleValue(Expr *E) {
2089 E = E->IgnoreParens();
2090
Richard Trieue0991252012-06-14 23:18:09 +00002091 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieude5e75c2012-06-14 23:11:34 +00002092 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2093 return;
Richard Trieue0991252012-06-14 23:18:09 +00002094 Expr *Base = E;
Richard Trieude5e75c2012-06-14 23:11:34 +00002095 while (isa<MemberExpr>(Base)) {
2096 ME = dyn_cast<MemberExpr>(Base);
2097 if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl()))
2098 if (VarD->hasGlobalStorage())
2099 return;
2100 Base = ME->getBase();
2101 }
2102
2103 if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg5965b7c2012-08-20 08:52:22 +00002104 unsigned diag = VD->getType()->isReferenceType()
2105 ? diag::warn_reference_field_is_uninit
2106 : diag::warn_field_is_uninit;
2107 S.Diag(ME->getExprLoc(), diag);
Richard Trieude5e75c2012-06-14 23:11:34 +00002108 return;
2109 }
John McCallb4190042009-11-04 23:02:40 +00002110 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002111
2112 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2113 HandleValue(CO->getTrueExpr());
2114 HandleValue(CO->getFalseExpr());
2115 return;
2116 }
2117
2118 if (BinaryConditionalOperator *BCO =
2119 dyn_cast<BinaryConditionalOperator>(E)) {
2120 HandleValue(BCO->getCommon());
2121 HandleValue(BCO->getFalseExpr());
2122 return;
2123 }
2124
2125 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2126 switch (BO->getOpcode()) {
2127 default:
2128 return;
2129 case(BO_PtrMemD):
2130 case(BO_PtrMemI):
2131 HandleValue(BO->getLHS());
2132 return;
2133 case(BO_Comma):
2134 HandleValue(BO->getRHS());
2135 return;
2136 }
2137 }
John McCallb4190042009-11-04 23:02:40 +00002138 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002139
2140 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2141 if (E->getCastKind() == CK_LValueToRValue)
2142 HandleValue(E->getSubExpr());
2143
2144 Inherited::VisitImplicitCastExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002145 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002146
2147 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2148 Expr *Callee = E->getCallee();
2149 if (isa<MemberExpr>(Callee))
2150 HandleValue(Callee);
2151
2152 Inherited::VisitCXXMemberCallExpr(E);
2153 }
2154 };
2155 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2156 ValueDecl *VD) {
2157 UninitializedFieldVisitor(S, VD).HandleExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002158 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002159} // namespace
John McCallb4190042009-11-04 23:02:40 +00002160
John McCallf312b1e2010-08-26 23:41:50 +00002161MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002162Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002163 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002164 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2165 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2166 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002167 "Member must be a FieldDecl or IndirectFieldDecl");
2168
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002169 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002170 return true;
2171
Douglas Gregor464b2f02010-11-05 22:21:31 +00002172 if (Member->isInvalidDecl())
2173 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002174
John McCallb4190042009-11-04 23:02:40 +00002175 // Diagnose value-uses of fields to initialize themselves, e.g.
2176 // foo(foo)
2177 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002178 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002179 Expr **Args;
2180 unsigned NumArgs;
2181 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2182 Args = ParenList->getExprs();
2183 NumArgs = ParenList->getNumExprs();
2184 } else {
2185 InitListExpr *InitList = cast<InitListExpr>(Init);
2186 Args = InitList->getInits();
2187 NumArgs = InitList->getNumInits();
2188 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002189
Richard Trieude5e75c2012-06-14 23:11:34 +00002190 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2191 != DiagnosticsEngine::Ignored)
2192 for (unsigned i = 0; i < NumArgs; ++i)
2193 // FIXME: Warn about the case when other fields are used before being
John McCallb4190042009-11-04 23:02:40 +00002194 // uninitialized. For example, let this field be the i'th field. When
2195 // initializing the i'th field, throw a warning if any of the >= i'th
2196 // fields are used, as they are not yet initialized.
2197 // Right now we are only handling the case where the i'th field uses
2198 // itself in its initializer.
Richard Trieude5e75c2012-06-14 23:11:34 +00002199 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002200
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002201 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002202
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002203 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002204 // Can't check initialization for a member of dependent type or when
2205 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002206 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002207 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002208 bool InitList = false;
2209 if (isa<InitListExpr>(Init)) {
2210 InitList = true;
2211 Args = &Init;
2212 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002213
2214 if (isStdInitializerList(Member->getType(), 0)) {
2215 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2216 << /*at end of ctor*/1 << InitRange;
2217 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002218 }
2219
Chandler Carruth894aed92010-12-06 09:23:57 +00002220 // Initialize the member.
2221 InitializedEntity MemberEntity =
2222 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2223 : InitializedEntity::InitializeMember(IndirectMember, 0);
2224 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002225 InitList ? InitializationKind::CreateDirectList(IdLoc)
2226 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2227 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002228
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002229 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2230 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002231 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002232 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002233 if (MemberInit.isInvalid())
2234 return true;
2235
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002236 CheckImplicitConversions(MemberInit.get(),
2237 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002238
2239 // C++0x [class.base.init]p7:
2240 // The initialization of each base and member constitutes a
2241 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002242 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002243 if (MemberInit.isInvalid())
2244 return true;
2245
2246 // If we are in a dependent context, template instantiation will
2247 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002248 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002249 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2250 // of the information that we have about the member
2251 // initializer. However, deconstructing the ASTs is a dicey process,
2252 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002253 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002254 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002255 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002256 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002257 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2258 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002259 }
2260
Chandler Carruth894aed92010-12-06 09:23:57 +00002261 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002262 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2263 InitRange.getBegin(), Init,
2264 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002265 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002266 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2267 InitRange.getBegin(), Init,
2268 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002269 }
Eli Friedman59c04372009-07-29 19:44:27 +00002270}
2271
John McCallf312b1e2010-08-26 23:41:50 +00002272MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002273Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002274 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002275 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002276 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002277 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002278 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002279 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002280
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002281 bool InitList = true;
2282 Expr **Args = &Init;
2283 unsigned NumArgs = 1;
2284 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2285 InitList = false;
2286 Args = ParenList->getExprs();
2287 NumArgs = ParenList->getNumExprs();
2288 }
2289
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002290 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002291 // Initialize the object.
2292 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2293 QualType(ClassDecl->getTypeForDecl(), 0));
2294 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002295 InitList ? InitializationKind::CreateDirectList(NameLoc)
2296 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2297 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002298 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2299 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002300 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002301 0);
Sean Hunt41717662011-02-26 19:13:13 +00002302 if (DelegationInit.isInvalid())
2303 return true;
2304
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002305 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2306 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002307
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002308 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002309
2310 // C++0x [class.base.init]p7:
2311 // The initialization of each base and member constitutes a
2312 // full-expression.
2313 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2314 if (DelegationInit.isInvalid())
2315 return true;
2316
Eli Friedmand21016f2012-05-19 23:35:23 +00002317 // If we are in a dependent context, template instantiation will
2318 // perform this type-checking again. Just save the arguments that we
2319 // received in a ParenListExpr.
2320 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2321 // of the information that we have about the base
2322 // initializer. However, deconstructing the ASTs is a dicey process,
2323 // and this approach is far more likely to get the corner cases right.
2324 if (CurContext->isDependentContext())
2325 DelegationInit = Owned(Init);
2326
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002327 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002328 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002329 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002330}
2331
2332MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002333Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002334 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002335 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002336 SourceLocation BaseLoc
2337 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002338
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002339 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2340 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2341 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2342
2343 // C++ [class.base.init]p2:
2344 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002345 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002346 // of that class, the mem-initializer is ill-formed. A
2347 // mem-initializer-list can initialize a base class using any
2348 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002349 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002350
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002351 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002352 if (EllipsisLoc.isValid()) {
2353 // This is a pack expansion.
2354 if (!BaseType->containsUnexpandedParameterPack()) {
2355 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002356 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002357
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002358 EllipsisLoc = SourceLocation();
2359 }
2360 } else {
2361 // Check for any unexpanded parameter packs.
2362 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2363 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002364
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002365 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002366 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002367 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002368
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002369 // Check for direct and virtual base classes.
2370 const CXXBaseSpecifier *DirectBaseSpec = 0;
2371 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2372 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002373 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2374 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002375 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002376
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002377 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2378 VirtualBaseSpec);
2379
2380 // C++ [base.class.init]p2:
2381 // Unless the mem-initializer-id names a nonstatic data member of the
2382 // constructor's class or a direct or virtual base of that class, the
2383 // mem-initializer is ill-formed.
2384 if (!DirectBaseSpec && !VirtualBaseSpec) {
2385 // If the class has any dependent bases, then it's possible that
2386 // one of those types will resolve to the same type as
2387 // BaseType. Therefore, just treat this as a dependent base
2388 // class initialization. FIXME: Should we try to check the
2389 // initialization anyway? It seems odd.
2390 if (ClassDecl->hasAnyDependentBases())
2391 Dependent = true;
2392 else
2393 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2394 << BaseType << Context.getTypeDeclType(ClassDecl)
2395 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2396 }
2397 }
2398
2399 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002400 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002401
Sebastian Redl6df65482011-09-24 17:48:25 +00002402 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2403 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002404 InitRange.getBegin(), Init,
2405 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002406 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002407
2408 // C++ [base.class.init]p2:
2409 // If a mem-initializer-id is ambiguous because it designates both
2410 // a direct non-virtual base class and an inherited virtual base
2411 // class, the mem-initializer is ill-formed.
2412 if (DirectBaseSpec && VirtualBaseSpec)
2413 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002414 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002415
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002416 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002417 if (!BaseSpec)
2418 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2419
2420 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002421 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002422 Expr **Args = &Init;
2423 unsigned NumArgs = 1;
2424 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002425 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002426 Args = ParenList->getExprs();
2427 NumArgs = ParenList->getNumExprs();
2428 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002429
2430 InitializedEntity BaseEntity =
2431 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2432 InitializationKind Kind =
2433 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2434 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2435 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002436 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2437 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002438 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002439 if (BaseInit.isInvalid())
2440 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002441
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002442 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002443
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002444 // C++0x [class.base.init]p7:
2445 // The initialization of each base and member constitutes a
2446 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002447 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002448 if (BaseInit.isInvalid())
2449 return true;
2450
2451 // If we are in a dependent context, template instantiation will
2452 // perform this type-checking again. Just save the arguments that we
2453 // received in a ParenListExpr.
2454 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2455 // of the information that we have about the base
2456 // initializer. However, deconstructing the ASTs is a dicey process,
2457 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002458 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002459 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002460
Sean Huntcbb67482011-01-08 20:30:50 +00002461 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002462 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002463 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002464 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002465 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002466}
2467
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002468// Create a static_cast\<T&&>(expr).
2469static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2470 QualType ExprType = E->getType();
2471 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2472 SourceLocation ExprLoc = E->getLocStart();
2473 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2474 TargetType, ExprLoc);
2475
2476 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2477 SourceRange(ExprLoc, ExprLoc),
2478 E->getSourceRange()).take();
2479}
2480
Anders Carlssone5ef7402010-04-23 03:10:23 +00002481/// ImplicitInitializerKind - How an implicit base or member initializer should
2482/// initialize its base or member.
2483enum ImplicitInitializerKind {
2484 IIK_Default,
2485 IIK_Copy,
2486 IIK_Move
2487};
2488
Anders Carlssondefefd22010-04-23 02:00:02 +00002489static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002490BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002491 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002492 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002493 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002494 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002495 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002496 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2497 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002498
John McCall60d7b3a2010-08-24 06:29:42 +00002499 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002500
2501 switch (ImplicitInitKind) {
2502 case IIK_Default: {
2503 InitializationKind InitKind
2504 = InitializationKind::CreateDefault(Constructor->getLocation());
2505 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002506 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002507 break;
2508 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002509
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002510 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002511 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002512 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002513 ParmVarDecl *Param = Constructor->getParamDecl(0);
2514 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002515
Anders Carlssone5ef7402010-04-23 03:10:23 +00002516 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002517 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002518 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002519 Constructor->getLocation(), ParamType,
2520 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002521
Eli Friedman5f2987c2012-02-02 03:46:19 +00002522 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2523
Anders Carlssonc7957502010-04-24 22:02:54 +00002524 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002525 QualType ArgTy =
2526 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2527 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002528
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002529 if (Moving) {
2530 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2531 }
2532
John McCallf871d0c2010-08-07 06:22:56 +00002533 CXXCastPath BasePath;
2534 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002535 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2536 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002537 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002538 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002539
Anders Carlssone5ef7402010-04-23 03:10:23 +00002540 InitializationKind InitKind
2541 = InitializationKind::CreateDirect(Constructor->getLocation(),
2542 SourceLocation(), SourceLocation());
2543 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2544 &CopyCtorArg, 1);
2545 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002546 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002547 break;
2548 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002549 }
John McCall9ae2f072010-08-23 23:25:46 +00002550
Douglas Gregor53c374f2010-12-07 00:41:46 +00002551 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002552 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002553 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002554
Anders Carlssondefefd22010-04-23 02:00:02 +00002555 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002556 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002557 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2558 SourceLocation()),
2559 BaseSpec->isVirtual(),
2560 SourceLocation(),
2561 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002562 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002563 SourceLocation());
2564
Anders Carlssondefefd22010-04-23 02:00:02 +00002565 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002566}
2567
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002568static bool RefersToRValueRef(Expr *MemRef) {
2569 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2570 return Referenced->getType()->isRValueReferenceType();
2571}
2572
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002573static bool
2574BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002575 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002576 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002577 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002578 if (Field->isInvalidDecl())
2579 return true;
2580
Chandler Carruthf186b542010-06-29 23:50:44 +00002581 SourceLocation Loc = Constructor->getLocation();
2582
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002583 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2584 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002585 ParmVarDecl *Param = Constructor->getParamDecl(0);
2586 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002587
2588 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002589 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2590 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002591
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002592 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002593 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002594 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002595 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002596
Eli Friedman5f2987c2012-02-02 03:46:19 +00002597 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2598
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002599 if (Moving) {
2600 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2601 }
2602
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002603 // Build a reference to this field within the parameter.
2604 CXXScopeSpec SS;
2605 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2606 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002607 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2608 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002609 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002610 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002611 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002612 ParamType, Loc,
2613 /*IsArrow=*/false,
2614 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002615 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002616 /*FirstQualifierInScope=*/0,
2617 MemberLookup,
2618 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002619 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002620 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002621
2622 // C++11 [class.copy]p15:
2623 // - if a member m has rvalue reference type T&&, it is direct-initialized
2624 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002625 if (RefersToRValueRef(CtorArg.get())) {
2626 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002627 }
2628
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002629 // When the field we are copying is an array, create index variables for
2630 // each dimension of the array. We use these index variables to subscript
2631 // the source array, and other clients (e.g., CodeGen) will perform the
2632 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002633 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002634 QualType BaseType = Field->getType();
2635 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002636 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002637 while (const ConstantArrayType *Array
2638 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002639 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002640 // Create the iteration variable for this array index.
2641 IdentifierInfo *IterationVarName = 0;
2642 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002643 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002644 llvm::raw_svector_ostream OS(Str);
2645 OS << "__i" << IndexVariables.size();
2646 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2647 }
2648 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002649 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002650 IterationVarName, SizeType,
2651 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002652 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002653 IndexVariables.push_back(IterationVar);
2654
2655 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002656 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002657 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002658 assert(!IterationVarRef.isInvalid() &&
2659 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002660 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2661 assert(!IterationVarRef.isInvalid() &&
2662 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002663
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002664 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002665 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002666 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002667 Loc);
2668 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002669 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002670
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002671 BaseType = Array->getElementType();
2672 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002673
2674 // The array subscript expression is an lvalue, which is wrong for moving.
2675 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002676 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002677
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002678 // Construct the entity that we will be initializing. For an array, this
2679 // will be first element in the array, which may require several levels
2680 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002681 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002682 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002683 if (Indirect)
2684 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2685 else
2686 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002687 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2688 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2689 0,
2690 Entities.back()));
2691
2692 // Direct-initialize to use the copy constructor.
2693 InitializationKind InitKind =
2694 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2695
Sebastian Redl74e611a2011-09-04 18:14:28 +00002696 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002697 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002698 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002699
John McCall60d7b3a2010-08-24 06:29:42 +00002700 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002701 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002702 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002703 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002704 if (MemberInit.isInvalid())
2705 return true;
2706
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002707 if (Indirect) {
2708 assert(IndexVariables.size() == 0 &&
2709 "Indirect field improperly initialized");
2710 CXXMemberInit
2711 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2712 Loc, Loc,
2713 MemberInit.takeAs<Expr>(),
2714 Loc);
2715 } else
2716 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2717 Loc, MemberInit.takeAs<Expr>(),
2718 Loc,
2719 IndexVariables.data(),
2720 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002721 return false;
2722 }
2723
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002724 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2725
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002726 QualType FieldBaseElementType =
2727 SemaRef.Context.getBaseElementType(Field->getType());
2728
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002729 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002730 InitializedEntity InitEntity
2731 = Indirect? InitializedEntity::InitializeMember(Indirect)
2732 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002733 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002734 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002735
2736 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002737 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002738 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002739
Douglas Gregor53c374f2010-12-07 00:41:46 +00002740 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002741 if (MemberInit.isInvalid())
2742 return true;
2743
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002744 if (Indirect)
2745 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2746 Indirect, Loc,
2747 Loc,
2748 MemberInit.get(),
2749 Loc);
2750 else
2751 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2752 Field, Loc, Loc,
2753 MemberInit.get(),
2754 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002755 return false;
2756 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002757
Sean Hunt1f2f3842011-05-17 00:19:05 +00002758 if (!Field->getParent()->isUnion()) {
2759 if (FieldBaseElementType->isReferenceType()) {
2760 SemaRef.Diag(Constructor->getLocation(),
2761 diag::err_uninitialized_member_in_ctor)
2762 << (int)Constructor->isImplicit()
2763 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2764 << 0 << Field->getDeclName();
2765 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2766 return true;
2767 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002768
Sean Hunt1f2f3842011-05-17 00:19:05 +00002769 if (FieldBaseElementType.isConstQualified()) {
2770 SemaRef.Diag(Constructor->getLocation(),
2771 diag::err_uninitialized_member_in_ctor)
2772 << (int)Constructor->isImplicit()
2773 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2774 << 1 << Field->getDeclName();
2775 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2776 return true;
2777 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002778 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002779
David Blaikie4e4d0842012-03-11 07:00:24 +00002780 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002781 FieldBaseElementType->isObjCRetainableType() &&
2782 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2783 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002784 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002785 // Default-initialize Objective-C pointers to NULL.
2786 CXXMemberInit
2787 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2788 Loc, Loc,
2789 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2790 Loc);
2791 return false;
2792 }
2793
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002794 // Nothing to initialize.
2795 CXXMemberInit = 0;
2796 return false;
2797}
John McCallf1860e52010-05-20 23:23:51 +00002798
2799namespace {
2800struct BaseAndFieldInfo {
2801 Sema &S;
2802 CXXConstructorDecl *Ctor;
2803 bool AnyErrorsInInits;
2804 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002805 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002806 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002807
2808 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2809 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002810 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2811 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002812 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002813 else if (Generated && Ctor->isMoveConstructor())
2814 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002815 else
2816 IIK = IIK_Default;
2817 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002818
2819 bool isImplicitCopyOrMove() const {
2820 switch (IIK) {
2821 case IIK_Copy:
2822 case IIK_Move:
2823 return true;
2824
2825 case IIK_Default:
2826 return false;
2827 }
David Blaikie30263482012-01-20 21:50:17 +00002828
2829 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002830 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002831
2832 bool addFieldInitializer(CXXCtorInitializer *Init) {
2833 AllToInit.push_back(Init);
2834
2835 // Check whether this initializer makes the field "used".
2836 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2837 S.UnusedPrivateFields.remove(Init->getAnyMember());
2838
2839 return false;
2840 }
John McCallf1860e52010-05-20 23:23:51 +00002841};
2842}
2843
Richard Smitha4950662011-09-19 13:34:43 +00002844/// \brief Determine whether the given indirect field declaration is somewhere
2845/// within an anonymous union.
2846static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2847 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2848 CEnd = F->chain_end();
2849 C != CEnd; ++C)
2850 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2851 if (Record->isUnion())
2852 return true;
2853
2854 return false;
2855}
2856
Douglas Gregorddb21472011-11-02 23:04:16 +00002857/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2858/// array type.
2859static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2860 if (T->isIncompleteArrayType())
2861 return true;
2862
2863 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2864 if (!ArrayT->getSize())
2865 return true;
2866
2867 T = ArrayT->getElementType();
2868 }
2869
2870 return false;
2871}
2872
Richard Smith7a614d82011-06-11 17:19:42 +00002873static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002874 FieldDecl *Field,
2875 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002876
Chandler Carruthe861c602010-06-30 02:59:29 +00002877 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00002878 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
2879 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002880
Richard Smith0b8220a2012-08-07 21:30:42 +00002881 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00002882 // has a brace-or-equal-initializer, the entity is initialized as specified
2883 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002884 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002885 CXXCtorInitializer *Init;
2886 if (Indirect)
2887 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2888 SourceLocation(),
2889 SourceLocation(), 0,
2890 SourceLocation());
2891 else
2892 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2893 SourceLocation(),
2894 SourceLocation(), 0,
2895 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00002896 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002897 }
2898
Richard Smithc115f632011-09-18 11:14:50 +00002899 // Don't build an implicit initializer for union members if none was
2900 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002901 if (Field->getParent()->isUnion() ||
2902 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002903 return false;
2904
Douglas Gregorddb21472011-11-02 23:04:16 +00002905 // Don't initialize incomplete or zero-length arrays.
2906 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2907 return false;
2908
John McCallf1860e52010-05-20 23:23:51 +00002909 // Don't try to build an implicit initializer if there were semantic
2910 // errors in any of the initializers (and therefore we might be
2911 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002912 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002913 return false;
2914
Sean Huntcbb67482011-01-08 20:30:50 +00002915 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002916 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2917 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002918 return true;
John McCallf1860e52010-05-20 23:23:51 +00002919
Richard Smith0b8220a2012-08-07 21:30:42 +00002920 if (!Init)
2921 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00002922
Richard Smith0b8220a2012-08-07 21:30:42 +00002923 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002924}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002925
2926bool
2927Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2928 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002929 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002930 Constructor->setNumCtorInitializers(1);
2931 CXXCtorInitializer **initializer =
2932 new (Context) CXXCtorInitializer*[1];
2933 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2934 Constructor->setCtorInitializers(initializer);
2935
Sean Huntb76af9c2011-05-03 23:05:34 +00002936 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002937 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002938 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2939 }
2940
Sean Huntc1598702011-05-05 00:05:47 +00002941 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002942
Sean Hunt059ce0d2011-05-01 07:04:31 +00002943 return false;
2944}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002945
John McCallb77115d2011-06-17 00:18:42 +00002946bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2947 CXXCtorInitializer **Initializers,
2948 unsigned NumInitializers,
2949 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002950 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002951 // Just store the initializers as written, they will be checked during
2952 // instantiation.
2953 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002954 Constructor->setNumCtorInitializers(NumInitializers);
2955 CXXCtorInitializer **baseOrMemberInitializers =
2956 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002957 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002958 NumInitializers * sizeof(CXXCtorInitializer*));
2959 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002960 }
2961
2962 return false;
2963 }
2964
John McCallf1860e52010-05-20 23:23:51 +00002965 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002966
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002967 // We need to build the initializer AST according to order of construction
2968 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002969 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002970 if (!ClassDecl)
2971 return true;
2972
Eli Friedman80c30da2009-11-09 19:20:36 +00002973 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002974
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002975 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002976 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002977
2978 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002979 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002980 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002981 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002982 }
2983
Anders Carlsson711f34a2010-04-21 19:52:01 +00002984 // Keep track of the direct virtual bases.
2985 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2986 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2987 E = ClassDecl->bases_end(); I != E; ++I) {
2988 if (I->isVirtual())
2989 DirectVBases.insert(I);
2990 }
2991
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002992 // Push virtual bases before others.
2993 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2994 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2995
Sean Huntcbb67482011-01-08 20:30:50 +00002996 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002997 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2998 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002999 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00003000 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00003001 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003002 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003003 VBase, IsInheritedVirtualBase,
3004 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003005 HadError = true;
3006 continue;
3007 }
Anders Carlsson84688f22010-04-20 23:11:20 +00003008
John McCallf1860e52010-05-20 23:23:51 +00003009 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003010 }
3011 }
Mike Stump1eb44332009-09-09 15:08:12 +00003012
John McCallf1860e52010-05-20 23:23:51 +00003013 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003014 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3015 E = ClassDecl->bases_end(); Base != E; ++Base) {
3016 // Virtuals are in the virtual base list and already constructed.
3017 if (Base->isVirtual())
3018 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00003019
Sean Huntcbb67482011-01-08 20:30:50 +00003020 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00003021 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3022 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003023 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003024 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003025 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003026 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003027 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003028 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003029 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003030 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003031
John McCallf1860e52010-05-20 23:23:51 +00003032 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003033 }
3034 }
Mike Stump1eb44332009-09-09 15:08:12 +00003035
John McCallf1860e52010-05-20 23:23:51 +00003036 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003037 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3038 MemEnd = ClassDecl->decls_end();
3039 Mem != MemEnd; ++Mem) {
3040 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003041 // C++ [class.bit]p2:
3042 // A declaration for a bit-field that omits the identifier declares an
3043 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3044 // initialized.
3045 if (F->isUnnamedBitfield())
3046 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003047
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003048 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003049 // handle anonymous struct/union fields based on their individual
3050 // indirect fields.
3051 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3052 continue;
3053
3054 if (CollectFieldInitializer(*this, Info, F))
3055 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003056 continue;
3057 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003058
3059 // Beyond this point, we only consider default initialization.
3060 if (Info.IIK != IIK_Default)
3061 continue;
3062
3063 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3064 if (F->getType()->isIncompleteArrayType()) {
3065 assert(ClassDecl->hasFlexibleArrayMember() &&
3066 "Incomplete array type is not valid");
3067 continue;
3068 }
3069
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003070 // Initialize each field of an anonymous struct individually.
3071 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3072 HadError = true;
3073
3074 continue;
3075 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003076 }
Mike Stump1eb44332009-09-09 15:08:12 +00003077
John McCallf1860e52010-05-20 23:23:51 +00003078 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003079 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003080 Constructor->setNumCtorInitializers(NumInitializers);
3081 CXXCtorInitializer **baseOrMemberInitializers =
3082 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003083 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003084 NumInitializers * sizeof(CXXCtorInitializer*));
3085 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003086
John McCallef027fe2010-03-16 21:39:52 +00003087 // Constructors implicitly reference the base and member
3088 // destructors.
3089 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3090 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003091 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003092
3093 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003094}
3095
Eli Friedman6347f422009-07-21 19:28:10 +00003096static void *GetKeyForTopLevelField(FieldDecl *Field) {
3097 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003098 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003099 if (RT->getDecl()->isAnonymousStructOrUnion())
3100 return static_cast<void *>(RT->getDecl());
3101 }
3102 return static_cast<void *>(Field);
3103}
3104
Anders Carlssonea356fb2010-04-02 05:42:15 +00003105static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003106 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003107}
3108
Anders Carlssonea356fb2010-04-02 05:42:15 +00003109static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003110 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003111 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003112 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003113
Eli Friedman6347f422009-07-21 19:28:10 +00003114 // For fields injected into the class via declaration of an anonymous union,
3115 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003116 FieldDecl *Field = Member->getAnyMember();
3117
John McCall3c3ccdb2010-04-10 09:28:51 +00003118 // If the field is a member of an anonymous struct or union, our key
3119 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003120 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003121 if (RD->isAnonymousStructOrUnion()) {
3122 while (true) {
3123 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3124 if (Parent->isAnonymousStructOrUnion())
3125 RD = Parent;
3126 else
3127 break;
3128 }
3129
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003130 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003131 }
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003133 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003134}
3135
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003136static void
3137DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003138 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003139 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003140 unsigned NumInits) {
3141 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003142 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003143
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003144 // Don't check initializers order unless the warning is enabled at the
3145 // location of at least one initializer.
3146 bool ShouldCheckOrder = false;
3147 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003148 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003149 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3150 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003151 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003152 ShouldCheckOrder = true;
3153 break;
3154 }
3155 }
3156 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003157 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003158
John McCalld6ca8da2010-04-10 07:37:23 +00003159 // Build the list of bases and members in the order that they'll
3160 // actually be initialized. The explicit initializers should be in
3161 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003162 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003163
Anders Carlsson071d6102010-04-02 03:38:04 +00003164 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3165
John McCalld6ca8da2010-04-10 07:37:23 +00003166 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003167 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003168 ClassDecl->vbases_begin(),
3169 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003170 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003171
John McCalld6ca8da2010-04-10 07:37:23 +00003172 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003173 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003174 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003175 if (Base->isVirtual())
3176 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003177 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003178 }
Mike Stump1eb44332009-09-09 15:08:12 +00003179
John McCalld6ca8da2010-04-10 07:37:23 +00003180 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003181 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003182 E = ClassDecl->field_end(); Field != E; ++Field) {
3183 if (Field->isUnnamedBitfield())
3184 continue;
3185
David Blaikie581deb32012-06-06 20:45:41 +00003186 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003187 }
3188
John McCalld6ca8da2010-04-10 07:37:23 +00003189 unsigned NumIdealInits = IdealInitKeys.size();
3190 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003191
Sean Huntcbb67482011-01-08 20:30:50 +00003192 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003193 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003194 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003195 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003196
3197 // Scan forward to try to find this initializer in the idealized
3198 // initializers list.
3199 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3200 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003201 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003202
3203 // If we didn't find this initializer, it must be because we
3204 // scanned past it on a previous iteration. That can only
3205 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003206 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003207 Sema::SemaDiagnosticBuilder D =
3208 SemaRef.Diag(PrevInit->getSourceLocation(),
3209 diag::warn_initializer_out_of_order);
3210
Francois Pichet00eb3f92010-12-04 09:14:42 +00003211 if (PrevInit->isAnyMemberInitializer())
3212 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003213 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003214 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003215
Francois Pichet00eb3f92010-12-04 09:14:42 +00003216 if (Init->isAnyMemberInitializer())
3217 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003218 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003219 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003220
3221 // Move back to the initializer's location in the ideal list.
3222 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3223 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003224 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003225
3226 assert(IdealIndex != NumIdealInits &&
3227 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003228 }
John McCalld6ca8da2010-04-10 07:37:23 +00003229
3230 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003231 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003232}
3233
John McCall3c3ccdb2010-04-10 09:28:51 +00003234namespace {
3235bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003236 CXXCtorInitializer *Init,
3237 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003238 if (!PrevInit) {
3239 PrevInit = Init;
3240 return false;
3241 }
3242
3243 if (FieldDecl *Field = Init->getMember())
3244 S.Diag(Init->getSourceLocation(),
3245 diag::err_multiple_mem_initialization)
3246 << Field->getDeclName()
3247 << Init->getSourceRange();
3248 else {
John McCallf4c73712011-01-19 06:33:43 +00003249 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003250 assert(BaseClass && "neither field nor base");
3251 S.Diag(Init->getSourceLocation(),
3252 diag::err_multiple_base_initialization)
3253 << QualType(BaseClass, 0)
3254 << Init->getSourceRange();
3255 }
3256 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3257 << 0 << PrevInit->getSourceRange();
3258
3259 return true;
3260}
3261
Sean Huntcbb67482011-01-08 20:30:50 +00003262typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003263typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3264
3265bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003266 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003267 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003268 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003269 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003270 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003271
3272 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003273 if (Parent->isUnion()) {
3274 UnionEntry &En = Unions[Parent];
3275 if (En.first && En.first != Child) {
3276 S.Diag(Init->getSourceLocation(),
3277 diag::err_multiple_mem_union_initialization)
3278 << Field->getDeclName()
3279 << Init->getSourceRange();
3280 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3281 << 0 << En.second->getSourceRange();
3282 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003283 }
3284 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003285 En.first = Child;
3286 En.second = Init;
3287 }
David Blaikie6fe29652011-11-17 06:01:57 +00003288 if (!Parent->isAnonymousStructOrUnion())
3289 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003290 }
3291
3292 Child = Parent;
3293 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003294 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003295
3296 return false;
3297}
3298}
3299
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003300/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003301void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003302 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003303 CXXCtorInitializer **meminits,
3304 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003305 bool AnyErrors) {
3306 if (!ConstructorDecl)
3307 return;
3308
3309 AdjustDeclIfTemplate(ConstructorDecl);
3310
3311 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003312 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003313
3314 if (!Constructor) {
3315 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3316 return;
3317 }
3318
Sean Huntcbb67482011-01-08 20:30:50 +00003319 CXXCtorInitializer **MemInits =
3320 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003321
3322 // Mapping for the duplicate initializers check.
3323 // For member initializers, this is keyed with a FieldDecl*.
3324 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003325 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003326
3327 // Mapping for the inconsistent anonymous-union initializers check.
3328 RedundantUnionMap MemberUnions;
3329
Anders Carlssonea356fb2010-04-02 05:42:15 +00003330 bool HadError = false;
3331 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003332 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003333
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003334 // Set the source order index.
3335 Init->setSourceOrder(i);
3336
Francois Pichet00eb3f92010-12-04 09:14:42 +00003337 if (Init->isAnyMemberInitializer()) {
3338 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003339 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3340 CheckRedundantUnionInit(*this, Init, MemberUnions))
3341 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003342 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003343 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3344 if (CheckRedundantInit(*this, Init, Members[Key]))
3345 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003346 } else {
3347 assert(Init->isDelegatingInitializer());
3348 // This must be the only initializer
Richard Smitha6ddea62012-09-14 18:21:10 +00003349 if (NumMemInits != 1) {
3350 Diag(Init->getSourceLocation(),
Sean Hunt41717662011-02-26 19:13:13 +00003351 diag::err_delegating_initializer_alone)
Richard Smitha6ddea62012-09-14 18:21:10 +00003352 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
Sean Hunt059ce0d2011-05-01 07:04:31 +00003353 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003354 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003355 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003356 // Return immediately as the initializer is set.
3357 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003358 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003359 }
3360
Anders Carlssonea356fb2010-04-02 05:42:15 +00003361 if (HadError)
3362 return;
3363
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003364 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003365
Sean Huntcbb67482011-01-08 20:30:50 +00003366 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003367}
3368
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003369void
John McCallef027fe2010-03-16 21:39:52 +00003370Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3371 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003372 // Ignore dependent contexts. Also ignore unions, since their members never
3373 // have destructors implicitly called.
3374 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003375 return;
John McCall58e6f342010-03-16 05:22:47 +00003376
3377 // FIXME: all the access-control diagnostics are positioned on the
3378 // field/base declaration. That's probably good; that said, the
3379 // user might reasonably want to know why the destructor is being
3380 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003381
Anders Carlsson9f853df2009-11-17 04:44:12 +00003382 // Non-static data members.
3383 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3384 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003385 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003386 if (Field->isInvalidDecl())
3387 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003388
3389 // Don't destroy incomplete or zero-length arrays.
3390 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3391 continue;
3392
Anders Carlsson9f853df2009-11-17 04:44:12 +00003393 QualType FieldType = Context.getBaseElementType(Field->getType());
3394
3395 const RecordType* RT = FieldType->getAs<RecordType>();
3396 if (!RT)
3397 continue;
3398
3399 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003400 if (FieldClassDecl->isInvalidDecl())
3401 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003402 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003403 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003404 // The destructor for an implicit anonymous union member is never invoked.
3405 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3406 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003407
Douglas Gregordb89f282010-07-01 22:47:18 +00003408 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003409 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003410 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003411 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003412 << Field->getDeclName()
3413 << FieldType);
3414
Eli Friedman5f2987c2012-02-02 03:46:19 +00003415 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003416 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003417 }
3418
John McCall58e6f342010-03-16 05:22:47 +00003419 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3420
Anders Carlsson9f853df2009-11-17 04:44:12 +00003421 // Bases.
3422 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3423 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003424 // Bases are always records in a well-formed non-dependent class.
3425 const RecordType *RT = Base->getType()->getAs<RecordType>();
3426
3427 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003428 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003429 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003430
John McCall58e6f342010-03-16 05:22:47 +00003431 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003432 // If our base class is invalid, we probably can't get its dtor anyway.
3433 if (BaseClassDecl->isInvalidDecl())
3434 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003435 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003436 continue;
John McCall58e6f342010-03-16 05:22:47 +00003437
Douglas Gregordb89f282010-07-01 22:47:18 +00003438 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003439 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003440
3441 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003442 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003443 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003444 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003445 << Base->getSourceRange(),
3446 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003447
Eli Friedman5f2987c2012-02-02 03:46:19 +00003448 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003449 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003450 }
3451
3452 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003453 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3454 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003455
3456 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003457 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003458
3459 // Ignore direct virtual bases.
3460 if (DirectVirtualBases.count(RT))
3461 continue;
3462
John McCall58e6f342010-03-16 05:22:47 +00003463 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003464 // If our base class is invalid, we probably can't get its dtor anyway.
3465 if (BaseClassDecl->isInvalidDecl())
3466 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003467 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003468 continue;
John McCall58e6f342010-03-16 05:22:47 +00003469
Douglas Gregordb89f282010-07-01 22:47:18 +00003470 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003471 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003472 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003473 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003474 << VBase->getType(),
3475 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003476
Eli Friedman5f2987c2012-02-02 03:46:19 +00003477 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003478 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003479 }
3480}
3481
John McCalld226f652010-08-21 09:40:31 +00003482void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003483 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003484 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003485
Mike Stump1eb44332009-09-09 15:08:12 +00003486 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003487 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003488 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003489}
3490
Mike Stump1eb44332009-09-09 15:08:12 +00003491bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003492 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003493 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3494 unsigned DiagID;
3495 AbstractDiagSelID SelID;
3496
3497 public:
3498 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3499 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3500
3501 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003502 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003503 if (SelID == -1)
3504 S.Diag(Loc, DiagID) << T;
3505 else
3506 S.Diag(Loc, DiagID) << SelID << T;
3507 }
3508 } Diagnoser(DiagID, SelID);
3509
3510 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003511}
3512
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003513bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003514 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003515 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003516 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003517
Anders Carlsson11f21a02009-03-23 19:10:31 +00003518 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003519 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003520
Ted Kremenek6217b802009-07-29 21:53:49 +00003521 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003522 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003523 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003524 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003525
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003526 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003527 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003528 }
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Ted Kremenek6217b802009-07-29 21:53:49 +00003530 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003531 if (!RT)
3532 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003533
John McCall86ff3082010-02-04 22:26:26 +00003534 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003535
John McCall94c3b562010-08-18 09:41:07 +00003536 // We can't answer whether something is abstract until it has a
3537 // definition. If it's currently being defined, we'll walk back
3538 // over all the declarations when we have a full definition.
3539 const CXXRecordDecl *Def = RD->getDefinition();
3540 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003541 return false;
3542
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003543 if (!RD->isAbstract())
3544 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003545
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003546 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003547 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003548
John McCall94c3b562010-08-18 09:41:07 +00003549 return true;
3550}
3551
3552void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3553 // Check if we've already emitted the list of pure virtual functions
3554 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003555 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003556 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003557
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003558 CXXFinalOverriderMap FinalOverriders;
3559 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003561 // Keep a set of seen pure methods so we won't diagnose the same method
3562 // more than once.
3563 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3564
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003565 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3566 MEnd = FinalOverriders.end();
3567 M != MEnd;
3568 ++M) {
3569 for (OverridingMethods::iterator SO = M->second.begin(),
3570 SOEnd = M->second.end();
3571 SO != SOEnd; ++SO) {
3572 // C++ [class.abstract]p4:
3573 // A class is abstract if it contains or inherits at least one
3574 // pure virtual function for which the final overrider is pure
3575 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003577 //
3578 if (SO->second.size() != 1)
3579 continue;
3580
3581 if (!SO->second.front().Method->isPure())
3582 continue;
3583
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003584 if (!SeenPureMethods.insert(SO->second.front().Method))
3585 continue;
3586
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003587 Diag(SO->second.front().Method->getLocation(),
3588 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003589 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003590 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003591 }
3592
3593 if (!PureVirtualClassDiagSet)
3594 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3595 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003596}
3597
Anders Carlsson8211eff2009-03-24 01:19:16 +00003598namespace {
John McCall94c3b562010-08-18 09:41:07 +00003599struct AbstractUsageInfo {
3600 Sema &S;
3601 CXXRecordDecl *Record;
3602 CanQualType AbstractType;
3603 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003604
John McCall94c3b562010-08-18 09:41:07 +00003605 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3606 : S(S), Record(Record),
3607 AbstractType(S.Context.getCanonicalType(
3608 S.Context.getTypeDeclType(Record))),
3609 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003610
John McCall94c3b562010-08-18 09:41:07 +00003611 void DiagnoseAbstractType() {
3612 if (Invalid) return;
3613 S.DiagnoseAbstractType(Record);
3614 Invalid = true;
3615 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003616
John McCall94c3b562010-08-18 09:41:07 +00003617 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3618};
3619
3620struct CheckAbstractUsage {
3621 AbstractUsageInfo &Info;
3622 const NamedDecl *Ctx;
3623
3624 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3625 : Info(Info), Ctx(Ctx) {}
3626
3627 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3628 switch (TL.getTypeLocClass()) {
3629#define ABSTRACT_TYPELOC(CLASS, PARENT)
3630#define TYPELOC(CLASS, PARENT) \
3631 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3632#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003633 }
John McCall94c3b562010-08-18 09:41:07 +00003634 }
Mike Stump1eb44332009-09-09 15:08:12 +00003635
John McCall94c3b562010-08-18 09:41:07 +00003636 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3637 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3638 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003639 if (!TL.getArg(I))
3640 continue;
3641
John McCall94c3b562010-08-18 09:41:07 +00003642 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3643 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003644 }
John McCall94c3b562010-08-18 09:41:07 +00003645 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003646
John McCall94c3b562010-08-18 09:41:07 +00003647 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3648 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3649 }
Mike Stump1eb44332009-09-09 15:08:12 +00003650
John McCall94c3b562010-08-18 09:41:07 +00003651 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3652 // Visit the type parameters from a permissive context.
3653 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3654 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3655 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3656 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3657 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3658 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003659 }
John McCall94c3b562010-08-18 09:41:07 +00003660 }
Mike Stump1eb44332009-09-09 15:08:12 +00003661
John McCall94c3b562010-08-18 09:41:07 +00003662 // Visit pointee types from a permissive context.
3663#define CheckPolymorphic(Type) \
3664 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3665 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3666 }
3667 CheckPolymorphic(PointerTypeLoc)
3668 CheckPolymorphic(ReferenceTypeLoc)
3669 CheckPolymorphic(MemberPointerTypeLoc)
3670 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003671 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003672
John McCall94c3b562010-08-18 09:41:07 +00003673 /// Handle all the types we haven't given a more specific
3674 /// implementation for above.
3675 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3676 // Every other kind of type that we haven't called out already
3677 // that has an inner type is either (1) sugar or (2) contains that
3678 // inner type in some way as a subobject.
3679 if (TypeLoc Next = TL.getNextTypeLoc())
3680 return Visit(Next, Sel);
3681
3682 // If there's no inner type and we're in a permissive context,
3683 // don't diagnose.
3684 if (Sel == Sema::AbstractNone) return;
3685
3686 // Check whether the type matches the abstract type.
3687 QualType T = TL.getType();
3688 if (T->isArrayType()) {
3689 Sel = Sema::AbstractArrayType;
3690 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003691 }
John McCall94c3b562010-08-18 09:41:07 +00003692 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3693 if (CT != Info.AbstractType) return;
3694
3695 // It matched; do some magic.
3696 if (Sel == Sema::AbstractArrayType) {
3697 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3698 << T << TL.getSourceRange();
3699 } else {
3700 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3701 << Sel << T << TL.getSourceRange();
3702 }
3703 Info.DiagnoseAbstractType();
3704 }
3705};
3706
3707void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3708 Sema::AbstractDiagSelID Sel) {
3709 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3710}
3711
3712}
3713
3714/// Check for invalid uses of an abstract type in a method declaration.
3715static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3716 CXXMethodDecl *MD) {
3717 // No need to do the check on definitions, which require that
3718 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003719 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003720 return;
3721
3722 // For safety's sake, just ignore it if we don't have type source
3723 // information. This should never happen for non-implicit methods,
3724 // but...
3725 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3726 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3727}
3728
3729/// Check for invalid uses of an abstract type within a class definition.
3730static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3731 CXXRecordDecl *RD) {
3732 for (CXXRecordDecl::decl_iterator
3733 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3734 Decl *D = *I;
3735 if (D->isImplicit()) continue;
3736
3737 // Methods and method templates.
3738 if (isa<CXXMethodDecl>(D)) {
3739 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3740 } else if (isa<FunctionTemplateDecl>(D)) {
3741 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3742 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3743
3744 // Fields and static variables.
3745 } else if (isa<FieldDecl>(D)) {
3746 FieldDecl *FD = cast<FieldDecl>(D);
3747 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3748 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3749 } else if (isa<VarDecl>(D)) {
3750 VarDecl *VD = cast<VarDecl>(D);
3751 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3752 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3753
3754 // Nested classes and class templates.
3755 } else if (isa<CXXRecordDecl>(D)) {
3756 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3757 } else if (isa<ClassTemplateDecl>(D)) {
3758 CheckAbstractClassUsage(Info,
3759 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3760 }
3761 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003762}
3763
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003764/// \brief Perform semantic checks on a class definition that has been
3765/// completing, introducing implicitly-declared members, checking for
3766/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003767void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003768 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003769 return;
3770
John McCall94c3b562010-08-18 09:41:07 +00003771 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3772 AbstractUsageInfo Info(*this, Record);
3773 CheckAbstractClassUsage(Info, Record);
3774 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003775
3776 // If this is not an aggregate type and has no user-declared constructor,
3777 // complain about any non-static data members of reference or const scalar
3778 // type, since they will never get initializers.
3779 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003780 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3781 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003782 bool Complained = false;
3783 for (RecordDecl::field_iterator F = Record->field_begin(),
3784 FEnd = Record->field_end();
3785 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003786 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003787 continue;
3788
Douglas Gregor325e5932010-04-15 00:00:53 +00003789 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003790 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003791 if (!Complained) {
3792 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3793 << Record->getTagKind() << Record;
3794 Complained = true;
3795 }
3796
3797 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3798 << F->getType()->isReferenceType()
3799 << F->getDeclName();
3800 }
3801 }
3802 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003803
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003804 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003805 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003806
3807 if (Record->getIdentifier()) {
3808 // C++ [class.mem]p13:
3809 // If T is the name of a class, then each of the following shall have a
3810 // name different from T:
3811 // - every member of every anonymous union that is a member of class T.
3812 //
3813 // C++ [class.mem]p14:
3814 // In addition, if class T has a user-declared constructor (12.1), every
3815 // non-static data member of class T shall have a name different from T.
3816 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003817 R.first != R.second; ++R.first) {
3818 NamedDecl *D = *R.first;
3819 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3820 isa<IndirectFieldDecl>(D)) {
3821 Diag(D->getLocation(), diag::err_member_name_of_class)
3822 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003823 break;
3824 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003825 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003826 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003827
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003828 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003829 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003830 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003831 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003832 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3833 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3834 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003835
3836 // See if a method overloads virtual methods in a base
3837 /// class without overriding any.
3838 if (!Record->isDependentType()) {
3839 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3840 MEnd = Record->method_end();
3841 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00003842 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003843 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003844 }
3845 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003846
Richard Smith9f569cc2011-10-01 02:31:28 +00003847 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3848 // function that is not a constructor declares that member function to be
3849 // const. [...] The class of which that function is a member shall be
3850 // a literal type.
3851 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003852 // If the class has virtual bases, any constexpr members will already have
3853 // been diagnosed by the checks performed on the member declaration, so
3854 // suppress this (less useful) diagnostic.
3855 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3856 !Record->isLiteral() && !Record->getNumVBases()) {
3857 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3858 MEnd = Record->method_end();
3859 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003860 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003861 switch (Record->getTemplateSpecializationKind()) {
3862 case TSK_ImplicitInstantiation:
3863 case TSK_ExplicitInstantiationDeclaration:
3864 case TSK_ExplicitInstantiationDefinition:
3865 // If a template instantiates to a non-literal type, but its members
3866 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003867 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003868 continue;
3869
3870 case TSK_Undeclared:
3871 case TSK_ExplicitSpecialization:
David Blaikie262bc182012-04-30 02:36:29 +00003872 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
Douglas Gregorf502d8e2012-05-04 16:48:41 +00003873 diag::err_constexpr_method_non_literal);
Richard Smith9f569cc2011-10-01 02:31:28 +00003874 break;
3875 }
3876
3877 // Only produce one error per class.
3878 break;
3879 }
3880 }
3881 }
3882
Sebastian Redlf677ea32011-02-05 19:23:19 +00003883 // Declare inherited constructors. We do this eagerly here because:
3884 // - The standard requires an eager diagnostic for conflicting inherited
3885 // constructors from different classes.
3886 // - The lazy declaration of the other implicit constructors is so as to not
3887 // waste space and performance on classes that are not meant to be
3888 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3889 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003890 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003891}
3892
3893void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003894 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3895 ME = Record->method_end();
Richard Smith3003e1d2012-05-15 04:39:51 +00003896 MI != ME; ++MI)
3897 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
David Blaikie581deb32012-06-06 20:45:41 +00003898 CheckExplicitlyDefaultedSpecialMember(*MI);
Sean Hunt001cad92011-05-10 00:49:42 +00003899}
3900
Richard Smith7756afa2012-06-10 05:43:50 +00003901/// Is the special member function which would be selected to perform the
3902/// specified operation on the specified class type a constexpr constructor?
3903static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3904 Sema::CXXSpecialMember CSM,
3905 bool ConstArg) {
3906 Sema::SpecialMemberOverloadResult *SMOR =
3907 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
3908 false, false, false, false);
3909 if (!SMOR || !SMOR->getMethod())
3910 // A constructor we wouldn't select can't be "involved in initializing"
3911 // anything.
3912 return true;
3913 return SMOR->getMethod()->isConstexpr();
3914}
3915
3916/// Determine whether the specified special member function would be constexpr
3917/// if it were implicitly defined.
3918static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3919 Sema::CXXSpecialMember CSM,
3920 bool ConstArg) {
3921 if (!S.getLangOpts().CPlusPlus0x)
3922 return false;
3923
3924 // C++11 [dcl.constexpr]p4:
3925 // In the definition of a constexpr constructor [...]
3926 switch (CSM) {
3927 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003928 // Since default constructor lookup is essentially trivial (and cannot
3929 // involve, for instance, template instantiation), we compute whether a
3930 // defaulted default constructor is constexpr directly within CXXRecordDecl.
3931 //
3932 // This is important for performance; we need to know whether the default
3933 // constructor is constexpr to determine whether the type is a literal type.
3934 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
3935
Richard Smith7756afa2012-06-10 05:43:50 +00003936 case Sema::CXXCopyConstructor:
3937 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003938 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00003939 break;
3940
3941 case Sema::CXXCopyAssignment:
3942 case Sema::CXXMoveAssignment:
3943 case Sema::CXXDestructor:
3944 case Sema::CXXInvalid:
3945 return false;
3946 }
3947
3948 // -- if the class is a non-empty union, or for each non-empty anonymous
3949 // union member of a non-union class, exactly one non-static data member
3950 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00003951 //
3952 // If we squint, this is guaranteed, since exactly one non-static data member
3953 // will be initialized (if the constructor isn't deleted), we just don't know
3954 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00003955 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00003956 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00003957
3958 // -- the class shall not have any virtual base classes;
3959 if (ClassDecl->getNumVBases())
3960 return false;
3961
3962 // -- every constructor involved in initializing [...] base class
3963 // sub-objects shall be a constexpr constructor;
3964 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
3965 BEnd = ClassDecl->bases_end();
3966 B != BEnd; ++B) {
3967 const RecordType *BaseType = B->getType()->getAs<RecordType>();
3968 if (!BaseType) continue;
3969
3970 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3971 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
3972 return false;
3973 }
3974
3975 // -- every constructor involved in initializing non-static data members
3976 // [...] shall be a constexpr constructor;
3977 // -- every non-static data member and base class sub-object shall be
3978 // initialized
3979 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
3980 FEnd = ClassDecl->field_end();
3981 F != FEnd; ++F) {
3982 if (F->isInvalidDecl())
3983 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00003984 if (const RecordType *RecordTy =
3985 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00003986 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
3987 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
3988 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00003989 }
3990 }
3991
3992 // All OK, it's constexpr!
3993 return true;
3994}
3995
Richard Smithb9d0b762012-07-27 04:22:15 +00003996static Sema::ImplicitExceptionSpecification
3997computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
3998 switch (S.getSpecialMember(MD)) {
3999 case Sema::CXXDefaultConstructor:
4000 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4001 case Sema::CXXCopyConstructor:
4002 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4003 case Sema::CXXCopyAssignment:
4004 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4005 case Sema::CXXMoveConstructor:
4006 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4007 case Sema::CXXMoveAssignment:
4008 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4009 case Sema::CXXDestructor:
4010 return S.ComputeDefaultedDtorExceptionSpec(MD);
4011 case Sema::CXXInvalid:
4012 break;
4013 }
4014 llvm_unreachable("only special members have implicit exception specs");
4015}
4016
Richard Smithdd25e802012-07-30 23:48:14 +00004017static void
4018updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4019 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4020 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4021 ExceptSpec.getEPI(EPI);
4022 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4023 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4024 FPT->getNumArgs(), EPI));
4025 FD->setType(QualType(NewFPT, 0));
4026}
4027
Richard Smithb9d0b762012-07-27 04:22:15 +00004028void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4029 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4030 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4031 return;
4032
Richard Smithdd25e802012-07-30 23:48:14 +00004033 // Evaluate the exception specification.
4034 ImplicitExceptionSpecification ExceptSpec =
4035 computeImplicitExceptionSpec(*this, Loc, MD);
4036
4037 // Update the type of the special member to use it.
4038 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4039
4040 // A user-provided destructor can be defined outside the class. When that
4041 // happens, be sure to update the exception specification on both
4042 // declarations.
4043 const FunctionProtoType *CanonicalFPT =
4044 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4045 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4046 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4047 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004048}
4049
4050static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4051static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4052
Richard Smith3003e1d2012-05-15 04:39:51 +00004053void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4054 CXXRecordDecl *RD = MD->getParent();
4055 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004056
Richard Smith3003e1d2012-05-15 04:39:51 +00004057 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4058 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004059
4060 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004061 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004062 bool First = MD == MD->getCanonicalDecl();
4063
4064 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004065
4066 // C++11 [dcl.fct.def.default]p1:
4067 // A function that is explicitly defaulted shall
4068 // -- be a special member function (checked elsewhere),
4069 // -- have the same type (except for ref-qualifiers, and except that a
4070 // copy operation can take a non-const reference) as an implicit
4071 // declaration, and
4072 // -- not have default arguments.
4073 unsigned ExpectedParams = 1;
4074 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4075 ExpectedParams = 0;
4076 if (MD->getNumParams() != ExpectedParams) {
4077 // This also checks for default arguments: a copy or move constructor with a
4078 // default argument is classified as a default constructor, and assignment
4079 // operations and destructors can't have default arguments.
4080 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4081 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004082 HadError = true;
4083 }
4084
Richard Smith3003e1d2012-05-15 04:39:51 +00004085 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004086
Richard Smithb9d0b762012-07-27 04:22:15 +00004087 // Compute argument constness, constexpr, and triviality.
Richard Smith7756afa2012-06-10 05:43:50 +00004088 bool CanHaveConstParam = false;
Axel Naumann8f411c32012-09-17 14:26:53 +00004089 bool Trivial = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004090 switch (CSM) {
4091 case CXXDefaultConstructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004092 Trivial = RD->hasTrivialDefaultConstructor();
4093 break;
4094 case CXXCopyConstructor:
Richard Smithb9d0b762012-07-27 04:22:15 +00004095 CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004096 Trivial = RD->hasTrivialCopyConstructor();
4097 break;
4098 case CXXCopyAssignment:
Richard Smithb9d0b762012-07-27 04:22:15 +00004099 CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004100 Trivial = RD->hasTrivialCopyAssignment();
4101 break;
4102 case CXXMoveConstructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004103 Trivial = RD->hasTrivialMoveConstructor();
4104 break;
4105 case CXXMoveAssignment:
Richard Smith3003e1d2012-05-15 04:39:51 +00004106 Trivial = RD->hasTrivialMoveAssignment();
4107 break;
4108 case CXXDestructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004109 Trivial = RD->hasTrivialDestructor();
4110 break;
4111 case CXXInvalid:
4112 llvm_unreachable("non-special member explicitly defaulted!");
4113 }
Sean Hunt2b188082011-05-14 05:23:28 +00004114
Richard Smith3003e1d2012-05-15 04:39:51 +00004115 QualType ReturnType = Context.VoidTy;
4116 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4117 // Check for return type matching.
4118 ReturnType = Type->getResultType();
4119 QualType ExpectedReturnType =
4120 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4121 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4122 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4123 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4124 HadError = true;
4125 }
4126
4127 // A defaulted special member cannot have cv-qualifiers.
4128 if (Type->getTypeQuals()) {
4129 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4130 << (CSM == CXXMoveAssignment);
4131 HadError = true;
4132 }
4133 }
4134
4135 // Check for parameter type matching.
4136 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004137 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004138 if (ExpectedParams && ArgType->isReferenceType()) {
4139 // Argument must be reference to possibly-const T.
4140 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004141 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004142
4143 if (ReferentType.isVolatileQualified()) {
4144 Diag(MD->getLocation(),
4145 diag::err_defaulted_special_member_volatile_param) << CSM;
4146 HadError = true;
4147 }
4148
Richard Smith7756afa2012-06-10 05:43:50 +00004149 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004150 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4151 Diag(MD->getLocation(),
4152 diag::err_defaulted_special_member_copy_const_param)
4153 << (CSM == CXXCopyAssignment);
4154 // FIXME: Explain why this special member can't be const.
4155 } else {
4156 Diag(MD->getLocation(),
4157 diag::err_defaulted_special_member_move_const_param)
4158 << (CSM == CXXMoveAssignment);
4159 }
4160 HadError = true;
4161 }
4162
4163 // If a function is explicitly defaulted on its first declaration, it shall
4164 // have the same parameter type as if it had been implicitly declared.
4165 // (Presumably this is to prevent it from being trivial?)
Richard Smith7756afa2012-06-10 05:43:50 +00004166 if (!HasConstParam && CanHaveConstParam && First)
Richard Smith3003e1d2012-05-15 04:39:51 +00004167 Diag(MD->getLocation(),
4168 diag::err_defaulted_special_member_copy_non_const_param)
4169 << (CSM == CXXCopyAssignment);
4170 } else if (ExpectedParams) {
4171 // A copy assignment operator can take its argument by value, but a
4172 // defaulted one cannot.
4173 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004174 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004175 HadError = true;
4176 }
Sean Huntbe631222011-05-17 20:44:43 +00004177
Richard Smithb9d0b762012-07-27 04:22:15 +00004178 // Rebuild the type with the implicit exception specification added, if we
4179 // are going to need it.
4180 const FunctionProtoType *ImplicitType = 0;
4181 if (First || Type->hasExceptionSpec()) {
4182 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4183 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4184 ImplicitType = cast<FunctionProtoType>(
4185 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4186 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004187
Richard Smith61802452011-12-22 02:22:31 +00004188 // C++11 [dcl.fct.def.default]p2:
4189 // An explicitly-defaulted function may be declared constexpr only if it
4190 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004191 // Do not apply this rule to members of class templates, since core issue 1358
4192 // makes such functions always instantiate to constexpr functions. For
4193 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004194 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4195 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004196 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4197 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4198 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004199 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004200 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004201 }
4202 // and may have an explicit exception-specification only if it is compatible
4203 // with the exception-specification on the implicit declaration.
Richard Smith3003e1d2012-05-15 04:39:51 +00004204 if (Type->hasExceptionSpec() &&
4205 CheckEquivalentExceptionSpec(
4206 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4207 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4208 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004209
4210 // If a function is explicitly defaulted on its first declaration,
4211 if (First) {
4212 // -- it is implicitly considered to be constexpr if the implicit
4213 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004214 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004215
Richard Smith3003e1d2012-05-15 04:39:51 +00004216 // -- it is implicitly considered to have the same exception-specification
4217 // as if it had been implicitly declared,
4218 MD->setType(QualType(ImplicitType, 0));
Richard Smithe653ba22012-02-26 00:31:33 +00004219
4220 // Such a function is also trivial if the implicitly-declared function
4221 // would have been.
Richard Smith3003e1d2012-05-15 04:39:51 +00004222 MD->setTrivial(Trivial);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004223 }
4224
Richard Smith3003e1d2012-05-15 04:39:51 +00004225 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004226 if (First) {
4227 MD->setDeletedAsWritten();
4228 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004229 // C++11 [dcl.fct.def.default]p4:
4230 // [For a] user-provided explicitly-defaulted function [...] if such a
4231 // function is implicitly defined as deleted, the program is ill-formed.
4232 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4233 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004234 }
4235 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004236
Richard Smith3003e1d2012-05-15 04:39:51 +00004237 if (HadError)
4238 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004239}
4240
Richard Smith7d5088a2012-02-18 02:02:13 +00004241namespace {
4242struct SpecialMemberDeletionInfo {
4243 Sema &S;
4244 CXXMethodDecl *MD;
4245 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004246 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004247
4248 // Properties of the special member, computed for convenience.
4249 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4250 SourceLocation Loc;
4251
4252 bool AllFieldsAreConst;
4253
4254 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004255 Sema::CXXSpecialMember CSM, bool Diagnose)
4256 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004257 IsConstructor(false), IsAssignment(false), IsMove(false),
4258 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4259 AllFieldsAreConst(true) {
4260 switch (CSM) {
4261 case Sema::CXXDefaultConstructor:
4262 case Sema::CXXCopyConstructor:
4263 IsConstructor = true;
4264 break;
4265 case Sema::CXXMoveConstructor:
4266 IsConstructor = true;
4267 IsMove = true;
4268 break;
4269 case Sema::CXXCopyAssignment:
4270 IsAssignment = true;
4271 break;
4272 case Sema::CXXMoveAssignment:
4273 IsAssignment = true;
4274 IsMove = true;
4275 break;
4276 case Sema::CXXDestructor:
4277 break;
4278 case Sema::CXXInvalid:
4279 llvm_unreachable("invalid special member kind");
4280 }
4281
4282 if (MD->getNumParams()) {
4283 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4284 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4285 }
4286 }
4287
4288 bool inUnion() const { return MD->getParent()->isUnion(); }
4289
4290 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004291 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4292 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004293 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004294 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4295 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4296 Quals = 0;
4297 return S.LookupSpecialMember(Class, CSM,
4298 ConstArg || (Quals & Qualifiers::Const),
4299 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004300 MD->getRefQualifier() == RQ_RValue,
4301 TQ & Qualifiers::Const,
4302 TQ & Qualifiers::Volatile);
4303 }
4304
Richard Smith6c4c36c2012-03-30 20:53:28 +00004305 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004306
Richard Smith6c4c36c2012-03-30 20:53:28 +00004307 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004308 bool shouldDeleteForField(FieldDecl *FD);
4309 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004310
Richard Smith517bb842012-07-18 03:51:16 +00004311 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4312 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004313 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4314 Sema::SpecialMemberOverloadResult *SMOR,
4315 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004316
4317 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004318};
4319}
4320
John McCall12d8d802012-04-09 20:53:23 +00004321/// Is the given special member inaccessible when used on the given
4322/// sub-object.
4323bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4324 CXXMethodDecl *target) {
4325 /// If we're operating on a base class, the object type is the
4326 /// type of this special member.
4327 QualType objectTy;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004328 AccessSpecifier access = target->getAccess();
John McCall12d8d802012-04-09 20:53:23 +00004329 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4330 objectTy = S.Context.getTypeDeclType(MD->getParent());
4331 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4332
4333 // If we're operating on a field, the object type is the type of the field.
4334 } else {
4335 objectTy = S.Context.getTypeDeclType(target->getParent());
4336 }
4337
4338 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4339}
4340
Richard Smith6c4c36c2012-03-30 20:53:28 +00004341/// Check whether we should delete a special member due to the implicit
4342/// definition containing a call to a special member of a subobject.
4343bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4344 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4345 bool IsDtorCallInCtor) {
4346 CXXMethodDecl *Decl = SMOR->getMethod();
4347 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4348
4349 int DiagKind = -1;
4350
4351 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4352 DiagKind = !Decl ? 0 : 1;
4353 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4354 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004355 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004356 DiagKind = 3;
4357 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4358 !Decl->isTrivial()) {
4359 // A member of a union must have a trivial corresponding special member.
4360 // As a weird special case, a destructor call from a union's constructor
4361 // must be accessible and non-deleted, but need not be trivial. Such a
4362 // destructor is never actually called, but is semantically checked as
4363 // if it were.
4364 DiagKind = 4;
4365 }
4366
4367 if (DiagKind == -1)
4368 return false;
4369
4370 if (Diagnose) {
4371 if (Field) {
4372 S.Diag(Field->getLocation(),
4373 diag::note_deleted_special_member_class_subobject)
4374 << CSM << MD->getParent() << /*IsField*/true
4375 << Field << DiagKind << IsDtorCallInCtor;
4376 } else {
4377 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4378 S.Diag(Base->getLocStart(),
4379 diag::note_deleted_special_member_class_subobject)
4380 << CSM << MD->getParent() << /*IsField*/false
4381 << Base->getType() << DiagKind << IsDtorCallInCtor;
4382 }
4383
4384 if (DiagKind == 1)
4385 S.NoteDeletedFunction(Decl);
4386 // FIXME: Explain inaccessibility if DiagKind == 3.
4387 }
4388
4389 return true;
4390}
4391
Richard Smith9a561d52012-02-26 09:11:52 +00004392/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004393/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004394bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004395 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004396 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004397
4398 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004399 // -- any direct or virtual base class, or non-static data member with no
4400 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004401 // either M has no default constructor or overload resolution as applied
4402 // to M's default constructor results in an ambiguity or in a function
4403 // that is deleted or inaccessible
4404 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4405 // -- a direct or virtual base class B that cannot be copied/moved because
4406 // overload resolution, as applied to B's corresponding special member,
4407 // results in an ambiguity or a function that is deleted or inaccessible
4408 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004409 // C++11 [class.dtor]p5:
4410 // -- any direct or virtual base class [...] has a type with a destructor
4411 // that is deleted or inaccessible
4412 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004413 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004414 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004415 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004416
Richard Smith6c4c36c2012-03-30 20:53:28 +00004417 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4418 // -- any direct or virtual base class or non-static data member has a
4419 // type with a destructor that is deleted or inaccessible
4420 if (IsConstructor) {
4421 Sema::SpecialMemberOverloadResult *SMOR =
4422 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4423 false, false, false, false, false);
4424 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4425 return true;
4426 }
4427
Richard Smith9a561d52012-02-26 09:11:52 +00004428 return false;
4429}
4430
4431/// Check whether we should delete a special member function due to the class
4432/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004433bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004434 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004435 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004436}
4437
4438/// Check whether we should delete a special member function due to the class
4439/// having a particular non-static data member.
4440bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4441 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4442 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4443
4444 if (CSM == Sema::CXXDefaultConstructor) {
4445 // For a default constructor, all references must be initialized in-class
4446 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004447 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4448 if (Diagnose)
4449 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4450 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004451 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004452 }
Richard Smith79363f52012-02-27 06:07:25 +00004453 // C++11 [class.ctor]p5: any non-variant non-static data member of
4454 // const-qualified type (or array thereof) with no
4455 // brace-or-equal-initializer does not have a user-provided default
4456 // constructor.
4457 if (!inUnion() && FieldType.isConstQualified() &&
4458 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004459 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4460 if (Diagnose)
4461 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004462 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004463 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004464 }
4465
4466 if (inUnion() && !FieldType.isConstQualified())
4467 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004468 } else if (CSM == Sema::CXXCopyConstructor) {
4469 // For a copy constructor, data members must not be of rvalue reference
4470 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004471 if (FieldType->isRValueReferenceType()) {
4472 if (Diagnose)
4473 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4474 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004475 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004476 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004477 } else if (IsAssignment) {
4478 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004479 if (FieldType->isReferenceType()) {
4480 if (Diagnose)
4481 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4482 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004483 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004484 }
4485 if (!FieldRecord && FieldType.isConstQualified()) {
4486 // C++11 [class.copy]p23:
4487 // -- a non-static data member of const non-class type (or array thereof)
4488 if (Diagnose)
4489 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004490 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004491 return true;
4492 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004493 }
4494
4495 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004496 // Some additional restrictions exist on the variant members.
4497 if (!inUnion() && FieldRecord->isUnion() &&
4498 FieldRecord->isAnonymousStructOrUnion()) {
4499 bool AllVariantFieldsAreConst = true;
4500
Richard Smithdf8dc862012-03-29 19:00:10 +00004501 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004502 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4503 UE = FieldRecord->field_end();
4504 UI != UE; ++UI) {
4505 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004506
4507 if (!UnionFieldType.isConstQualified())
4508 AllVariantFieldsAreConst = false;
4509
Richard Smith9a561d52012-02-26 09:11:52 +00004510 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4511 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004512 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4513 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004514 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004515 }
4516
4517 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004518 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004519 FieldRecord->field_begin() != FieldRecord->field_end()) {
4520 if (Diagnose)
4521 S.Diag(FieldRecord->getLocation(),
4522 diag::note_deleted_default_ctor_all_const)
4523 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004524 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004525 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004526
Richard Smithdf8dc862012-03-29 19:00:10 +00004527 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004528 // This is technically non-conformant, but sanity demands it.
4529 return false;
4530 }
4531
Richard Smith517bb842012-07-18 03:51:16 +00004532 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4533 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004534 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004535 }
4536
4537 return false;
4538}
4539
4540/// C++11 [class.ctor] p5:
4541/// A defaulted default constructor for a class X is defined as deleted if
4542/// X is a union and all of its variant members are of const-qualified type.
4543bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004544 // This is a silly definition, because it gives an empty union a deleted
4545 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004546 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4547 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4548 if (Diagnose)
4549 S.Diag(MD->getParent()->getLocation(),
4550 diag::note_deleted_default_ctor_all_const)
4551 << MD->getParent() << /*not anonymous union*/0;
4552 return true;
4553 }
4554 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004555}
4556
4557/// Determine whether a defaulted special member function should be defined as
4558/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4559/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004560bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4561 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004562 if (MD->isInvalidDecl())
4563 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004564 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004565 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004566 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004567 return false;
4568
Richard Smith7d5088a2012-02-18 02:02:13 +00004569 // C++11 [expr.lambda.prim]p19:
4570 // The closure type associated with a lambda-expression has a
4571 // deleted (8.4.3) default constructor and a deleted copy
4572 // assignment operator.
4573 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004574 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4575 if (Diagnose)
4576 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004577 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004578 }
4579
Richard Smith5bdaac52012-04-02 20:59:25 +00004580 // For an anonymous struct or union, the copy and assignment special members
4581 // will never be used, so skip the check. For an anonymous union declared at
4582 // namespace scope, the constructor and destructor are used.
4583 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4584 RD->isAnonymousStructOrUnion())
4585 return false;
4586
Richard Smith6c4c36c2012-03-30 20:53:28 +00004587 // C++11 [class.copy]p7, p18:
4588 // If the class definition declares a move constructor or move assignment
4589 // operator, an implicitly declared copy constructor or copy assignment
4590 // operator is defined as deleted.
4591 if (MD->isImplicit() &&
4592 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4593 CXXMethodDecl *UserDeclaredMove = 0;
4594
4595 // In Microsoft mode, a user-declared move only causes the deletion of the
4596 // corresponding copy operation, not both copy operations.
4597 if (RD->hasUserDeclaredMoveConstructor() &&
4598 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4599 if (!Diagnose) return true;
4600 UserDeclaredMove = RD->getMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00004601 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004602 } else if (RD->hasUserDeclaredMoveAssignment() &&
4603 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4604 if (!Diagnose) return true;
4605 UserDeclaredMove = RD->getMoveAssignmentOperator();
Richard Smith1c931be2012-04-02 18:40:40 +00004606 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004607 }
4608
4609 if (UserDeclaredMove) {
4610 Diag(UserDeclaredMove->getLocation(),
4611 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004612 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004613 << UserDeclaredMove->isMoveAssignmentOperator();
4614 return true;
4615 }
4616 }
Sean Hunte16da072011-10-10 06:18:57 +00004617
Richard Smith5bdaac52012-04-02 20:59:25 +00004618 // Do access control from the special member function
4619 ContextRAII MethodContext(*this, MD);
4620
Richard Smith9a561d52012-02-26 09:11:52 +00004621 // C++11 [class.dtor]p5:
4622 // -- for a virtual destructor, lookup of the non-array deallocation function
4623 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004624 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004625 FunctionDecl *OperatorDelete = 0;
4626 DeclarationName Name =
4627 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4628 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004629 OperatorDelete, false)) {
4630 if (Diagnose)
4631 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004632 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004633 }
Richard Smith9a561d52012-02-26 09:11:52 +00004634 }
4635
Richard Smith6c4c36c2012-03-30 20:53:28 +00004636 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004637
Sean Huntcdee3fe2011-05-11 22:34:38 +00004638 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004639 BE = RD->bases_end(); BI != BE; ++BI)
4640 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004641 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004642 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004643
4644 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004645 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004646 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004647 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004648
4649 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004650 FE = RD->field_end(); FI != FE; ++FI)
4651 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004652 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004653 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004654
Richard Smith7d5088a2012-02-18 02:02:13 +00004655 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004656 return true;
4657
4658 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004659}
4660
4661/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004662namespace {
4663 struct FindHiddenVirtualMethodData {
4664 Sema *S;
4665 CXXMethodDecl *Method;
4666 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004667 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004668 };
4669}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004670
4671/// \brief Member lookup function that determines whether a given C++
4672/// method overloads virtual methods in a base class without overriding any,
4673/// to be used with CXXRecordDecl::lookupInBases().
4674static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4675 CXXBasePath &Path,
4676 void *UserData) {
4677 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4678
4679 FindHiddenVirtualMethodData &Data
4680 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4681
4682 DeclarationName Name = Data.Method->getDeclName();
4683 assert(Name.getNameKind() == DeclarationName::Identifier);
4684
4685 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004686 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004687 for (Path.Decls = BaseRecord->lookup(Name);
4688 Path.Decls.first != Path.Decls.second;
4689 ++Path.Decls.first) {
4690 NamedDecl *D = *Path.Decls.first;
4691 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004692 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004693 foundSameNameMethod = true;
4694 // Interested only in hidden virtual methods.
4695 if (!MD->isVirtual())
4696 continue;
4697 // If the method we are checking overrides a method from its base
4698 // don't warn about the other overloaded methods.
4699 if (!Data.S->IsOverload(Data.Method, MD, false))
4700 return true;
4701 // Collect the overload only if its hidden.
4702 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4703 overloadedMethods.push_back(MD);
4704 }
4705 }
4706
4707 if (foundSameNameMethod)
4708 Data.OverloadedMethods.append(overloadedMethods.begin(),
4709 overloadedMethods.end());
4710 return foundSameNameMethod;
4711}
4712
4713/// \brief See if a method overloads virtual methods in a base class without
4714/// overriding any.
4715void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4716 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004717 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004718 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00004719 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004720 return;
4721
4722 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4723 /*bool RecordPaths=*/false,
4724 /*bool DetectVirtual=*/false);
4725 FindHiddenVirtualMethodData Data;
4726 Data.Method = MD;
4727 Data.S = this;
4728
4729 // Keep the base methods that were overriden or introduced in the subclass
4730 // by 'using' in a set. A base method not in this set is hidden.
4731 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4732 res.first != res.second; ++res.first) {
4733 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4734 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4735 E = MD->end_overridden_methods();
4736 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004737 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004738 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4739 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004740 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004741 }
4742
4743 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4744 !Data.OverloadedMethods.empty()) {
4745 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4746 << MD << (Data.OverloadedMethods.size() > 1);
4747
4748 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4749 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4750 Diag(overloadedMD->getLocation(),
4751 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4752 }
4753 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004754}
4755
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004756void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004757 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004758 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004759 SourceLocation RBrac,
4760 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004761 if (!TagDecl)
4762 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004763
Douglas Gregor42af25f2009-05-11 19:58:34 +00004764 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004765
Rafael Espindolaf729ce02012-07-12 04:32:30 +00004766 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4767 if (l->getKind() != AttributeList::AT_Visibility)
4768 continue;
4769 l->setInvalid();
4770 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
4771 l->getName();
4772 }
4773
David Blaikie77b6de02011-09-22 02:58:26 +00004774 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004775 // strict aliasing violation!
4776 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004777 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004778
Douglas Gregor23c94db2010-07-02 17:43:08 +00004779 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004780 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004781}
4782
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004783/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4784/// special functions, such as the default constructor, copy
4785/// constructor, or destructor, to the given C++ class (C++
4786/// [special]p1). This routine can only be executed just before the
4787/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004788void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004789 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004790 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004791
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004792 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004793 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004794
David Blaikie4e4d0842012-03-11 07:00:24 +00004795 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004796 ++ASTContext::NumImplicitMoveConstructors;
4797
Douglas Gregora376d102010-07-02 21:50:04 +00004798 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4799 ++ASTContext::NumImplicitCopyAssignmentOperators;
4800
4801 // If we have a dynamic class, then the copy assignment operator may be
4802 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4803 // it shows up in the right place in the vtable and that we diagnose
4804 // problems with the implicit exception specification.
4805 if (ClassDecl->isDynamicClass())
4806 DeclareImplicitCopyAssignment(ClassDecl);
4807 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004808
Richard Smith1c931be2012-04-02 18:40:40 +00004809 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00004810 ++ASTContext::NumImplicitMoveAssignmentOperators;
4811
4812 // Likewise for the move assignment operator.
4813 if (ClassDecl->isDynamicClass())
4814 DeclareImplicitMoveAssignment(ClassDecl);
4815 }
4816
Douglas Gregor4923aa22010-07-02 20:37:36 +00004817 if (!ClassDecl->hasUserDeclaredDestructor()) {
4818 ++ASTContext::NumImplicitDestructors;
4819
4820 // If we have a dynamic class, then the destructor may be virtual, so we
4821 // have to declare the destructor immediately. This ensures that, e.g., it
4822 // shows up in the right place in the vtable and that we diagnose problems
4823 // with the implicit exception specification.
4824 if (ClassDecl->isDynamicClass())
4825 DeclareImplicitDestructor(ClassDecl);
4826 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004827}
4828
Francois Pichet8387e2a2011-04-22 22:18:13 +00004829void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4830 if (!D)
4831 return;
4832
4833 int NumParamList = D->getNumTemplateParameterLists();
4834 for (int i = 0; i < NumParamList; i++) {
4835 TemplateParameterList* Params = D->getTemplateParameterList(i);
4836 for (TemplateParameterList::iterator Param = Params->begin(),
4837 ParamEnd = Params->end();
4838 Param != ParamEnd; ++Param) {
4839 NamedDecl *Named = cast<NamedDecl>(*Param);
4840 if (Named->getDeclName()) {
4841 S->AddDecl(Named);
4842 IdResolver.AddDecl(Named);
4843 }
4844 }
4845 }
4846}
4847
John McCalld226f652010-08-21 09:40:31 +00004848void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004849 if (!D)
4850 return;
4851
4852 TemplateParameterList *Params = 0;
4853 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4854 Params = Template->getTemplateParameters();
4855 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4856 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4857 Params = PartialSpec->getTemplateParameters();
4858 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004859 return;
4860
Douglas Gregor6569d682009-05-27 23:11:45 +00004861 for (TemplateParameterList::iterator Param = Params->begin(),
4862 ParamEnd = Params->end();
4863 Param != ParamEnd; ++Param) {
4864 NamedDecl *Named = cast<NamedDecl>(*Param);
4865 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004866 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004867 IdResolver.AddDecl(Named);
4868 }
4869 }
4870}
4871
John McCalld226f652010-08-21 09:40:31 +00004872void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004873 if (!RecordD) return;
4874 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004875 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004876 PushDeclContext(S, Record);
4877}
4878
John McCalld226f652010-08-21 09:40:31 +00004879void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004880 if (!RecordD) return;
4881 PopDeclContext();
4882}
4883
Douglas Gregor72b505b2008-12-16 21:30:33 +00004884/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4885/// parsing a top-level (non-nested) C++ class, and we are now
4886/// parsing those parts of the given Method declaration that could
4887/// not be parsed earlier (C++ [class.mem]p2), such as default
4888/// arguments. This action should enter the scope of the given
4889/// Method declaration as if we had just parsed the qualified method
4890/// name. However, it should not bring the parameters into scope;
4891/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004892void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004893}
4894
4895/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4896/// C++ method declaration. We're (re-)introducing the given
4897/// function parameter into scope for use in parsing later parts of
4898/// the method declaration. For example, we could see an
4899/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004900void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004901 if (!ParamD)
4902 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004903
John McCalld226f652010-08-21 09:40:31 +00004904 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004905
4906 // If this parameter has an unparsed default argument, clear it out
4907 // to make way for the parsed default argument.
4908 if (Param->hasUnparsedDefaultArg())
4909 Param->setDefaultArg(0);
4910
John McCalld226f652010-08-21 09:40:31 +00004911 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004912 if (Param->getDeclName())
4913 IdResolver.AddDecl(Param);
4914}
4915
4916/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4917/// processing the delayed method declaration for Method. The method
4918/// declaration is now considered finished. There may be a separate
4919/// ActOnStartOfFunctionDef action later (not necessarily
4920/// immediately!) for this method, if it was also defined inside the
4921/// class body.
John McCalld226f652010-08-21 09:40:31 +00004922void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004923 if (!MethodD)
4924 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004925
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004926 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004927
John McCalld226f652010-08-21 09:40:31 +00004928 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004929
4930 // Now that we have our default arguments, check the constructor
4931 // again. It could produce additional diagnostics or affect whether
4932 // the class has implicitly-declared destructors, among other
4933 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004934 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4935 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004936
4937 // Check the default arguments, which we may have added.
4938 if (!Method->isInvalidDecl())
4939 CheckCXXDefaultArguments(Method);
4940}
4941
Douglas Gregor42a552f2008-11-05 20:51:48 +00004942/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004943/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004944/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004945/// emit diagnostics and set the invalid bit to true. In any case, the type
4946/// will be updated to reflect a well-formed type for the constructor and
4947/// returned.
4948QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004949 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004950 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004951
4952 // C++ [class.ctor]p3:
4953 // A constructor shall not be virtual (10.3) or static (9.4). A
4954 // constructor can be invoked for a const, volatile or const
4955 // volatile object. A constructor shall not be declared const,
4956 // volatile, or const volatile (9.3.2).
4957 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004958 if (!D.isInvalidType())
4959 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4960 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4961 << SourceRange(D.getIdentifierLoc());
4962 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004963 }
John McCalld931b082010-08-26 03:08:43 +00004964 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004965 if (!D.isInvalidType())
4966 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4967 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4968 << SourceRange(D.getIdentifierLoc());
4969 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004970 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004971 }
Mike Stump1eb44332009-09-09 15:08:12 +00004972
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004973 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004974 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004975 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004976 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4977 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004978 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004979 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4980 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004981 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004982 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4983 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004984 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004985 }
Mike Stump1eb44332009-09-09 15:08:12 +00004986
Douglas Gregorc938c162011-01-26 05:01:58 +00004987 // C++0x [class.ctor]p4:
4988 // A constructor shall not be declared with a ref-qualifier.
4989 if (FTI.hasRefQualifier()) {
4990 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4991 << FTI.RefQualifierIsLValueRef
4992 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4993 D.setInvalidType();
4994 }
4995
Douglas Gregor42a552f2008-11-05 20:51:48 +00004996 // Rebuild the function type "R" without any type qualifiers (in
4997 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004998 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004999 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005000 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5001 return R;
5002
5003 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5004 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005005 EPI.RefQualifier = RQ_None;
5006
Chris Lattner65401802009-04-25 08:28:21 +00005007 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005008 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005009}
5010
Douglas Gregor72b505b2008-12-16 21:30:33 +00005011/// CheckConstructor - Checks a fully-formed constructor for
5012/// well-formedness, issuing any diagnostics required. Returns true if
5013/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005014void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005015 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005016 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5017 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005018 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005019
5020 // C++ [class.copy]p3:
5021 // A declaration of a constructor for a class X is ill-formed if
5022 // its first parameter is of type (optionally cv-qualified) X and
5023 // either there are no other parameters or else all other
5024 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005025 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005026 ((Constructor->getNumParams() == 1) ||
5027 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005028 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5029 Constructor->getTemplateSpecializationKind()
5030 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005031 QualType ParamType = Constructor->getParamDecl(0)->getType();
5032 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5033 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005034 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005035 const char *ConstRef
5036 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5037 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005038 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005039 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005040
5041 // FIXME: Rather that making the constructor invalid, we should endeavor
5042 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005043 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005044 }
5045 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005046}
5047
John McCall15442822010-08-04 01:04:25 +00005048/// CheckDestructor - Checks a fully-formed destructor definition for
5049/// well-formedness, issuing any diagnostics required. Returns true
5050/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005051bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005052 CXXRecordDecl *RD = Destructor->getParent();
5053
5054 if (Destructor->isVirtual()) {
5055 SourceLocation Loc;
5056
5057 if (!Destructor->isImplicit())
5058 Loc = Destructor->getLocation();
5059 else
5060 Loc = RD->getLocation();
5061
5062 // If we have a virtual destructor, look up the deallocation function
5063 FunctionDecl *OperatorDelete = 0;
5064 DeclarationName Name =
5065 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005066 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005067 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005068
Eli Friedman5f2987c2012-02-02 03:46:19 +00005069 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005070
5071 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005072 }
Anders Carlsson37909802009-11-30 21:24:50 +00005073
5074 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005075}
5076
Mike Stump1eb44332009-09-09 15:08:12 +00005077static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005078FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5079 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5080 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005081 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005082}
5083
Douglas Gregor42a552f2008-11-05 20:51:48 +00005084/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5085/// the well-formednes of the destructor declarator @p D with type @p
5086/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005087/// emit diagnostics and set the declarator to invalid. Even if this happens,
5088/// will be updated to reflect a well-formed type for the destructor and
5089/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005090QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005091 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005092 // C++ [class.dtor]p1:
5093 // [...] A typedef-name that names a class is a class-name
5094 // (7.1.3); however, a typedef-name that names a class shall not
5095 // be used as the identifier in the declarator for a destructor
5096 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005097 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005098 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005099 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005100 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005101 else if (const TemplateSpecializationType *TST =
5102 DeclaratorType->getAs<TemplateSpecializationType>())
5103 if (TST->isTypeAlias())
5104 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5105 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005106
5107 // C++ [class.dtor]p2:
5108 // A destructor is used to destroy objects of its class type. A
5109 // destructor takes no parameters, and no return type can be
5110 // specified for it (not even void). The address of a destructor
5111 // shall not be taken. A destructor shall not be static. A
5112 // destructor can be invoked for a const, volatile or const
5113 // volatile object. A destructor shall not be declared const,
5114 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005115 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005116 if (!D.isInvalidType())
5117 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5118 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005119 << SourceRange(D.getIdentifierLoc())
5120 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5121
John McCalld931b082010-08-26 03:08:43 +00005122 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005123 }
Chris Lattner65401802009-04-25 08:28:21 +00005124 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005125 // Destructors don't have return types, but the parser will
5126 // happily parse something like:
5127 //
5128 // class X {
5129 // float ~X();
5130 // };
5131 //
5132 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005133 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5134 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5135 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005136 }
Mike Stump1eb44332009-09-09 15:08:12 +00005137
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005138 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005139 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005140 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005141 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5142 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005143 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005144 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5145 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005146 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005147 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5148 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005149 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005150 }
5151
Douglas Gregorc938c162011-01-26 05:01:58 +00005152 // C++0x [class.dtor]p2:
5153 // A destructor shall not be declared with a ref-qualifier.
5154 if (FTI.hasRefQualifier()) {
5155 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5156 << FTI.RefQualifierIsLValueRef
5157 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5158 D.setInvalidType();
5159 }
5160
Douglas Gregor42a552f2008-11-05 20:51:48 +00005161 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005162 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005163 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5164
5165 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005166 FTI.freeArgs();
5167 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005168 }
5169
Mike Stump1eb44332009-09-09 15:08:12 +00005170 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005171 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005172 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005173 D.setInvalidType();
5174 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005175
5176 // Rebuild the function type "R" without any type qualifiers or
5177 // parameters (in case any of the errors above fired) and with
5178 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005179 // types.
John McCalle23cf432010-12-14 08:05:40 +00005180 if (!D.isInvalidType())
5181 return R;
5182
Douglas Gregord92ec472010-07-01 05:10:53 +00005183 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005184 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5185 EPI.Variadic = false;
5186 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005187 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005188 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005189}
5190
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005191/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5192/// well-formednes of the conversion function declarator @p D with
5193/// type @p R. If there are any errors in the declarator, this routine
5194/// will emit diagnostics and return true. Otherwise, it will return
5195/// false. Either way, the type @p R will be updated to reflect a
5196/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005197void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005198 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005199 // C++ [class.conv.fct]p1:
5200 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005201 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005202 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005203 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005204 if (!D.isInvalidType())
5205 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5206 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5207 << SourceRange(D.getIdentifierLoc());
5208 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005209 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005210 }
John McCalla3f81372010-04-13 00:04:31 +00005211
5212 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5213
Chris Lattner6e475012009-04-25 08:35:12 +00005214 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005215 // Conversion functions don't have return types, but the parser will
5216 // happily parse something like:
5217 //
5218 // class X {
5219 // float operator bool();
5220 // };
5221 //
5222 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005223 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5224 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5225 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005226 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005227 }
5228
John McCalla3f81372010-04-13 00:04:31 +00005229 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5230
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005231 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005232 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005233 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5234
5235 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005236 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005237 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005238 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005239 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005240 D.setInvalidType();
5241 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005242
John McCalla3f81372010-04-13 00:04:31 +00005243 // Diagnose "&operator bool()" and other such nonsense. This
5244 // is actually a gcc extension which we don't support.
5245 if (Proto->getResultType() != ConvType) {
5246 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5247 << Proto->getResultType();
5248 D.setInvalidType();
5249 ConvType = Proto->getResultType();
5250 }
5251
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005252 // C++ [class.conv.fct]p4:
5253 // The conversion-type-id shall not represent a function type nor
5254 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005255 if (ConvType->isArrayType()) {
5256 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5257 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005258 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005259 } else if (ConvType->isFunctionType()) {
5260 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5261 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005262 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005263 }
5264
5265 // Rebuild the function type "R" without any parameters (in case any
5266 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005267 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005268 if (D.isInvalidType())
5269 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005270
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005271 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005272 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005273 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005274 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005275 diag::warn_cxx98_compat_explicit_conversion_functions :
5276 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005277 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005278}
5279
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005280/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5281/// the declaration of the given C++ conversion function. This routine
5282/// is responsible for recording the conversion function in the C++
5283/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005284Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005285 assert(Conversion && "Expected to receive a conversion function declaration");
5286
Douglas Gregor9d350972008-12-12 08:25:50 +00005287 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005288
5289 // Make sure we aren't redeclaring the conversion function.
5290 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005291
5292 // C++ [class.conv.fct]p1:
5293 // [...] A conversion function is never used to convert a
5294 // (possibly cv-qualified) object to the (possibly cv-qualified)
5295 // same object type (or a reference to it), to a (possibly
5296 // cv-qualified) base class of that type (or a reference to it),
5297 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005298 // FIXME: Suppress this warning if the conversion function ends up being a
5299 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005300 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005301 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005302 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005303 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005304 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5305 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005306 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005307 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005308 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5309 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005310 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005311 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005312 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005313 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005314 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005315 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005316 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005317 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005318 }
5319
Douglas Gregore80622f2010-09-29 04:25:11 +00005320 if (FunctionTemplateDecl *ConversionTemplate
5321 = Conversion->getDescribedFunctionTemplate())
5322 return ConversionTemplate;
5323
John McCalld226f652010-08-21 09:40:31 +00005324 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005325}
5326
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005327//===----------------------------------------------------------------------===//
5328// Namespace Handling
5329//===----------------------------------------------------------------------===//
5330
John McCallea318642010-08-26 09:15:37 +00005331
5332
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005333/// ActOnStartNamespaceDef - This is called at the start of a namespace
5334/// definition.
John McCalld226f652010-08-21 09:40:31 +00005335Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005336 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005337 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005338 SourceLocation IdentLoc,
5339 IdentifierInfo *II,
5340 SourceLocation LBrace,
5341 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005342 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5343 // For anonymous namespace, take the location of the left brace.
5344 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005345 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005346 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005347 bool IsStd = false;
5348 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005349 Scope *DeclRegionScope = NamespcScope->getParent();
5350
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005351 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005352 if (II) {
5353 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005354 // The identifier in an original-namespace-definition shall not
5355 // have been previously defined in the declarative region in
5356 // which the original-namespace-definition appears. The
5357 // identifier in an original-namespace-definition is the name of
5358 // the namespace. Subsequently in that declarative region, it is
5359 // treated as an original-namespace-name.
5360 //
5361 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005362 // look through using directives, just look for any ordinary names.
5363
5364 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005365 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5366 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005367 NamedDecl *PrevDecl = 0;
5368 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005369 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005370 R.first != R.second; ++R.first) {
5371 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5372 PrevDecl = *R.first;
5373 break;
5374 }
5375 }
5376
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005377 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5378
5379 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005380 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005381 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005382 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005383 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005384 // The user probably just forgot the 'inline', so suggest that it
5385 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005386 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005387 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5388 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005389 Diag(Loc, diag::err_inline_namespace_mismatch)
5390 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005391 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005392 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5393
5394 IsInline = PrevNS->isInline();
5395 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005396 } else if (PrevDecl) {
5397 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005398 Diag(Loc, diag::err_redefinition_different_kind)
5399 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005400 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005401 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005402 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005403 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005404 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005405 // This is the first "real" definition of the namespace "std", so update
5406 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005407 PrevNS = getStdNamespace();
5408 IsStd = true;
5409 AddToKnown = !IsInline;
5410 } else {
5411 // We've seen this namespace for the first time.
5412 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005413 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005414 } else {
John McCall9aeed322009-10-01 00:25:31 +00005415 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005416
5417 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005418 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005419 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005420 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005421 } else {
5422 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005423 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005424 }
5425
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005426 if (PrevNS && IsInline != PrevNS->isInline()) {
5427 // inline-ness must match
5428 Diag(Loc, diag::err_inline_namespace_mismatch)
5429 << IsInline;
5430 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005431
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005432 // Recover by ignoring the new namespace's inline status.
5433 IsInline = PrevNS->isInline();
5434 }
5435 }
5436
5437 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5438 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005439 if (IsInvalid)
5440 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005441
5442 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005443
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005444 // FIXME: Should we be merging attributes?
5445 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005446 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005447
5448 if (IsStd)
5449 StdNamespace = Namespc;
5450 if (AddToKnown)
5451 KnownNamespaces[Namespc] = false;
5452
5453 if (II) {
5454 PushOnScopeChains(Namespc, DeclRegionScope);
5455 } else {
5456 // Link the anonymous namespace into its parent.
5457 DeclContext *Parent = CurContext->getRedeclContext();
5458 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5459 TU->setAnonymousNamespace(Namespc);
5460 } else {
5461 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005462 }
John McCall9aeed322009-10-01 00:25:31 +00005463
Douglas Gregora4181472010-03-24 00:46:35 +00005464 CurContext->addDecl(Namespc);
5465
John McCall9aeed322009-10-01 00:25:31 +00005466 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5467 // behaves as if it were replaced by
5468 // namespace unique { /* empty body */ }
5469 // using namespace unique;
5470 // namespace unique { namespace-body }
5471 // where all occurrences of 'unique' in a translation unit are
5472 // replaced by the same identifier and this identifier differs
5473 // from all other identifiers in the entire program.
5474
5475 // We just create the namespace with an empty name and then add an
5476 // implicit using declaration, just like the standard suggests.
5477 //
5478 // CodeGen enforces the "universally unique" aspect by giving all
5479 // declarations semantically contained within an anonymous
5480 // namespace internal linkage.
5481
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005482 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005483 UsingDirectiveDecl* UD
5484 = UsingDirectiveDecl::Create(Context, CurContext,
5485 /* 'using' */ LBrace,
5486 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005487 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005488 /* identifier */ SourceLocation(),
5489 Namespc,
5490 /* Ancestor */ CurContext);
5491 UD->setImplicit();
5492 CurContext->addDecl(UD);
5493 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005494 }
5495
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00005496 ActOnDocumentableDecl(Namespc);
5497
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005498 // Although we could have an invalid decl (i.e. the namespace name is a
5499 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005500 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5501 // for the namespace has the declarations that showed up in that particular
5502 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005503 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005504 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005505}
5506
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005507/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5508/// is a namespace alias, returns the namespace it points to.
5509static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5510 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5511 return AD->getNamespace();
5512 return dyn_cast_or_null<NamespaceDecl>(D);
5513}
5514
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005515/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5516/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005517void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005518 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5519 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005520 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005521 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005522 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005523 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005524}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005525
John McCall384aff82010-08-25 07:42:41 +00005526CXXRecordDecl *Sema::getStdBadAlloc() const {
5527 return cast_or_null<CXXRecordDecl>(
5528 StdBadAlloc.get(Context.getExternalSource()));
5529}
5530
5531NamespaceDecl *Sema::getStdNamespace() const {
5532 return cast_or_null<NamespaceDecl>(
5533 StdNamespace.get(Context.getExternalSource()));
5534}
5535
Douglas Gregor66992202010-06-29 17:53:46 +00005536/// \brief Retrieve the special "std" namespace, which may require us to
5537/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005538NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005539 if (!StdNamespace) {
5540 // The "std" namespace has not yet been defined, so build one implicitly.
5541 StdNamespace = NamespaceDecl::Create(Context,
5542 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005543 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005544 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005545 &PP.getIdentifierTable().get("std"),
5546 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005547 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005548 }
5549
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005550 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005551}
5552
Sebastian Redl395e04d2012-01-17 22:49:33 +00005553bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005554 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005555 "Looking for std::initializer_list outside of C++.");
5556
5557 // We're looking for implicit instantiations of
5558 // template <typename E> class std::initializer_list.
5559
5560 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5561 return false;
5562
Sebastian Redl84760e32012-01-17 22:49:58 +00005563 ClassTemplateDecl *Template = 0;
5564 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005565
Sebastian Redl84760e32012-01-17 22:49:58 +00005566 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005567
Sebastian Redl84760e32012-01-17 22:49:58 +00005568 ClassTemplateSpecializationDecl *Specialization =
5569 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5570 if (!Specialization)
5571 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005572
Sebastian Redl84760e32012-01-17 22:49:58 +00005573 Template = Specialization->getSpecializedTemplate();
5574 Arguments = Specialization->getTemplateArgs().data();
5575 } else if (const TemplateSpecializationType *TST =
5576 Ty->getAs<TemplateSpecializationType>()) {
5577 Template = dyn_cast_or_null<ClassTemplateDecl>(
5578 TST->getTemplateName().getAsTemplateDecl());
5579 Arguments = TST->getArgs();
5580 }
5581 if (!Template)
5582 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005583
5584 if (!StdInitializerList) {
5585 // Haven't recognized std::initializer_list yet, maybe this is it.
5586 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5587 if (TemplateClass->getIdentifier() !=
5588 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005589 !getStdNamespace()->InEnclosingNamespaceSetOf(
5590 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005591 return false;
5592 // This is a template called std::initializer_list, but is it the right
5593 // template?
5594 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005595 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005596 return false;
5597 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5598 return false;
5599
5600 // It's the right template.
5601 StdInitializerList = Template;
5602 }
5603
5604 if (Template != StdInitializerList)
5605 return false;
5606
5607 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005608 if (Element)
5609 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005610 return true;
5611}
5612
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005613static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5614 NamespaceDecl *Std = S.getStdNamespace();
5615 if (!Std) {
5616 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5617 return 0;
5618 }
5619
5620 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5621 Loc, Sema::LookupOrdinaryName);
5622 if (!S.LookupQualifiedName(Result, Std)) {
5623 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5624 return 0;
5625 }
5626 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5627 if (!Template) {
5628 Result.suppressDiagnostics();
5629 // We found something weird. Complain about the first thing we found.
5630 NamedDecl *Found = *Result.begin();
5631 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5632 return 0;
5633 }
5634
5635 // We found some template called std::initializer_list. Now verify that it's
5636 // correct.
5637 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005638 if (Params->getMinRequiredArguments() != 1 ||
5639 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005640 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5641 return 0;
5642 }
5643
5644 return Template;
5645}
5646
5647QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5648 if (!StdInitializerList) {
5649 StdInitializerList = LookupStdInitializerList(*this, Loc);
5650 if (!StdInitializerList)
5651 return QualType();
5652 }
5653
5654 TemplateArgumentListInfo Args(Loc, Loc);
5655 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5656 Context.getTrivialTypeSourceInfo(Element,
5657 Loc)));
5658 return Context.getCanonicalType(
5659 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5660}
5661
Sebastian Redl98d36062012-01-17 22:50:14 +00005662bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5663 // C++ [dcl.init.list]p2:
5664 // A constructor is an initializer-list constructor if its first parameter
5665 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5666 // std::initializer_list<E> for some type E, and either there are no other
5667 // parameters or else all other parameters have default arguments.
5668 if (Ctor->getNumParams() < 1 ||
5669 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5670 return false;
5671
5672 QualType ArgType = Ctor->getParamDecl(0)->getType();
5673 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5674 ArgType = RT->getPointeeType().getUnqualifiedType();
5675
5676 return isStdInitializerList(ArgType, 0);
5677}
5678
Douglas Gregor9172aa62011-03-26 22:25:30 +00005679/// \brief Determine whether a using statement is in a context where it will be
5680/// apply in all contexts.
5681static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5682 switch (CurContext->getDeclKind()) {
5683 case Decl::TranslationUnit:
5684 return true;
5685 case Decl::LinkageSpec:
5686 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5687 default:
5688 return false;
5689 }
5690}
5691
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005692namespace {
5693
5694// Callback to only accept typo corrections that are namespaces.
5695class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5696 public:
5697 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5698 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5699 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5700 }
5701 return false;
5702 }
5703};
5704
5705}
5706
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005707static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5708 CXXScopeSpec &SS,
5709 SourceLocation IdentLoc,
5710 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005711 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005712 R.clear();
5713 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005714 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005715 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005716 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5717 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005718 if (DeclContext *DC = S.computeDeclContext(SS, false))
5719 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5720 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5721 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5722 else
5723 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5724 << Ident << CorrectedQuotedStr
5725 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005726
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005727 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5728 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005729
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005730 R.addDecl(Corrected.getCorrectionDecl());
5731 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005732 }
5733 return false;
5734}
5735
John McCalld226f652010-08-21 09:40:31 +00005736Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005737 SourceLocation UsingLoc,
5738 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005739 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005740 SourceLocation IdentLoc,
5741 IdentifierInfo *NamespcName,
5742 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005743 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5744 assert(NamespcName && "Invalid NamespcName.");
5745 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005746
5747 // This can only happen along a recovery path.
5748 while (S->getFlags() & Scope::TemplateParamScope)
5749 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005750 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005751
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005752 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005753 NestedNameSpecifier *Qualifier = 0;
5754 if (SS.isSet())
5755 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5756
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005757 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005758 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5759 LookupParsedName(R, S, &SS);
5760 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005761 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005762
Douglas Gregor66992202010-06-29 17:53:46 +00005763 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005764 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005765 // Allow "using namespace std;" or "using namespace ::std;" even if
5766 // "std" hasn't been defined yet, for GCC compatibility.
5767 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5768 NamespcName->isStr("std")) {
5769 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005770 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005771 R.resolveKind();
5772 }
5773 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005774 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005775 }
5776
John McCallf36e02d2009-10-09 21:13:30 +00005777 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005778 NamedDecl *Named = R.getFoundDecl();
5779 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5780 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005781 // C++ [namespace.udir]p1:
5782 // A using-directive specifies that the names in the nominated
5783 // namespace can be used in the scope in which the
5784 // using-directive appears after the using-directive. During
5785 // unqualified name lookup (3.4.1), the names appear as if they
5786 // were declared in the nearest enclosing namespace which
5787 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005788 // namespace. [Note: in this context, "contains" means "contains
5789 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005790
5791 // Find enclosing context containing both using-directive and
5792 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005793 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005794 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5795 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5796 CommonAncestor = CommonAncestor->getParent();
5797
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005798 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005799 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005800 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005801
Douglas Gregor9172aa62011-03-26 22:25:30 +00005802 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005803 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005804 Diag(IdentLoc, diag::warn_using_directive_in_header);
5805 }
5806
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005807 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005808 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005809 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005810 }
5811
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005812 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005813 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005814}
5815
5816void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005817 // If the scope has an associated entity and the using directive is at
5818 // namespace or translation unit scope, add the UsingDirectiveDecl into
5819 // its lookup structure so qualified name lookup can find it.
5820 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5821 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005822 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005823 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005824 // Otherwise, it is at block sope. The using-directives will affect lookup
5825 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005826 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005827}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005828
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005829
John McCalld226f652010-08-21 09:40:31 +00005830Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005831 AccessSpecifier AS,
5832 bool HasUsingKeyword,
5833 SourceLocation UsingLoc,
5834 CXXScopeSpec &SS,
5835 UnqualifiedId &Name,
5836 AttributeList *AttrList,
5837 bool IsTypeName,
5838 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005839 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005840
Douglas Gregor12c118a2009-11-04 16:30:06 +00005841 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005842 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005843 case UnqualifiedId::IK_Identifier:
5844 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005845 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005846 case UnqualifiedId::IK_ConversionFunctionId:
5847 break;
5848
5849 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005850 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00005851 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005852 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005853 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00005854 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5855 // instead once inheriting constructors work.
5856 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00005857 diag::err_using_decl_constructor)
5858 << SS.getRange();
5859
David Blaikie4e4d0842012-03-11 07:00:24 +00005860 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005861
John McCalld226f652010-08-21 09:40:31 +00005862 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005863
5864 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005865 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005866 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005867 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005868
5869 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005870 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005871 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005872 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005873 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005874
5875 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5876 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005877 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005878 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005879
John McCall60fa3cf2009-12-11 02:10:03 +00005880 // Warn about using declarations.
5881 // TODO: store that the declaration was written without 'using' and
5882 // talk about access decls instead of using decls in the
5883 // diagnostics.
5884 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005885 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005886
5887 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005888 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005889 }
5890
Douglas Gregor56c04582010-12-16 00:46:58 +00005891 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5892 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5893 return 0;
5894
John McCall9488ea12009-11-17 05:59:44 +00005895 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005896 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005897 /* IsInstantiation */ false,
5898 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005899 if (UD)
5900 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005901
John McCalld226f652010-08-21 09:40:31 +00005902 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005903}
5904
Douglas Gregor09acc982010-07-07 23:08:52 +00005905/// \brief Determine whether a using declaration considers the given
5906/// declarations as "equivalent", e.g., if they are redeclarations of
5907/// the same entity or are both typedefs of the same type.
5908static bool
5909IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5910 bool &SuppressRedeclaration) {
5911 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5912 SuppressRedeclaration = false;
5913 return true;
5914 }
5915
Richard Smith162e1c12011-04-15 14:24:37 +00005916 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5917 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005918 SuppressRedeclaration = true;
5919 return Context.hasSameType(TD1->getUnderlyingType(),
5920 TD2->getUnderlyingType());
5921 }
5922
5923 return false;
5924}
5925
5926
John McCall9f54ad42009-12-10 09:41:52 +00005927/// Determines whether to create a using shadow decl for a particular
5928/// decl, given the set of decls existing prior to this using lookup.
5929bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5930 const LookupResult &Previous) {
5931 // Diagnose finding a decl which is not from a base class of the
5932 // current class. We do this now because there are cases where this
5933 // function will silently decide not to build a shadow decl, which
5934 // will pre-empt further diagnostics.
5935 //
5936 // We don't need to do this in C++0x because we do the check once on
5937 // the qualifier.
5938 //
5939 // FIXME: diagnose the following if we care enough:
5940 // struct A { int foo; };
5941 // struct B : A { using A::foo; };
5942 // template <class T> struct C : A {};
5943 // template <class T> struct D : C<T> { using B::foo; } // <---
5944 // This is invalid (during instantiation) in C++03 because B::foo
5945 // resolves to the using decl in B, which is not a base class of D<T>.
5946 // We can't diagnose it immediately because C<T> is an unknown
5947 // specialization. The UsingShadowDecl in D<T> then points directly
5948 // to A::foo, which will look well-formed when we instantiate.
5949 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00005950 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00005951 DeclContext *OrigDC = Orig->getDeclContext();
5952
5953 // Handle enums and anonymous structs.
5954 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5955 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5956 while (OrigRec->isAnonymousStructOrUnion())
5957 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5958
5959 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5960 if (OrigDC == CurContext) {
5961 Diag(Using->getLocation(),
5962 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005963 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005964 Diag(Orig->getLocation(), diag::note_using_decl_target);
5965 return true;
5966 }
5967
Douglas Gregordc355712011-02-25 00:36:19 +00005968 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005969 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005970 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005971 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005972 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005973 Diag(Orig->getLocation(), diag::note_using_decl_target);
5974 return true;
5975 }
5976 }
5977
5978 if (Previous.empty()) return false;
5979
5980 NamedDecl *Target = Orig;
5981 if (isa<UsingShadowDecl>(Target))
5982 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5983
John McCalld7533ec2009-12-11 02:33:26 +00005984 // If the target happens to be one of the previous declarations, we
5985 // don't have a conflict.
5986 //
5987 // FIXME: but we might be increasing its access, in which case we
5988 // should redeclare it.
5989 NamedDecl *NonTag = 0, *Tag = 0;
5990 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5991 I != E; ++I) {
5992 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005993 bool Result;
5994 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5995 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005996
5997 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5998 }
5999
John McCall9f54ad42009-12-10 09:41:52 +00006000 if (Target->isFunctionOrFunctionTemplate()) {
6001 FunctionDecl *FD;
6002 if (isa<FunctionTemplateDecl>(Target))
6003 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6004 else
6005 FD = cast<FunctionDecl>(Target);
6006
6007 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006008 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006009 case Ovl_Overload:
6010 return false;
6011
6012 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006013 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006014 break;
6015
6016 // We found a decl with the exact signature.
6017 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006018 // If we're in a record, we want to hide the target, so we
6019 // return true (without a diagnostic) to tell the caller not to
6020 // build a shadow decl.
6021 if (CurContext->isRecord())
6022 return true;
6023
6024 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006025 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006026 break;
6027 }
6028
6029 Diag(Target->getLocation(), diag::note_using_decl_target);
6030 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6031 return true;
6032 }
6033
6034 // Target is not a function.
6035
John McCall9f54ad42009-12-10 09:41:52 +00006036 if (isa<TagDecl>(Target)) {
6037 // No conflict between a tag and a non-tag.
6038 if (!Tag) return false;
6039
John McCall41ce66f2009-12-10 19:51:03 +00006040 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006041 Diag(Target->getLocation(), diag::note_using_decl_target);
6042 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6043 return true;
6044 }
6045
6046 // No conflict between a tag and a non-tag.
6047 if (!NonTag) return false;
6048
John McCall41ce66f2009-12-10 19:51:03 +00006049 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006050 Diag(Target->getLocation(), diag::note_using_decl_target);
6051 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6052 return true;
6053}
6054
John McCall9488ea12009-11-17 05:59:44 +00006055/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006056UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006057 UsingDecl *UD,
6058 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006059
6060 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006061 NamedDecl *Target = Orig;
6062 if (isa<UsingShadowDecl>(Target)) {
6063 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6064 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006065 }
6066
6067 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006068 = UsingShadowDecl::Create(Context, CurContext,
6069 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006070 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006071
6072 Shadow->setAccess(UD->getAccess());
6073 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6074 Shadow->setInvalidDecl();
6075
John McCall9488ea12009-11-17 05:59:44 +00006076 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006077 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006078 else
John McCall604e7f12009-12-08 07:46:18 +00006079 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006080
John McCall604e7f12009-12-08 07:46:18 +00006081
John McCall9f54ad42009-12-10 09:41:52 +00006082 return Shadow;
6083}
John McCall604e7f12009-12-08 07:46:18 +00006084
John McCall9f54ad42009-12-10 09:41:52 +00006085/// Hides a using shadow declaration. This is required by the current
6086/// using-decl implementation when a resolvable using declaration in a
6087/// class is followed by a declaration which would hide or override
6088/// one or more of the using decl's targets; for example:
6089///
6090/// struct Base { void foo(int); };
6091/// struct Derived : Base {
6092/// using Base::foo;
6093/// void foo(int);
6094/// };
6095///
6096/// The governing language is C++03 [namespace.udecl]p12:
6097///
6098/// When a using-declaration brings names from a base class into a
6099/// derived class scope, member functions in the derived class
6100/// override and/or hide member functions with the same name and
6101/// parameter types in a base class (rather than conflicting).
6102///
6103/// There are two ways to implement this:
6104/// (1) optimistically create shadow decls when they're not hidden
6105/// by existing declarations, or
6106/// (2) don't create any shadow decls (or at least don't make them
6107/// visible) until we've fully parsed/instantiated the class.
6108/// The problem with (1) is that we might have to retroactively remove
6109/// a shadow decl, which requires several O(n) operations because the
6110/// decl structures are (very reasonably) not designed for removal.
6111/// (2) avoids this but is very fiddly and phase-dependent.
6112void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006113 if (Shadow->getDeclName().getNameKind() ==
6114 DeclarationName::CXXConversionFunctionName)
6115 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6116
John McCall9f54ad42009-12-10 09:41:52 +00006117 // Remove it from the DeclContext...
6118 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006119
John McCall9f54ad42009-12-10 09:41:52 +00006120 // ...and the scope, if applicable...
6121 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006122 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006123 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006124 }
6125
John McCall9f54ad42009-12-10 09:41:52 +00006126 // ...and the using decl.
6127 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6128
6129 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006130 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006131}
6132
John McCall7ba107a2009-11-18 02:36:19 +00006133/// Builds a using declaration.
6134///
6135/// \param IsInstantiation - Whether this call arises from an
6136/// instantiation of an unresolved using declaration. We treat
6137/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006138NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6139 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006140 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006141 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006142 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006143 bool IsInstantiation,
6144 bool IsTypeName,
6145 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006146 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006147 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006148 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006149
Anders Carlsson550b14b2009-08-28 05:49:21 +00006150 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006151
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006152 if (SS.isEmpty()) {
6153 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006154 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006155 }
Mike Stump1eb44332009-09-09 15:08:12 +00006156
John McCall9f54ad42009-12-10 09:41:52 +00006157 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006158 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006159 ForRedeclaration);
6160 Previous.setHideTags(false);
6161 if (S) {
6162 LookupName(Previous, S);
6163
6164 // It is really dumb that we have to do this.
6165 LookupResult::Filter F = Previous.makeFilter();
6166 while (F.hasNext()) {
6167 NamedDecl *D = F.next();
6168 if (!isDeclInScope(D, CurContext, S))
6169 F.erase();
6170 }
6171 F.done();
6172 } else {
6173 assert(IsInstantiation && "no scope in non-instantiation");
6174 assert(CurContext->isRecord() && "scope not record in instantiation");
6175 LookupQualifiedName(Previous, CurContext);
6176 }
6177
John McCall9f54ad42009-12-10 09:41:52 +00006178 // Check for invalid redeclarations.
6179 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6180 return 0;
6181
6182 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006183 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6184 return 0;
6185
John McCallaf8e6ed2009-11-12 03:15:40 +00006186 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006187 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006188 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006189 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006190 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006191 // FIXME: not all declaration name kinds are legal here
6192 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6193 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006194 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006195 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006196 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006197 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6198 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006199 }
John McCalled976492009-12-04 22:46:56 +00006200 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006201 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6202 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006203 }
John McCalled976492009-12-04 22:46:56 +00006204 D->setAccess(AS);
6205 CurContext->addDecl(D);
6206
6207 if (!LookupContext) return D;
6208 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006209
John McCall77bb1aa2010-05-01 00:40:08 +00006210 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006211 UD->setInvalidDecl();
6212 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006213 }
6214
Richard Smithc5a89a12012-04-02 01:30:27 +00006215 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006216 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006217 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006218 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006219 return UD;
6220 }
6221
6222 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006223
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006224 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006225
John McCall604e7f12009-12-08 07:46:18 +00006226 // Unlike most lookups, we don't always want to hide tag
6227 // declarations: tag names are visible through the using declaration
6228 // even if hidden by ordinary names, *except* in a dependent context
6229 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006230 if (!IsInstantiation)
6231 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006232
John McCallb9abd8722012-04-07 03:04:20 +00006233 // For the purposes of this lookup, we have a base object type
6234 // equal to that of the current context.
6235 if (CurContext->isRecord()) {
6236 R.setBaseObjectType(
6237 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6238 }
6239
John McCalla24dc2e2009-11-17 02:14:36 +00006240 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006241
John McCallf36e02d2009-10-09 21:13:30 +00006242 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006243 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006244 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006245 UD->setInvalidDecl();
6246 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006247 }
6248
John McCalled976492009-12-04 22:46:56 +00006249 if (R.isAmbiguous()) {
6250 UD->setInvalidDecl();
6251 return UD;
6252 }
Mike Stump1eb44332009-09-09 15:08:12 +00006253
John McCall7ba107a2009-11-18 02:36:19 +00006254 if (IsTypeName) {
6255 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006256 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006257 Diag(IdentLoc, diag::err_using_typename_non_type);
6258 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6259 Diag((*I)->getUnderlyingDecl()->getLocation(),
6260 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006261 UD->setInvalidDecl();
6262 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006263 }
6264 } else {
6265 // If we asked for a non-typename and we got a type, error out,
6266 // but only if this is an instantiation of an unresolved using
6267 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006268 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006269 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6270 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006271 UD->setInvalidDecl();
6272 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006273 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006274 }
6275
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006276 // C++0x N2914 [namespace.udecl]p6:
6277 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006278 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006279 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6280 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006281 UD->setInvalidDecl();
6282 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006283 }
Mike Stump1eb44332009-09-09 15:08:12 +00006284
John McCall9f54ad42009-12-10 09:41:52 +00006285 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6286 if (!CheckUsingShadowDecl(UD, *I, Previous))
6287 BuildUsingShadowDecl(S, UD, *I);
6288 }
John McCall9488ea12009-11-17 05:59:44 +00006289
6290 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006291}
6292
Sebastian Redlf677ea32011-02-05 19:23:19 +00006293/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006294bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6295 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006296
Douglas Gregordc355712011-02-25 00:36:19 +00006297 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006298 assert(SourceType &&
6299 "Using decl naming constructor doesn't have type in scope spec.");
6300 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6301
6302 // Check whether the named type is a direct base class.
6303 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6304 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6305 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6306 BaseIt != BaseE; ++BaseIt) {
6307 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6308 if (CanonicalSourceType == BaseType)
6309 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006310 if (BaseIt->getType()->isDependentType())
6311 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006312 }
6313
6314 if (BaseIt == BaseE) {
6315 // Did not find SourceType in the bases.
6316 Diag(UD->getUsingLocation(),
6317 diag::err_using_decl_constructor_not_in_direct_base)
6318 << UD->getNameInfo().getSourceRange()
6319 << QualType(SourceType, 0) << TargetClass;
6320 return true;
6321 }
6322
Richard Smithc5a89a12012-04-02 01:30:27 +00006323 if (!CurContext->isDependentContext())
6324 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006325
6326 return false;
6327}
6328
John McCall9f54ad42009-12-10 09:41:52 +00006329/// Checks that the given using declaration is not an invalid
6330/// redeclaration. Note that this is checking only for the using decl
6331/// itself, not for any ill-formedness among the UsingShadowDecls.
6332bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6333 bool isTypeName,
6334 const CXXScopeSpec &SS,
6335 SourceLocation NameLoc,
6336 const LookupResult &Prev) {
6337 // C++03 [namespace.udecl]p8:
6338 // C++0x [namespace.udecl]p10:
6339 // A using-declaration is a declaration and can therefore be used
6340 // repeatedly where (and only where) multiple declarations are
6341 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006342 //
John McCall8a726212010-11-29 18:01:58 +00006343 // That's in non-member contexts.
6344 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006345 return false;
6346
6347 NestedNameSpecifier *Qual
6348 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6349
6350 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6351 NamedDecl *D = *I;
6352
6353 bool DTypename;
6354 NestedNameSpecifier *DQual;
6355 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6356 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006357 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006358 } else if (UnresolvedUsingValueDecl *UD
6359 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6360 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006361 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006362 } else if (UnresolvedUsingTypenameDecl *UD
6363 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6364 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006365 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006366 } else continue;
6367
6368 // using decls differ if one says 'typename' and the other doesn't.
6369 // FIXME: non-dependent using decls?
6370 if (isTypeName != DTypename) continue;
6371
6372 // using decls differ if they name different scopes (but note that
6373 // template instantiation can cause this check to trigger when it
6374 // didn't before instantiation).
6375 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6376 Context.getCanonicalNestedNameSpecifier(DQual))
6377 continue;
6378
6379 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006380 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006381 return true;
6382 }
6383
6384 return false;
6385}
6386
John McCall604e7f12009-12-08 07:46:18 +00006387
John McCalled976492009-12-04 22:46:56 +00006388/// Checks that the given nested-name qualifier used in a using decl
6389/// in the current context is appropriately related to the current
6390/// scope. If an error is found, diagnoses it and returns true.
6391bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6392 const CXXScopeSpec &SS,
6393 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006394 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006395
John McCall604e7f12009-12-08 07:46:18 +00006396 if (!CurContext->isRecord()) {
6397 // C++03 [namespace.udecl]p3:
6398 // C++0x [namespace.udecl]p8:
6399 // A using-declaration for a class member shall be a member-declaration.
6400
6401 // If we weren't able to compute a valid scope, it must be a
6402 // dependent class scope.
6403 if (!NamedContext || NamedContext->isRecord()) {
6404 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6405 << SS.getRange();
6406 return true;
6407 }
6408
6409 // Otherwise, everything is known to be fine.
6410 return false;
6411 }
6412
6413 // The current scope is a record.
6414
6415 // If the named context is dependent, we can't decide much.
6416 if (!NamedContext) {
6417 // FIXME: in C++0x, we can diagnose if we can prove that the
6418 // nested-name-specifier does not refer to a base class, which is
6419 // still possible in some cases.
6420
6421 // Otherwise we have to conservatively report that things might be
6422 // okay.
6423 return false;
6424 }
6425
6426 if (!NamedContext->isRecord()) {
6427 // Ideally this would point at the last name in the specifier,
6428 // but we don't have that level of source info.
6429 Diag(SS.getRange().getBegin(),
6430 diag::err_using_decl_nested_name_specifier_is_not_class)
6431 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6432 return true;
6433 }
6434
Douglas Gregor6fb07292010-12-21 07:41:49 +00006435 if (!NamedContext->isDependentContext() &&
6436 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6437 return true;
6438
David Blaikie4e4d0842012-03-11 07:00:24 +00006439 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006440 // C++0x [namespace.udecl]p3:
6441 // In a using-declaration used as a member-declaration, the
6442 // nested-name-specifier shall name a base class of the class
6443 // being defined.
6444
6445 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6446 cast<CXXRecordDecl>(NamedContext))) {
6447 if (CurContext == NamedContext) {
6448 Diag(NameLoc,
6449 diag::err_using_decl_nested_name_specifier_is_current_class)
6450 << SS.getRange();
6451 return true;
6452 }
6453
6454 Diag(SS.getRange().getBegin(),
6455 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6456 << (NestedNameSpecifier*) SS.getScopeRep()
6457 << cast<CXXRecordDecl>(CurContext)
6458 << SS.getRange();
6459 return true;
6460 }
6461
6462 return false;
6463 }
6464
6465 // C++03 [namespace.udecl]p4:
6466 // A using-declaration used as a member-declaration shall refer
6467 // to a member of a base class of the class being defined [etc.].
6468
6469 // Salient point: SS doesn't have to name a base class as long as
6470 // lookup only finds members from base classes. Therefore we can
6471 // diagnose here only if we can prove that that can't happen,
6472 // i.e. if the class hierarchies provably don't intersect.
6473
6474 // TODO: it would be nice if "definitely valid" results were cached
6475 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6476 // need to be repeated.
6477
6478 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006479 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006480
6481 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6482 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6483 Data->Bases.insert(Base);
6484 return true;
6485 }
6486
6487 bool hasDependentBases(const CXXRecordDecl *Class) {
6488 return !Class->forallBases(collect, this);
6489 }
6490
6491 /// Returns true if the base is dependent or is one of the
6492 /// accumulated base classes.
6493 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6494 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6495 return !Data->Bases.count(Base);
6496 }
6497
6498 bool mightShareBases(const CXXRecordDecl *Class) {
6499 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6500 }
6501 };
6502
6503 UserData Data;
6504
6505 // Returns false if we find a dependent base.
6506 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6507 return false;
6508
6509 // Returns false if the class has a dependent base or if it or one
6510 // of its bases is present in the base set of the current context.
6511 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6512 return false;
6513
6514 Diag(SS.getRange().getBegin(),
6515 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6516 << (NestedNameSpecifier*) SS.getScopeRep()
6517 << cast<CXXRecordDecl>(CurContext)
6518 << SS.getRange();
6519
6520 return true;
John McCalled976492009-12-04 22:46:56 +00006521}
6522
Richard Smith162e1c12011-04-15 14:24:37 +00006523Decl *Sema::ActOnAliasDeclaration(Scope *S,
6524 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006525 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006526 SourceLocation UsingLoc,
6527 UnqualifiedId &Name,
6528 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006529 // Skip up to the relevant declaration scope.
6530 while (S->getFlags() & Scope::TemplateParamScope)
6531 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006532 assert((S->getFlags() & Scope::DeclScope) &&
6533 "got alias-declaration outside of declaration scope");
6534
6535 if (Type.isInvalid())
6536 return 0;
6537
6538 bool Invalid = false;
6539 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6540 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006541 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006542
6543 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6544 return 0;
6545
6546 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006547 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006548 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006549 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6550 TInfo->getTypeLoc().getBeginLoc());
6551 }
Richard Smith162e1c12011-04-15 14:24:37 +00006552
6553 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6554 LookupName(Previous, S);
6555
6556 // Warn about shadowing the name of a template parameter.
6557 if (Previous.isSingleResult() &&
6558 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006559 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006560 Previous.clear();
6561 }
6562
6563 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6564 "name in alias declaration must be an identifier");
6565 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6566 Name.StartLocation,
6567 Name.Identifier, TInfo);
6568
6569 NewTD->setAccess(AS);
6570
6571 if (Invalid)
6572 NewTD->setInvalidDecl();
6573
Richard Smith3e4c6c42011-05-05 21:57:07 +00006574 CheckTypedefForVariablyModifiedType(S, NewTD);
6575 Invalid |= NewTD->isInvalidDecl();
6576
Richard Smith162e1c12011-04-15 14:24:37 +00006577 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006578
6579 NamedDecl *NewND;
6580 if (TemplateParamLists.size()) {
6581 TypeAliasTemplateDecl *OldDecl = 0;
6582 TemplateParameterList *OldTemplateParams = 0;
6583
6584 if (TemplateParamLists.size() != 1) {
6585 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006586 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
6587 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006588 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006589 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00006590
6591 // Only consider previous declarations in the same scope.
6592 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6593 /*ExplicitInstantiationOrSpecialization*/false);
6594 if (!Previous.empty()) {
6595 Redeclaration = true;
6596
6597 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6598 if (!OldDecl && !Invalid) {
6599 Diag(UsingLoc, diag::err_redefinition_different_kind)
6600 << Name.Identifier;
6601
6602 NamedDecl *OldD = Previous.getRepresentativeDecl();
6603 if (OldD->getLocation().isValid())
6604 Diag(OldD->getLocation(), diag::note_previous_definition);
6605
6606 Invalid = true;
6607 }
6608
6609 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6610 if (TemplateParameterListsAreEqual(TemplateParams,
6611 OldDecl->getTemplateParameters(),
6612 /*Complain=*/true,
6613 TPL_TemplateMatch))
6614 OldTemplateParams = OldDecl->getTemplateParameters();
6615 else
6616 Invalid = true;
6617
6618 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6619 if (!Invalid &&
6620 !Context.hasSameType(OldTD->getUnderlyingType(),
6621 NewTD->getUnderlyingType())) {
6622 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6623 // but we can't reasonably accept it.
6624 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6625 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6626 if (OldTD->getLocation().isValid())
6627 Diag(OldTD->getLocation(), diag::note_previous_definition);
6628 Invalid = true;
6629 }
6630 }
6631 }
6632
6633 // Merge any previous default template arguments into our parameters,
6634 // and check the parameter list.
6635 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6636 TPC_TypeAliasTemplate))
6637 return 0;
6638
6639 TypeAliasTemplateDecl *NewDecl =
6640 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6641 Name.Identifier, TemplateParams,
6642 NewTD);
6643
6644 NewDecl->setAccess(AS);
6645
6646 if (Invalid)
6647 NewDecl->setInvalidDecl();
6648 else if (OldDecl)
6649 NewDecl->setPreviousDeclaration(OldDecl);
6650
6651 NewND = NewDecl;
6652 } else {
6653 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6654 NewND = NewTD;
6655 }
Richard Smith162e1c12011-04-15 14:24:37 +00006656
6657 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006658 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006659
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00006660 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00006661 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006662}
6663
John McCalld226f652010-08-21 09:40:31 +00006664Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006665 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006666 SourceLocation AliasLoc,
6667 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006668 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006669 SourceLocation IdentLoc,
6670 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006671
Anders Carlsson81c85c42009-03-28 23:53:49 +00006672 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006673 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6674 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006675
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006676 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006677 NamedDecl *PrevDecl
6678 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6679 ForRedeclaration);
6680 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6681 PrevDecl = 0;
6682
6683 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006684 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006685 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006686 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006687 // FIXME: At some point, we'll want to create the (redundant)
6688 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006689 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006690 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006691 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006692 }
Mike Stump1eb44332009-09-09 15:08:12 +00006693
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006694 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6695 diag::err_redefinition_different_kind;
6696 Diag(AliasLoc, DiagID) << Alias;
6697 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006698 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006699 }
6700
John McCalla24dc2e2009-11-17 02:14:36 +00006701 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006702 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006703
John McCallf36e02d2009-10-09 21:13:30 +00006704 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006705 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00006706 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006707 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006708 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006709 }
Mike Stump1eb44332009-09-09 15:08:12 +00006710
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006711 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006712 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006713 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006714 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006715
John McCall3dbd3d52010-02-16 06:53:13 +00006716 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006717 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006718}
6719
Douglas Gregor39957dc2010-05-01 15:04:51 +00006720namespace {
6721 /// \brief Scoped object used to handle the state changes required in Sema
6722 /// to implicitly define the body of a C++ member function;
6723 class ImplicitlyDefinedFunctionScope {
6724 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006725 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006726
6727 public:
6728 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006729 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006730 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006731 S.PushFunctionScope();
6732 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6733 }
6734
6735 ~ImplicitlyDefinedFunctionScope() {
6736 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006737 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006738 }
6739 };
6740}
6741
Sean Hunt001cad92011-05-10 00:49:42 +00006742Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00006743Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
6744 CXXMethodDecl *MD) {
6745 CXXRecordDecl *ClassDecl = MD->getParent();
6746
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006747 // C++ [except.spec]p14:
6748 // An implicitly declared special member function (Clause 12) shall have an
6749 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00006750 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006751 if (ClassDecl->isInvalidDecl())
6752 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006753
Sebastian Redl60618fa2011-03-12 11:50:43 +00006754 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006755 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6756 BEnd = ClassDecl->bases_end();
6757 B != BEnd; ++B) {
6758 if (B->isVirtual()) // Handled below.
6759 continue;
6760
Douglas Gregor18274032010-07-03 00:47:00 +00006761 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6762 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006763 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6764 // If this is a deleted function, add it anyway. This might be conformant
6765 // with the standard. This might not. I'm not sure. It might not matter.
6766 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006767 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006768 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006769 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006770
6771 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006772 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6773 BEnd = ClassDecl->vbases_end();
6774 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006775 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6776 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006777 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6778 // If this is a deleted function, add it anyway. This might be conformant
6779 // with the standard. This might not. I'm not sure. It might not matter.
6780 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006781 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006782 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006783 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006784
6785 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006786 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6787 FEnd = ClassDecl->field_end();
6788 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006789 if (F->hasInClassInitializer()) {
6790 if (Expr *E = F->getInClassInitializer())
6791 ExceptSpec.CalledExpr(E);
6792 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00006793 // DR1351:
6794 // If the brace-or-equal-initializer of a non-static data member
6795 // invokes a defaulted default constructor of its class or of an
6796 // enclosing class in a potentially evaluated subexpression, the
6797 // program is ill-formed.
6798 //
6799 // This resolution is unworkable: the exception specification of the
6800 // default constructor can be needed in an unevaluated context, in
6801 // particular, in the operand of a noexcept-expression, and we can be
6802 // unable to compute an exception specification for an enclosed class.
6803 //
6804 // We do not allow an in-class initializer to require the evaluation
6805 // of the exception specification for any in-class initializer whose
6806 // definition is not lexically complete.
6807 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00006808 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006809 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006810 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6811 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6812 // If this is a deleted function, add it anyway. This might be conformant
6813 // with the standard. This might not. I'm not sure. It might not matter.
6814 // In particular, the problem is that this function never gets called. It
6815 // might just be ill-formed because this function attempts to refer to
6816 // a deleted function here.
6817 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006818 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006819 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006820 }
John McCalle23cf432010-12-14 08:05:40 +00006821
Sean Hunt001cad92011-05-10 00:49:42 +00006822 return ExceptSpec;
6823}
6824
6825CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6826 CXXRecordDecl *ClassDecl) {
6827 // C++ [class.ctor]p5:
6828 // A default constructor for a class X is a constructor of class X
6829 // that can be called without an argument. If there is no
6830 // user-declared constructor for class X, a default constructor is
6831 // implicitly declared. An implicitly-declared default constructor
6832 // is an inline public member of its class.
6833 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6834 "Should not build implicit default constructor!");
6835
Richard Smith7756afa2012-06-10 05:43:50 +00006836 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
6837 CXXDefaultConstructor,
6838 false);
6839
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006840 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006841 CanQualType ClassType
6842 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006843 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006844 DeclarationName Name
6845 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006846 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006847 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00006848 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00006849 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00006850 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006851 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006852 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006853 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006854 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Richard Smithb9d0b762012-07-27 04:22:15 +00006855
6856 // Build an exception specification pointing back at this constructor.
6857 FunctionProtoType::ExtProtoInfo EPI;
6858 EPI.ExceptionSpecType = EST_Unevaluated;
6859 EPI.ExceptionSpecDecl = DefaultCon;
6860 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6861
Douglas Gregor18274032010-07-03 00:47:00 +00006862 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006863 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6864
Douglas Gregor23c94db2010-07-02 17:43:08 +00006865 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006866 PushOnScopeChains(DefaultCon, S, false);
6867 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006868
Sean Hunte16da072011-10-10 06:18:57 +00006869 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006870 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006871
Douglas Gregor32df23e2010-07-01 22:02:46 +00006872 return DefaultCon;
6873}
6874
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006875void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6876 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006877 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006878 !Constructor->doesThisDeclarationHaveABody() &&
6879 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006880 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006881
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006882 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006883 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006884
Douglas Gregor39957dc2010-05-01 15:04:51 +00006885 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006886 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006887 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006888 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006889 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006890 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006891 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006892 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006893 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006894
6895 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00006896 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006897
6898 Constructor->setUsed();
6899 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006900
6901 if (ASTMutationListener *L = getASTMutationListener()) {
6902 L->CompletedImplicitDefinition(Constructor);
6903 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006904}
6905
Richard Smith7a614d82011-06-11 17:19:42 +00006906void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6907 if (!D) return;
6908 AdjustDeclIfTemplate(D);
6909
6910 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
Richard Smith7a614d82011-06-11 17:19:42 +00006911
Richard Smithb9d0b762012-07-27 04:22:15 +00006912 if (!ClassDecl->isDependentType())
6913 CheckExplicitlyDefaultedMethods(ClassDecl);
Richard Smith7a614d82011-06-11 17:19:42 +00006914}
6915
Sebastian Redlf677ea32011-02-05 19:23:19 +00006916void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6917 // We start with an initial pass over the base classes to collect those that
6918 // inherit constructors from. If there are none, we can forgo all further
6919 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006920 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006921 BasesVector BasesToInheritFrom;
6922 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6923 BaseE = ClassDecl->bases_end();
6924 BaseIt != BaseE; ++BaseIt) {
6925 if (BaseIt->getInheritConstructors()) {
6926 QualType Base = BaseIt->getType();
6927 if (Base->isDependentType()) {
6928 // If we inherit constructors from anything that is dependent, just
6929 // abort processing altogether. We'll get another chance for the
6930 // instantiations.
6931 return;
6932 }
6933 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6934 }
6935 }
6936 if (BasesToInheritFrom.empty())
6937 return;
6938
6939 // Now collect the constructors that we already have in the current class.
6940 // Those take precedence over inherited constructors.
6941 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6942 // unless there is a user-declared constructor with the same signature in
6943 // the class where the using-declaration appears.
6944 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6945 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6946 CtorE = ClassDecl->ctor_end();
6947 CtorIt != CtorE; ++CtorIt) {
6948 ExistingConstructors.insert(
6949 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6950 }
6951
Sebastian Redlf677ea32011-02-05 19:23:19 +00006952 DeclarationName CreatedCtorName =
6953 Context.DeclarationNames.getCXXConstructorName(
6954 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6955
6956 // Now comes the true work.
6957 // First, we keep a map from constructor types to the base that introduced
6958 // them. Needed for finding conflicting constructors. We also keep the
6959 // actually inserted declarations in there, for pretty diagnostics.
6960 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6961 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6962 ConstructorToSourceMap InheritedConstructors;
6963 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6964 BaseE = BasesToInheritFrom.end();
6965 BaseIt != BaseE; ++BaseIt) {
6966 const RecordType *Base = *BaseIt;
6967 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6968 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6969 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6970 CtorE = BaseDecl->ctor_end();
6971 CtorIt != CtorE; ++CtorIt) {
6972 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00006973 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00006974 DeclarationName Name =
6975 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00006976 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6977 LookupQualifiedName(Result, CurContext);
6978 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006979 SourceLocation UsingLoc = UD ? UD->getLocation() :
6980 ClassDecl->getLocation();
6981
6982 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6983 // from the class X named in the using-declaration consists of actual
6984 // constructors and notional constructors that result from the
6985 // transformation of defaulted parameters as follows:
6986 // - all non-template default constructors of X, and
6987 // - for each non-template constructor of X that has at least one
6988 // parameter with a default argument, the set of constructors that
6989 // results from omitting any ellipsis parameter specification and
6990 // successively omitting parameters with a default argument from the
6991 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00006992 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006993 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6994 const FunctionProtoType *BaseCtorType =
6995 BaseCtor->getType()->getAs<FunctionProtoType>();
6996
6997 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6998 maxParams = BaseCtor->getNumParams();
6999 params <= maxParams; ++params) {
7000 // Skip default constructors. They're never inherited.
7001 if (params == 0)
7002 continue;
7003 // Skip copy and move constructors for the same reason.
7004 if (CanBeCopyOrMove && params == 1)
7005 continue;
7006
7007 // Build up a function type for this particular constructor.
7008 // FIXME: The working paper does not consider that the exception spec
7009 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007010 // source. This code doesn't yet, either. When it does, this code will
7011 // need to be delayed until after exception specifications and in-class
7012 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007013 const Type *NewCtorType;
7014 if (params == maxParams)
7015 NewCtorType = BaseCtorType;
7016 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007017 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007018 for (unsigned i = 0; i < params; ++i) {
7019 Args.push_back(BaseCtorType->getArgType(i));
7020 }
7021 FunctionProtoType::ExtProtoInfo ExtInfo =
7022 BaseCtorType->getExtProtoInfo();
7023 ExtInfo.Variadic = false;
7024 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7025 Args.data(), params, ExtInfo)
7026 .getTypePtr();
7027 }
7028 const Type *CanonicalNewCtorType =
7029 Context.getCanonicalType(NewCtorType);
7030
7031 // Now that we have the type, first check if the class already has a
7032 // constructor with this signature.
7033 if (ExistingConstructors.count(CanonicalNewCtorType))
7034 continue;
7035
7036 // Then we check if we have already declared an inherited constructor
7037 // with this signature.
7038 std::pair<ConstructorToSourceMap::iterator, bool> result =
7039 InheritedConstructors.insert(std::make_pair(
7040 CanonicalNewCtorType,
7041 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7042 if (!result.second) {
7043 // Already in the map. If it came from a different class, that's an
7044 // error. Not if it's from the same.
7045 CanQualType PreviousBase = result.first->second.first;
7046 if (CanonicalBase != PreviousBase) {
7047 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7048 const CXXConstructorDecl *PrevBaseCtor =
7049 PrevCtor->getInheritedConstructor();
7050 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7051
7052 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7053 Diag(BaseCtor->getLocation(),
7054 diag::note_using_decl_constructor_conflict_current_ctor);
7055 Diag(PrevBaseCtor->getLocation(),
7056 diag::note_using_decl_constructor_conflict_previous_ctor);
7057 Diag(PrevCtor->getLocation(),
7058 diag::note_using_decl_constructor_conflict_previous_using);
7059 }
7060 continue;
7061 }
7062
7063 // OK, we're there, now add the constructor.
7064 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007065 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007066 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7067 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007068 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7069 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007070 /*ImplicitlyDeclared=*/true,
7071 // FIXME: Due to a defect in the standard, we treat inherited
7072 // constructors as constexpr even if that makes them ill-formed.
7073 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007074 NewCtor->setAccess(BaseCtor->getAccess());
7075
7076 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007077 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007078 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007079 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7080 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007081 /*IdentifierInfo=*/0,
7082 BaseCtorType->getArgType(i),
7083 /*TInfo=*/0, SC_None,
7084 SC_None, /*DefaultArg=*/0));
7085 }
David Blaikie4278c652011-09-21 18:16:56 +00007086 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007087 NewCtor->setInheritedConstructor(BaseCtor);
7088
Sebastian Redlf677ea32011-02-05 19:23:19 +00007089 ClassDecl->addDecl(NewCtor);
7090 result.first->second.second = NewCtor;
7091 }
7092 }
7093 }
7094}
7095
Sean Huntcb45a0f2011-05-12 22:46:25 +00007096Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007097Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7098 CXXRecordDecl *ClassDecl = MD->getParent();
7099
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007100 // C++ [except.spec]p14:
7101 // An implicitly declared special member function (Clause 12) shall have
7102 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007103 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007104 if (ClassDecl->isInvalidDecl())
7105 return ExceptSpec;
7106
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007107 // Direct base-class destructors.
7108 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7109 BEnd = ClassDecl->bases_end();
7110 B != BEnd; ++B) {
7111 if (B->isVirtual()) // Handled below.
7112 continue;
7113
7114 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007115 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007116 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007117 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007118
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007119 // Virtual base-class destructors.
7120 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7121 BEnd = ClassDecl->vbases_end();
7122 B != BEnd; ++B) {
7123 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007124 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007125 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007126 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007127
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007128 // Field destructors.
7129 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7130 FEnd = ClassDecl->field_end();
7131 F != FEnd; ++F) {
7132 if (const RecordType *RecordTy
7133 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007134 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007135 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007136 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007137
Sean Huntcb45a0f2011-05-12 22:46:25 +00007138 return ExceptSpec;
7139}
7140
7141CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7142 // C++ [class.dtor]p2:
7143 // If a class has no user-declared destructor, a destructor is
7144 // declared implicitly. An implicitly-declared destructor is an
7145 // inline public member of its class.
Sean Huntcb45a0f2011-05-12 22:46:25 +00007146
Douglas Gregor4923aa22010-07-02 20:37:36 +00007147 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007148 CanQualType ClassType
7149 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007150 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007151 DeclarationName Name
7152 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007153 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007154 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007155 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7156 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007157 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007158 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007159 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007160 Destructor->setImplicit();
7161 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Richard Smithb9d0b762012-07-27 04:22:15 +00007162
7163 // Build an exception specification pointing back at this destructor.
7164 FunctionProtoType::ExtProtoInfo EPI;
7165 EPI.ExceptionSpecType = EST_Unevaluated;
7166 EPI.ExceptionSpecDecl = Destructor;
7167 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7168
Douglas Gregor4923aa22010-07-02 20:37:36 +00007169 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007170 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007171
Douglas Gregor4923aa22010-07-02 20:37:36 +00007172 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007173 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007174 PushOnScopeChains(Destructor, S, false);
7175 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007176
Richard Smith9a561d52012-02-26 09:11:52 +00007177 AddOverriddenMethods(ClassDecl, Destructor);
7178
Richard Smith7d5088a2012-02-18 02:02:13 +00007179 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00007180 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00007181
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007182 return Destructor;
7183}
7184
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007185void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007186 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007187 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007188 !Destructor->doesThisDeclarationHaveABody() &&
7189 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007190 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007191 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007192 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007193
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007194 if (Destructor->isInvalidDecl())
7195 return;
7196
Douglas Gregor39957dc2010-05-01 15:04:51 +00007197 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007198
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007199 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007200 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7201 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007202
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007203 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007204 Diag(CurrentLocation, diag::note_member_synthesized_at)
7205 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7206
7207 Destructor->setInvalidDecl();
7208 return;
7209 }
7210
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007211 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007212 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007213 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007214 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007215 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007216
7217 if (ASTMutationListener *L = getASTMutationListener()) {
7218 L->CompletedImplicitDefinition(Destructor);
7219 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007220}
7221
Richard Smitha4156b82012-04-21 18:42:51 +00007222/// \brief Perform any semantic analysis which needs to be delayed until all
7223/// pending class member declarations have been parsed.
7224void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007225 // Perform any deferred checking of exception specifications for virtual
7226 // destructors.
7227 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7228 i != e; ++i) {
7229 const CXXDestructorDecl *Dtor =
7230 DelayedDestructorExceptionSpecChecks[i].first;
7231 assert(!Dtor->getParent()->isDependentType() &&
7232 "Should not ever add destructors of templates into the list.");
7233 CheckOverridingFunctionExceptionSpec(Dtor,
7234 DelayedDestructorExceptionSpecChecks[i].second);
7235 }
7236 DelayedDestructorExceptionSpecChecks.clear();
7237}
7238
Richard Smithb9d0b762012-07-27 04:22:15 +00007239void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7240 CXXDestructorDecl *Destructor) {
7241 assert(getLangOpts().CPlusPlus0x &&
7242 "adjusting dtor exception specs was introduced in c++11");
7243
Sebastian Redl0ee33912011-05-19 05:13:44 +00007244 // C++11 [class.dtor]p3:
7245 // A declaration of a destructor that does not have an exception-
7246 // specification is implicitly considered to have the same exception-
7247 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007248 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007249 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007250 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007251 return;
7252
Chandler Carruth3f224b22011-09-20 04:55:26 +00007253 // Replace the destructor's type, building off the existing one. Fortunately,
7254 // the only thing of interest in the destructor type is its extended info.
7255 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007256 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7257 EPI.ExceptionSpecType = EST_Unevaluated;
7258 EPI.ExceptionSpecDecl = Destructor;
7259 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007260
Sebastian Redl0ee33912011-05-19 05:13:44 +00007261 // FIXME: If the destructor has a body that could throw, and the newly created
7262 // spec doesn't allow exceptions, we should emit a warning, because this
7263 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007264 // However, we don't have a body or an exception specification yet, so it
7265 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007266}
7267
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007268/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007269/// \c To.
7270///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007271/// This routine is used to copy/move the members of a class with an
7272/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007273/// copied are arrays, this routine builds for loops to copy them.
7274///
7275/// \param S The Sema object used for type-checking.
7276///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007277/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007278///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007279/// \param T The type of the expressions being copied/moved. Both expressions
7280/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007281///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007282/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007283///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007284/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007285///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007286/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007287/// Otherwise, it's a non-static member subobject.
7288///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007289/// \param Copying Whether we're copying or moving.
7290///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007291/// \param Depth Internal parameter recording the depth of the recursion.
7292///
7293/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007294static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007295BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007296 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007297 bool CopyingBaseSubobject, bool Copying,
7298 unsigned Depth = 0) {
7299 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007300 // Each subobject is assigned in the manner appropriate to its type:
7301 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007302 // - if the subobject is of class type, as if by a call to operator= with
7303 // the subobject as the object expression and the corresponding
7304 // subobject of x as a single function argument (as if by explicit
7305 // qualification; that is, ignoring any possible virtual overriding
7306 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007307 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7308 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7309
7310 // Look for operator=.
7311 DeclarationName Name
7312 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7313 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7314 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7315
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007316 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007317 LookupResult::Filter F = OpLookup.makeFilter();
7318 while (F.hasNext()) {
7319 NamedDecl *D = F.next();
7320 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Richard Smith1c931be2012-04-02 18:40:40 +00007321 if (Method->isCopyAssignmentOperator() ||
7322 (!Copying && Method->isMoveAssignmentOperator()))
Douglas Gregor06a9f362010-05-01 20:49:11 +00007323 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007324
Douglas Gregor06a9f362010-05-01 20:49:11 +00007325 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007326 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007327 F.done();
7328
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007329 // Suppress the protected check (C++ [class.protected]) for each of the
7330 // assignment operators we found. This strange dance is required when
7331 // we're assigning via a base classes's copy-assignment operator. To
7332 // ensure that we're getting the right base class subobject (without
7333 // ambiguities), we need to cast "this" to that subobject type; to
7334 // ensure that we don't go through the virtual call mechanism, we need
7335 // to qualify the operator= name with the base class (see below). However,
7336 // this means that if the base class has a protected copy assignment
7337 // operator, the protected member access check will fail. So, we
7338 // rewrite "protected" access to "public" access in this case, since we
7339 // know by construction that we're calling from a derived class.
7340 if (CopyingBaseSubobject) {
7341 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7342 L != LEnd; ++L) {
7343 if (L.getAccess() == AS_protected)
7344 L.setAccess(AS_public);
7345 }
7346 }
7347
Douglas Gregor06a9f362010-05-01 20:49:11 +00007348 // Create the nested-name-specifier that will be used to qualify the
7349 // reference to operator=; this is required to suppress the virtual
7350 // call mechanism.
7351 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007352 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007353 SS.MakeTrivial(S.Context,
7354 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007355 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007356 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007357
7358 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007359 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007360 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007361 /*TemplateKWLoc=*/SourceLocation(),
7362 /*FirstQualifierInScope=*/0,
7363 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007364 /*TemplateArgs=*/0,
7365 /*SuppressQualifierCheck=*/true);
7366 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007367 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007368
7369 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007370
John McCall60d7b3a2010-08-24 06:29:42 +00007371 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007372 OpEqualRef.takeAs<Expr>(),
7373 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007374 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007375 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007376
7377 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007378 }
John McCallb0207482010-03-16 06:11:48 +00007379
Douglas Gregor06a9f362010-05-01 20:49:11 +00007380 // - if the subobject is of scalar type, the built-in assignment
7381 // operator is used.
7382 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7383 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007384 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007385 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007386 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007387
7388 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007389 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007390
7391 // - if the subobject is an array, each element is assigned, in the
7392 // manner appropriate to the element type;
7393
7394 // Construct a loop over the array bounds, e.g.,
7395 //
7396 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7397 //
7398 // that will copy each of the array elements.
7399 QualType SizeType = S.Context.getSizeType();
7400
7401 // Create the iteration variable.
7402 IdentifierInfo *IterationVarName = 0;
7403 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007404 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007405 llvm::raw_svector_ostream OS(Str);
7406 OS << "__i" << Depth;
7407 IterationVarName = &S.Context.Idents.get(OS.str());
7408 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007409 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007410 IterationVarName, SizeType,
7411 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007412 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007413
7414 // Initialize the iteration variable to zero.
7415 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007416 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007417
7418 // Create a reference to the iteration variable; we'll use this several
7419 // times throughout.
7420 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007421 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007422 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007423 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7424 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7425
Douglas Gregor06a9f362010-05-01 20:49:11 +00007426 // Create the DeclStmt that holds the iteration variable.
7427 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7428
7429 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007430 llvm::APInt Upper
7431 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007432 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007433 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007434 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7435 BO_NE, S.Context.BoolTy,
7436 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007437
7438 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007439 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007440 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7441 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007442
7443 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007444 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007445 IterationVarRefRVal,
7446 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007447 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007448 IterationVarRefRVal,
7449 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007450 if (!Copying) // Cast to rvalue
7451 From = CastForMoving(S, From);
7452
7453 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007454 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7455 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007456 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007457 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007458 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007459
7460 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007461 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007462 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007463 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007464 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007465}
7466
Richard Smithb9d0b762012-07-27 04:22:15 +00007467/// Determine whether an implicit copy assignment operator for ClassDecl has a
7468/// const argument.
7469/// FIXME: It ought to be possible to store this on the record.
7470static bool isImplicitCopyAssignmentArgConst(Sema &S,
7471 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007472 if (ClassDecl->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007473 return true;
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007474
Douglas Gregord3c35902010-07-01 16:36:15 +00007475 // C++ [class.copy]p10:
7476 // If the class definition does not explicitly declare a copy
7477 // assignment operator, one is declared implicitly.
7478 // The implicitly-defined copy assignment operator for a class X
7479 // will have the form
7480 //
7481 // X& X::operator=(const X&)
7482 //
7483 // if
Douglas Gregord3c35902010-07-01 16:36:15 +00007484 // -- each direct base class B of X has a copy assignment operator
7485 // whose parameter is of type const B&, const volatile B& or B,
7486 // and
7487 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7488 BaseEnd = ClassDecl->bases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007489 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007490 // We'll handle this below
Richard Smithb9d0b762012-07-27 04:22:15 +00007491 if (S.getLangOpts().CPlusPlus0x && Base->isVirtual())
Sean Hunt661c67a2011-06-21 23:42:56 +00007492 continue;
7493
Douglas Gregord3c35902010-07-01 16:36:15 +00007494 assert(!Base->getType()->isDependentType() &&
7495 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007496 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smithb9d0b762012-07-27 04:22:15 +00007497 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0))
7498 return false;
Sean Hunt661c67a2011-06-21 23:42:56 +00007499 }
7500
Richard Smithebaf0e62011-10-18 20:49:44 +00007501 // In C++11, the above citation has "or virtual" added
Richard Smithb9d0b762012-07-27 04:22:15 +00007502 if (S.getLangOpts().CPlusPlus0x) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007503 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7504 BaseEnd = ClassDecl->vbases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007505 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007506 assert(!Base->getType()->isDependentType() &&
7507 "Cannot generate implicit members for class with dependent bases.");
7508 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smithb9d0b762012-07-27 04:22:15 +00007509 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7510 false, 0))
7511 return false;
Sean Hunt661c67a2011-06-21 23:42:56 +00007512 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007513 }
7514
7515 // -- for all the nonstatic data members of X that are of a class
7516 // type M (or array thereof), each such class type has a copy
7517 // assignment operator whose parameter is of type const M&,
7518 // const volatile M& or M.
7519 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7520 FieldEnd = ClassDecl->field_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007521 Field != FieldEnd; ++Field) {
7522 QualType FieldType = S.Context.getBaseElementType(Field->getType());
7523 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl())
7524 if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7525 false, 0))
7526 return false;
Douglas Gregord3c35902010-07-01 16:36:15 +00007527 }
7528
7529 // Otherwise, the implicitly declared copy assignment operator will
7530 // have the form
7531 //
7532 // X& X::operator=(X&)
Richard Smithb9d0b762012-07-27 04:22:15 +00007533
7534 return true;
7535}
7536
7537Sema::ImplicitExceptionSpecification
7538Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
7539 CXXRecordDecl *ClassDecl = MD->getParent();
7540
7541 ImplicitExceptionSpecification ExceptSpec(*this);
7542 if (ClassDecl->isInvalidDecl())
7543 return ExceptSpec;
7544
7545 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
7546 assert(T->getNumArgs() == 1 && "not a copy assignment op");
7547 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
7548
Douglas Gregorb87786f2010-07-01 17:48:08 +00007549 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00007550 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00007551 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007552
7553 // It is unspecified whether or not an implicit copy assignment operator
7554 // attempts to deduplicate calls to assignment operators of virtual bases are
7555 // made. As such, this exception specification is effectively unspecified.
7556 // Based on a similar decision made for constness in C++0x, we're erring on
7557 // the side of assuming such calls to be made regardless of whether they
7558 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007559 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7560 BaseEnd = ClassDecl->bases_end();
7561 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007562 if (Base->isVirtual())
7563 continue;
7564
Douglas Gregora376d102010-07-02 21:50:04 +00007565 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007566 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007567 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7568 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007569 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00007570 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007571
7572 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7573 BaseEnd = ClassDecl->vbases_end();
7574 Base != BaseEnd; ++Base) {
7575 CXXRecordDecl *BaseClassDecl
7576 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7577 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7578 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007579 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00007580 }
7581
Douglas Gregorb87786f2010-07-01 17:48:08 +00007582 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7583 FieldEnd = ClassDecl->field_end();
7584 Field != FieldEnd;
7585 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007586 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007587 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7588 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00007589 LookupCopyingAssignment(FieldClassDecl,
7590 ArgQuals | FieldType.getCVRQualifiers(),
7591 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007592 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007593 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007594 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007595
Richard Smithb9d0b762012-07-27 04:22:15 +00007596 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00007597}
7598
7599CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7600 // Note: The following rules are largely analoguous to the copy
7601 // constructor rules. Note that virtual bases are not taken into account
7602 // for determining the argument type of the operator. Note also that
7603 // operators taking an object instead of a reference are allowed.
7604
Sean Hunt30de05c2011-05-14 05:23:20 +00007605 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7606 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithb9d0b762012-07-27 04:22:15 +00007607 if (isImplicitCopyAssignmentArgConst(*this, ClassDecl))
Sean Hunt30de05c2011-05-14 05:23:20 +00007608 ArgType = ArgType.withConst();
7609 ArgType = Context.getLValueReferenceType(ArgType);
7610
Douglas Gregord3c35902010-07-01 16:36:15 +00007611 // An implicitly-declared copy assignment operator is an inline public
7612 // member of its class.
7613 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007614 SourceLocation ClassLoc = ClassDecl->getLocation();
7615 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007616 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00007617 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00007618 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007619 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007620 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007621 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007622 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007623 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007624 CopyAssignment->setImplicit();
7625 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Richard Smithb9d0b762012-07-27 04:22:15 +00007626
7627 // Build an exception specification pointing back at this member.
7628 FunctionProtoType::ExtProtoInfo EPI;
7629 EPI.ExceptionSpecType = EST_Unevaluated;
7630 EPI.ExceptionSpecDecl = CopyAssignment;
7631 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
7632
Douglas Gregord3c35902010-07-01 16:36:15 +00007633 // Add the parameter to the operator.
7634 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007635 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007636 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007637 SC_None,
7638 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007639 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007640
Douglas Gregora376d102010-07-02 21:50:04 +00007641 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007642 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007643
Douglas Gregor23c94db2010-07-02 17:43:08 +00007644 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007645 PushOnScopeChains(CopyAssignment, S, false);
7646 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007647
Nico Weberafcc96a2012-01-23 03:19:29 +00007648 // C++0x [class.copy]p19:
7649 // .... If the class definition does not explicitly declare a copy
7650 // assignment operator, there is no user-declared move constructor, and
7651 // there is no user-declared move assignment operator, a copy assignment
7652 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00007653 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007654 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00007655
Douglas Gregord3c35902010-07-01 16:36:15 +00007656 AddOverriddenMethods(ClassDecl, CopyAssignment);
7657 return CopyAssignment;
7658}
7659
Douglas Gregor06a9f362010-05-01 20:49:11 +00007660void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7661 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007662 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007663 CopyAssignOperator->isOverloadedOperator() &&
7664 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007665 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7666 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007667 "DefineImplicitCopyAssignment called for wrong function");
7668
7669 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7670
7671 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7672 CopyAssignOperator->setInvalidDecl();
7673 return;
7674 }
7675
7676 CopyAssignOperator->setUsed();
7677
7678 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007679 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007680
7681 // C++0x [class.copy]p30:
7682 // The implicitly-defined or explicitly-defaulted copy assignment operator
7683 // for a non-union class X performs memberwise copy assignment of its
7684 // subobjects. The direct base classes of X are assigned first, in the
7685 // order of their declaration in the base-specifier-list, and then the
7686 // immediate non-static data members of X are assigned, in the order in
7687 // which they were declared in the class definition.
7688
7689 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00007690 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007691
7692 // The parameter for the "other" object, which we are copying from.
7693 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7694 Qualifiers OtherQuals = Other->getType().getQualifiers();
7695 QualType OtherRefType = Other->getType();
7696 if (const LValueReferenceType *OtherRef
7697 = OtherRefType->getAs<LValueReferenceType>()) {
7698 OtherRefType = OtherRef->getPointeeType();
7699 OtherQuals = OtherRefType.getQualifiers();
7700 }
7701
7702 // Our location for everything implicitly-generated.
7703 SourceLocation Loc = CopyAssignOperator->getLocation();
7704
7705 // Construct a reference to the "other" object. We'll be using this
7706 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007707 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007708 assert(OtherRef && "Reference to parameter cannot fail!");
7709
7710 // Construct the "this" pointer. We'll be using this throughout the generated
7711 // ASTs.
7712 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7713 assert(This && "Reference to this cannot fail!");
7714
7715 // Assign base classes.
7716 bool Invalid = false;
7717 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7718 E = ClassDecl->bases_end(); Base != E; ++Base) {
7719 // Form the assignment:
7720 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7721 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007722 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007723 Invalid = true;
7724 continue;
7725 }
7726
John McCallf871d0c2010-08-07 06:22:56 +00007727 CXXCastPath BasePath;
7728 BasePath.push_back(Base);
7729
Douglas Gregor06a9f362010-05-01 20:49:11 +00007730 // Construct the "from" expression, which is an implicit cast to the
7731 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007732 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007733 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7734 CK_UncheckedDerivedToBase,
7735 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007736
7737 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007738 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007739
7740 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007741 To = ImpCastExprToType(To.take(),
7742 Context.getCVRQualifiedType(BaseType,
7743 CopyAssignOperator->getTypeQualifiers()),
7744 CK_UncheckedDerivedToBase,
7745 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007746
7747 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007748 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007749 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007750 /*CopyingBaseSubobject=*/true,
7751 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007752 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007753 Diag(CurrentLocation, diag::note_member_synthesized_at)
7754 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7755 CopyAssignOperator->setInvalidDecl();
7756 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007757 }
7758
7759 // Success! Record the copy.
7760 Statements.push_back(Copy.takeAs<Expr>());
7761 }
7762
7763 // \brief Reference to the __builtin_memcpy function.
7764 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007765 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007766 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007767
7768 // Assign non-static members.
7769 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7770 FieldEnd = ClassDecl->field_end();
7771 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007772 if (Field->isUnnamedBitfield())
7773 continue;
7774
Douglas Gregor06a9f362010-05-01 20:49:11 +00007775 // Check for members of reference type; we can't copy those.
7776 if (Field->getType()->isReferenceType()) {
7777 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7778 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7779 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007780 Diag(CurrentLocation, diag::note_member_synthesized_at)
7781 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007782 Invalid = true;
7783 continue;
7784 }
7785
7786 // Check for members of const-qualified, non-class type.
7787 QualType BaseType = Context.getBaseElementType(Field->getType());
7788 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7789 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7790 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7791 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007792 Diag(CurrentLocation, diag::note_member_synthesized_at)
7793 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007794 Invalid = true;
7795 continue;
7796 }
John McCallb77115d2011-06-17 00:18:42 +00007797
7798 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007799 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7800 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007801
7802 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007803 if (FieldType->isIncompleteArrayType()) {
7804 assert(ClassDecl->hasFlexibleArrayMember() &&
7805 "Incomplete array type is not valid");
7806 continue;
7807 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007808
7809 // Build references to the field in the object we're copying from and to.
7810 CXXScopeSpec SS; // Intentionally empty
7811 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7812 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00007813 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007814 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007815 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007816 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007817 SS, SourceLocation(), 0,
7818 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007819 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007820 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007821 SS, SourceLocation(), 0,
7822 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007823 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7824 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7825
7826 // If the field should be copied with __builtin_memcpy rather than via
7827 // explicit assignments, do so. This optimization only applies for arrays
7828 // of scalars and arrays of class type with trivial copy-assignment
7829 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007830 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007831 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007832 // Compute the size of the memory buffer to be copied.
7833 QualType SizeType = Context.getSizeType();
7834 llvm::APInt Size(Context.getTypeSize(SizeType),
7835 Context.getTypeSizeInChars(BaseType).getQuantity());
7836 for (const ConstantArrayType *Array
7837 = Context.getAsConstantArrayType(FieldType);
7838 Array;
7839 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007840 llvm::APInt ArraySize
7841 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007842 Size *= ArraySize;
7843 }
7844
7845 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007846 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7847 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007848
7849 bool NeedsCollectableMemCpy =
7850 (BaseType->isRecordType() &&
7851 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7852
7853 if (NeedsCollectableMemCpy) {
7854 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007855 // Create a reference to the __builtin_objc_memmove_collectable function.
7856 LookupResult R(*this,
7857 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007858 Loc, LookupOrdinaryName);
7859 LookupName(R, TUScope, true);
7860
7861 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7862 if (!CollectableMemCpy) {
7863 // Something went horribly wrong earlier, and we will have
7864 // complained about it.
7865 Invalid = true;
7866 continue;
7867 }
7868
7869 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
Eli Friedmana6c66ce2012-08-31 00:14:07 +00007870 Context.BuiltinFnTy,
7871 VK_RValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007872 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7873 }
7874 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007875 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007876 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007877 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7878 LookupOrdinaryName);
7879 LookupName(R, TUScope, true);
7880
7881 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7882 if (!BuiltinMemCpy) {
7883 // Something went horribly wrong earlier, and we will have complained
7884 // about it.
7885 Invalid = true;
7886 continue;
7887 }
7888
7889 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
Eli Friedmana6c66ce2012-08-31 00:14:07 +00007890 Context.BuiltinFnTy,
7891 VK_RValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007892 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7893 }
7894
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00007895 SmallVector<Expr*, 8> CallArgs;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007896 CallArgs.push_back(To.takeAs<Expr>());
7897 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007898 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007899 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007900 if (NeedsCollectableMemCpy)
7901 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007902 CollectableMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007903 Loc, CallArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007904 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007905 else
7906 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007907 BuiltinMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007908 Loc, CallArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007909 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007910
Douglas Gregor06a9f362010-05-01 20:49:11 +00007911 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7912 Statements.push_back(Call.takeAs<Expr>());
7913 continue;
7914 }
7915
7916 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007917 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007918 To.get(), From.get(),
7919 /*CopyingBaseSubobject=*/false,
7920 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007921 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007922 Diag(CurrentLocation, diag::note_member_synthesized_at)
7923 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7924 CopyAssignOperator->setInvalidDecl();
7925 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007926 }
7927
7928 // Success! Record the copy.
7929 Statements.push_back(Copy.takeAs<Stmt>());
7930 }
7931
7932 if (!Invalid) {
7933 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007934 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007935
John McCall60d7b3a2010-08-24 06:29:42 +00007936 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007937 if (Return.isInvalid())
7938 Invalid = true;
7939 else {
7940 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007941
7942 if (Trap.hasErrorOccurred()) {
7943 Diag(CurrentLocation, diag::note_member_synthesized_at)
7944 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7945 Invalid = true;
7946 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007947 }
7948 }
7949
7950 if (Invalid) {
7951 CopyAssignOperator->setInvalidDecl();
7952 return;
7953 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007954
7955 StmtResult Body;
7956 {
7957 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007958 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007959 /*isStmtExpr=*/false);
7960 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7961 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007962 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007963
7964 if (ASTMutationListener *L = getASTMutationListener()) {
7965 L->CompletedImplicitDefinition(CopyAssignOperator);
7966 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007967}
7968
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007969Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007970Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
7971 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007972
Richard Smithb9d0b762012-07-27 04:22:15 +00007973 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007974 if (ClassDecl->isInvalidDecl())
7975 return ExceptSpec;
7976
7977 // C++0x [except.spec]p14:
7978 // An implicitly declared special member function (Clause 12) shall have an
7979 // exception-specification. [...]
7980
7981 // It is unspecified whether or not an implicit move assignment operator
7982 // attempts to deduplicate calls to assignment operators of virtual bases are
7983 // made. As such, this exception specification is effectively unspecified.
7984 // Based on a similar decision made for constness in C++0x, we're erring on
7985 // the side of assuming such calls to be made regardless of whether they
7986 // actually happen.
7987 // Note that a move constructor is not implicitly declared when there are
7988 // virtual bases, but it can still be user-declared and explicitly defaulted.
7989 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7990 BaseEnd = ClassDecl->bases_end();
7991 Base != BaseEnd; ++Base) {
7992 if (Base->isVirtual())
7993 continue;
7994
7995 CXXRecordDecl *BaseClassDecl
7996 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7997 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00007998 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007999 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008000 }
8001
8002 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8003 BaseEnd = ClassDecl->vbases_end();
8004 Base != BaseEnd; ++Base) {
8005 CXXRecordDecl *BaseClassDecl
8006 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8007 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00008008 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008009 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008010 }
8011
8012 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8013 FieldEnd = ClassDecl->field_end();
8014 Field != FieldEnd;
8015 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008016 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008017 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008018 if (CXXMethodDecl *MoveAssign =
8019 LookupMovingAssignment(FieldClassDecl,
8020 FieldType.getCVRQualifiers(),
8021 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008022 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008023 }
8024 }
8025
8026 return ExceptSpec;
8027}
8028
Richard Smith1c931be2012-04-02 18:40:40 +00008029/// Determine whether the class type has any direct or indirect virtual base
8030/// classes which have a non-trivial move assignment operator.
8031static bool
8032hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8033 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8034 BaseEnd = ClassDecl->vbases_end();
8035 Base != BaseEnd; ++Base) {
8036 CXXRecordDecl *BaseClass =
8037 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8038
8039 // Try to declare the move assignment. If it would be deleted, then the
8040 // class does not have a non-trivial move assignment.
8041 if (BaseClass->needsImplicitMoveAssignment())
8042 S.DeclareImplicitMoveAssignment(BaseClass);
8043
8044 // If the class has both a trivial move assignment and a non-trivial move
8045 // assignment, hasTrivialMoveAssignment() is false.
8046 if (BaseClass->hasDeclaredMoveAssignment() &&
8047 !BaseClass->hasTrivialMoveAssignment())
8048 return true;
8049 }
8050
8051 return false;
8052}
8053
8054/// Determine whether the given type either has a move constructor or is
8055/// trivially copyable.
8056static bool
8057hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8058 Type = S.Context.getBaseElementType(Type);
8059
8060 // FIXME: Technically, non-trivially-copyable non-class types, such as
8061 // reference types, are supposed to return false here, but that appears
8062 // to be a standard defect.
8063 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Richard Smith5d59b792012-04-25 18:28:49 +00008064 if (!ClassDecl || !ClassDecl->getDefinition())
Richard Smith1c931be2012-04-02 18:40:40 +00008065 return true;
8066
8067 if (Type.isTriviallyCopyableType(S.Context))
8068 return true;
8069
8070 if (IsConstructor) {
8071 if (ClassDecl->needsImplicitMoveConstructor())
8072 S.DeclareImplicitMoveConstructor(ClassDecl);
8073 return ClassDecl->hasDeclaredMoveConstructor();
8074 }
8075
8076 if (ClassDecl->needsImplicitMoveAssignment())
8077 S.DeclareImplicitMoveAssignment(ClassDecl);
8078 return ClassDecl->hasDeclaredMoveAssignment();
8079}
8080
8081/// Determine whether all non-static data members and direct or virtual bases
8082/// of class \p ClassDecl have either a move operation, or are trivially
8083/// copyable.
8084static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8085 bool IsConstructor) {
8086 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8087 BaseEnd = ClassDecl->bases_end();
8088 Base != BaseEnd; ++Base) {
8089 if (Base->isVirtual())
8090 continue;
8091
8092 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8093 return false;
8094 }
8095
8096 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8097 BaseEnd = ClassDecl->vbases_end();
8098 Base != BaseEnd; ++Base) {
8099 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8100 return false;
8101 }
8102
8103 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8104 FieldEnd = ClassDecl->field_end();
8105 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008106 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008107 return false;
8108 }
8109
8110 return true;
8111}
8112
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008113CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008114 // C++11 [class.copy]p20:
8115 // If the definition of a class X does not explicitly declare a move
8116 // assignment operator, one will be implicitly declared as defaulted
8117 // if and only if:
8118 //
8119 // - [first 4 bullets]
8120 assert(ClassDecl->needsImplicitMoveAssignment());
8121
8122 // [Checked after we build the declaration]
8123 // - the move assignment operator would not be implicitly defined as
8124 // deleted,
8125
8126 // [DR1402]:
8127 // - X has no direct or indirect virtual base class with a non-trivial
8128 // move assignment operator, and
8129 // - each of X's non-static data members and direct or virtual base classes
8130 // has a type that either has a move assignment operator or is trivially
8131 // copyable.
8132 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8133 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8134 ClassDecl->setFailedImplicitMoveAssignment();
8135 return 0;
8136 }
8137
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008138 // Note: The following rules are largely analoguous to the move
8139 // constructor rules.
8140
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008141 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8142 QualType RetType = Context.getLValueReferenceType(ArgType);
8143 ArgType = Context.getRValueReferenceType(ArgType);
8144
8145 // An implicitly-declared move assignment operator is an inline public
8146 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008147 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8148 SourceLocation ClassLoc = ClassDecl->getLocation();
8149 DeclarationNameInfo NameInfo(Name, ClassLoc);
8150 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008151 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008152 /*TInfo=*/0, /*isStatic=*/false,
8153 /*StorageClassAsWritten=*/SC_None,
8154 /*isInline=*/true,
8155 /*isConstexpr=*/false,
8156 SourceLocation());
8157 MoveAssignment->setAccess(AS_public);
8158 MoveAssignment->setDefaulted();
8159 MoveAssignment->setImplicit();
8160 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8161
Richard Smithb9d0b762012-07-27 04:22:15 +00008162 // Build an exception specification pointing back at this member.
8163 FunctionProtoType::ExtProtoInfo EPI;
8164 EPI.ExceptionSpecType = EST_Unevaluated;
8165 EPI.ExceptionSpecDecl = MoveAssignment;
8166 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8167
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008168 // Add the parameter to the operator.
8169 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8170 ClassLoc, ClassLoc, /*Id=*/0,
8171 ArgType, /*TInfo=*/0,
8172 SC_None,
8173 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008174 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008175
8176 // Note that we have added this copy-assignment operator.
8177 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8178
8179 // C++0x [class.copy]p9:
8180 // If the definition of a class X does not explicitly declare a move
8181 // assignment operator, one will be implicitly declared as defaulted if and
8182 // only if:
8183 // [...]
8184 // - the move assignment operator would not be implicitly defined as
8185 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008186 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008187 // Cache this result so that we don't try to generate this over and over
8188 // on every lookup, leaking memory and wasting time.
8189 ClassDecl->setFailedImplicitMoveAssignment();
8190 return 0;
8191 }
8192
8193 if (Scope *S = getScopeForContext(ClassDecl))
8194 PushOnScopeChains(MoveAssignment, S, false);
8195 ClassDecl->addDecl(MoveAssignment);
8196
8197 AddOverriddenMethods(ClassDecl, MoveAssignment);
8198 return MoveAssignment;
8199}
8200
8201void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8202 CXXMethodDecl *MoveAssignOperator) {
8203 assert((MoveAssignOperator->isDefaulted() &&
8204 MoveAssignOperator->isOverloadedOperator() &&
8205 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008206 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8207 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008208 "DefineImplicitMoveAssignment called for wrong function");
8209
8210 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8211
8212 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8213 MoveAssignOperator->setInvalidDecl();
8214 return;
8215 }
8216
8217 MoveAssignOperator->setUsed();
8218
8219 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8220 DiagnosticErrorTrap Trap(Diags);
8221
8222 // C++0x [class.copy]p28:
8223 // The implicitly-defined or move assignment operator for a non-union class
8224 // X performs memberwise move assignment of its subobjects. The direct base
8225 // classes of X are assigned first, in the order of their declaration in the
8226 // base-specifier-list, and then the immediate non-static data members of X
8227 // are assigned, in the order in which they were declared in the class
8228 // definition.
8229
8230 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008231 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008232
8233 // The parameter for the "other" object, which we are move from.
8234 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8235 QualType OtherRefType = Other->getType()->
8236 getAs<RValueReferenceType>()->getPointeeType();
8237 assert(OtherRefType.getQualifiers() == 0 &&
8238 "Bad argument type of defaulted move assignment");
8239
8240 // Our location for everything implicitly-generated.
8241 SourceLocation Loc = MoveAssignOperator->getLocation();
8242
8243 // Construct a reference to the "other" object. We'll be using this
8244 // throughout the generated ASTs.
8245 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8246 assert(OtherRef && "Reference to parameter cannot fail!");
8247 // Cast to rvalue.
8248 OtherRef = CastForMoving(*this, OtherRef);
8249
8250 // Construct the "this" pointer. We'll be using this throughout the generated
8251 // ASTs.
8252 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8253 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008254
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008255 // Assign base classes.
8256 bool Invalid = false;
8257 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8258 E = ClassDecl->bases_end(); Base != E; ++Base) {
8259 // Form the assignment:
8260 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8261 QualType BaseType = Base->getType().getUnqualifiedType();
8262 if (!BaseType->isRecordType()) {
8263 Invalid = true;
8264 continue;
8265 }
8266
8267 CXXCastPath BasePath;
8268 BasePath.push_back(Base);
8269
8270 // Construct the "from" expression, which is an implicit cast to the
8271 // appropriately-qualified base type.
8272 Expr *From = OtherRef;
8273 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008274 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008275
8276 // Dereference "this".
8277 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8278
8279 // Implicitly cast "this" to the appropriately-qualified base type.
8280 To = ImpCastExprToType(To.take(),
8281 Context.getCVRQualifiedType(BaseType,
8282 MoveAssignOperator->getTypeQualifiers()),
8283 CK_UncheckedDerivedToBase,
8284 VK_LValue, &BasePath);
8285
8286 // Build the move.
8287 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8288 To.get(), From,
8289 /*CopyingBaseSubobject=*/true,
8290 /*Copying=*/false);
8291 if (Move.isInvalid()) {
8292 Diag(CurrentLocation, diag::note_member_synthesized_at)
8293 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8294 MoveAssignOperator->setInvalidDecl();
8295 return;
8296 }
8297
8298 // Success! Record the move.
8299 Statements.push_back(Move.takeAs<Expr>());
8300 }
8301
8302 // \brief Reference to the __builtin_memcpy function.
8303 Expr *BuiltinMemCpyRef = 0;
8304 // \brief Reference to the __builtin_objc_memmove_collectable function.
8305 Expr *CollectableMemCpyRef = 0;
8306
8307 // Assign non-static members.
8308 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8309 FieldEnd = ClassDecl->field_end();
8310 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008311 if (Field->isUnnamedBitfield())
8312 continue;
8313
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008314 // Check for members of reference type; we can't move those.
8315 if (Field->getType()->isReferenceType()) {
8316 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8317 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8318 Diag(Field->getLocation(), diag::note_declared_at);
8319 Diag(CurrentLocation, diag::note_member_synthesized_at)
8320 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8321 Invalid = true;
8322 continue;
8323 }
8324
8325 // Check for members of const-qualified, non-class type.
8326 QualType BaseType = Context.getBaseElementType(Field->getType());
8327 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8328 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8329 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8330 Diag(Field->getLocation(), diag::note_declared_at);
8331 Diag(CurrentLocation, diag::note_member_synthesized_at)
8332 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8333 Invalid = true;
8334 continue;
8335 }
8336
8337 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008338 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8339 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008340
8341 QualType FieldType = Field->getType().getNonReferenceType();
8342 if (FieldType->isIncompleteArrayType()) {
8343 assert(ClassDecl->hasFlexibleArrayMember() &&
8344 "Incomplete array type is not valid");
8345 continue;
8346 }
8347
8348 // Build references to the field in the object we're copying from and to.
8349 CXXScopeSpec SS; // Intentionally empty
8350 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8351 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008352 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008353 MemberLookup.resolveKind();
8354 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8355 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008356 SS, SourceLocation(), 0,
8357 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008358 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8359 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008360 SS, SourceLocation(), 0,
8361 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008362 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8363 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8364
8365 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8366 "Member reference with rvalue base must be rvalue except for reference "
8367 "members, which aren't allowed for move assignment.");
8368
8369 // If the field should be copied with __builtin_memcpy rather than via
8370 // explicit assignments, do so. This optimization only applies for arrays
8371 // of scalars and arrays of class type with trivial move-assignment
8372 // operators.
8373 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8374 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8375 // Compute the size of the memory buffer to be copied.
8376 QualType SizeType = Context.getSizeType();
8377 llvm::APInt Size(Context.getTypeSize(SizeType),
8378 Context.getTypeSizeInChars(BaseType).getQuantity());
8379 for (const ConstantArrayType *Array
8380 = Context.getAsConstantArrayType(FieldType);
8381 Array;
8382 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8383 llvm::APInt ArraySize
8384 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8385 Size *= ArraySize;
8386 }
8387
Douglas Gregor45d3d712011-09-01 02:09:07 +00008388 // Take the address of the field references for "from" and "to". We
8389 // directly construct UnaryOperators here because semantic analysis
8390 // does not permit us to take the address of an xvalue.
8391 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8392 Context.getPointerType(From.get()->getType()),
8393 VK_RValue, OK_Ordinary, Loc);
8394 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8395 Context.getPointerType(To.get()->getType()),
8396 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008397
8398 bool NeedsCollectableMemCpy =
8399 (BaseType->isRecordType() &&
8400 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8401
8402 if (NeedsCollectableMemCpy) {
8403 if (!CollectableMemCpyRef) {
8404 // Create a reference to the __builtin_objc_memmove_collectable function.
8405 LookupResult R(*this,
8406 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8407 Loc, LookupOrdinaryName);
8408 LookupName(R, TUScope, true);
8409
8410 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8411 if (!CollectableMemCpy) {
8412 // Something went horribly wrong earlier, and we will have
8413 // complained about it.
8414 Invalid = true;
8415 continue;
8416 }
8417
8418 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008419 Context.BuiltinFnTy,
8420 VK_RValue, Loc, 0).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008421 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8422 }
8423 }
8424 // Create a reference to the __builtin_memcpy builtin function.
8425 else if (!BuiltinMemCpyRef) {
8426 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8427 LookupOrdinaryName);
8428 LookupName(R, TUScope, true);
8429
8430 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8431 if (!BuiltinMemCpy) {
8432 // Something went horribly wrong earlier, and we will have complained
8433 // about it.
8434 Invalid = true;
8435 continue;
8436 }
8437
8438 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
Eli Friedmana6c66ce2012-08-31 00:14:07 +00008439 Context.BuiltinFnTy,
8440 VK_RValue, Loc, 0).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008441 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8442 }
8443
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008444 SmallVector<Expr*, 8> CallArgs;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008445 CallArgs.push_back(To.takeAs<Expr>());
8446 CallArgs.push_back(From.takeAs<Expr>());
8447 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8448 ExprResult Call = ExprError();
8449 if (NeedsCollectableMemCpy)
8450 Call = ActOnCallExpr(/*Scope=*/0,
8451 CollectableMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008452 Loc, CallArgs,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008453 Loc);
8454 else
8455 Call = ActOnCallExpr(/*Scope=*/0,
8456 BuiltinMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008457 Loc, CallArgs,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008458 Loc);
8459
8460 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8461 Statements.push_back(Call.takeAs<Expr>());
8462 continue;
8463 }
8464
8465 // Build the move of this field.
8466 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8467 To.get(), From.get(),
8468 /*CopyingBaseSubobject=*/false,
8469 /*Copying=*/false);
8470 if (Move.isInvalid()) {
8471 Diag(CurrentLocation, diag::note_member_synthesized_at)
8472 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8473 MoveAssignOperator->setInvalidDecl();
8474 return;
8475 }
8476
8477 // Success! Record the copy.
8478 Statements.push_back(Move.takeAs<Stmt>());
8479 }
8480
8481 if (!Invalid) {
8482 // Add a "return *this;"
8483 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8484
8485 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8486 if (Return.isInvalid())
8487 Invalid = true;
8488 else {
8489 Statements.push_back(Return.takeAs<Stmt>());
8490
8491 if (Trap.hasErrorOccurred()) {
8492 Diag(CurrentLocation, diag::note_member_synthesized_at)
8493 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8494 Invalid = true;
8495 }
8496 }
8497 }
8498
8499 if (Invalid) {
8500 MoveAssignOperator->setInvalidDecl();
8501 return;
8502 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008503
8504 StmtResult Body;
8505 {
8506 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008507 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008508 /*isStmtExpr=*/false);
8509 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8510 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008511 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8512
8513 if (ASTMutationListener *L = getASTMutationListener()) {
8514 L->CompletedImplicitDefinition(MoveAssignOperator);
8515 }
8516}
8517
Richard Smithb9d0b762012-07-27 04:22:15 +00008518/// Determine whether an implicit copy constructor for ClassDecl has a const
8519/// argument.
8520/// FIXME: It ought to be possible to store this on the record.
8521static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008522 if (ClassDecl->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00008523 return true;
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008524
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008525 // C++ [class.copy]p5:
8526 // The implicitly-declared copy constructor for a class X will
8527 // have the form
8528 //
8529 // X::X(const X&)
8530 //
8531 // if
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008532 // -- each direct or virtual base class B of X has a copy
8533 // constructor whose first parameter is of type const B& or
8534 // const volatile B&, and
8535 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8536 BaseEnd = ClassDecl->bases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008537 Base != BaseEnd; ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008538 // Virtual bases are handled below.
8539 if (Base->isVirtual())
8540 continue;
Richard Smithb9d0b762012-07-27 04:22:15 +00008541
Douglas Gregor22584312010-07-02 23:41:54 +00008542 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008543 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smithb9d0b762012-07-27 04:22:15 +00008544 // FIXME: This lookup is wrong. If the copy ctor for a member or base is
8545 // ambiguous, we should still produce a constructor with a const-qualified
8546 // parameter.
8547 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8548 return false;
Douglas Gregor598a8542010-07-01 18:27:03 +00008549 }
8550
8551 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8552 BaseEnd = ClassDecl->vbases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008553 Base != BaseEnd; ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008554 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008555 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smithb9d0b762012-07-27 04:22:15 +00008556 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8557 return false;
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008558 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008559
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008560 // -- for all the nonstatic data members of X that are of a
8561 // class type M (or array thereof), each such class type
8562 // has a copy constructor whose first parameter is of type
8563 // const M& or const volatile M&.
8564 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8565 FieldEnd = ClassDecl->field_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008566 Field != FieldEnd; ++Field) {
8567 QualType FieldType = S.Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008568 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smithb9d0b762012-07-27 04:22:15 +00008569 if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const))
8570 return false;
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008571 }
8572 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008573
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008574 // Otherwise, the implicitly declared copy constructor will have
8575 // the form
8576 //
8577 // X::X(X&)
Richard Smithb9d0b762012-07-27 04:22:15 +00008578
8579 return true;
8580}
8581
8582Sema::ImplicitExceptionSpecification
8583Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
8584 CXXRecordDecl *ClassDecl = MD->getParent();
8585
8586 ImplicitExceptionSpecification ExceptSpec(*this);
8587 if (ClassDecl->isInvalidDecl())
8588 return ExceptSpec;
8589
8590 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8591 assert(T->getNumArgs() >= 1 && "not a copy ctor");
8592 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8593
Douglas Gregor0d405db2010-07-01 20:59:04 +00008594 // C++ [except.spec]p14:
8595 // An implicitly declared special member function (Clause 12) shall have an
8596 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00008597 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8598 BaseEnd = ClassDecl->bases_end();
8599 Base != BaseEnd;
8600 ++Base) {
8601 // Virtual bases are handled below.
8602 if (Base->isVirtual())
8603 continue;
8604
Douglas Gregor22584312010-07-02 23:41:54 +00008605 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008606 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008607 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008608 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008609 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008610 }
8611 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8612 BaseEnd = ClassDecl->vbases_end();
8613 Base != BaseEnd;
8614 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008615 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008616 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008617 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008618 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008619 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008620 }
8621 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8622 FieldEnd = ClassDecl->field_end();
8623 Field != FieldEnd;
8624 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008625 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008626 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8627 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008628 LookupCopyingConstructor(FieldClassDecl,
8629 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00008630 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008631 }
8632 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008633
Richard Smithb9d0b762012-07-27 04:22:15 +00008634 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00008635}
8636
8637CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8638 CXXRecordDecl *ClassDecl) {
8639 // C++ [class.copy]p4:
8640 // If the class definition does not explicitly declare a copy
8641 // constructor, one is declared implicitly.
8642
Sean Hunt49634cf2011-05-13 06:10:58 +00008643 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8644 QualType ArgType = ClassType;
Richard Smithb9d0b762012-07-27 04:22:15 +00008645 bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl);
Sean Hunt49634cf2011-05-13 06:10:58 +00008646 if (Const)
8647 ArgType = ArgType.withConst();
8648 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00008649
Richard Smith7756afa2012-06-10 05:43:50 +00008650 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8651 CXXCopyConstructor,
8652 Const);
8653
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008654 DeclarationName Name
8655 = Context.DeclarationNames.getCXXConstructorName(
8656 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008657 SourceLocation ClassLoc = ClassDecl->getLocation();
8658 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008659
8660 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008661 // member of its class.
8662 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008663 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008664 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008665 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008666 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008667 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008668 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008669
Richard Smithb9d0b762012-07-27 04:22:15 +00008670 // Build an exception specification pointing back at this member.
8671 FunctionProtoType::ExtProtoInfo EPI;
8672 EPI.ExceptionSpecType = EST_Unevaluated;
8673 EPI.ExceptionSpecDecl = CopyConstructor;
8674 CopyConstructor->setType(
8675 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8676
Douglas Gregor22584312010-07-02 23:41:54 +00008677 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008678 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8679
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008680 // Add the parameter to the constructor.
8681 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008682 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008683 /*IdentifierInfo=*/0,
8684 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008685 SC_None,
8686 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008687 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008688
Douglas Gregor23c94db2010-07-02 17:43:08 +00008689 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008690 PushOnScopeChains(CopyConstructor, S, false);
8691 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008692
Nico Weberafcc96a2012-01-23 03:19:29 +00008693 // C++11 [class.copy]p8:
8694 // ... If the class definition does not explicitly declare a copy
8695 // constructor, there is no user-declared move constructor, and there is no
8696 // user-declared move assignment operator, a copy constructor is implicitly
8697 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008698 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008699 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008700
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008701 return CopyConstructor;
8702}
8703
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008704void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008705 CXXConstructorDecl *CopyConstructor) {
8706 assert((CopyConstructor->isDefaulted() &&
8707 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008708 !CopyConstructor->doesThisDeclarationHaveABody() &&
8709 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008710 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008711
Anders Carlsson63010a72010-04-23 16:24:12 +00008712 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008713 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008714
Douglas Gregor39957dc2010-05-01 15:04:51 +00008715 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008716 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008717
Sean Huntcbb67482011-01-08 20:30:50 +00008718 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008719 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008720 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008721 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008722 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008723 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008724 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008725 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8726 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00008727 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008728 /*isStmtExpr=*/false)
8729 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008730 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008731 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008732
8733 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008734 if (ASTMutationListener *L = getASTMutationListener()) {
8735 L->CompletedImplicitDefinition(CopyConstructor);
8736 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008737}
8738
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008739Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008740Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
8741 CXXRecordDecl *ClassDecl = MD->getParent();
8742
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008743 // C++ [except.spec]p14:
8744 // An implicitly declared special member function (Clause 12) shall have an
8745 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008746 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008747 if (ClassDecl->isInvalidDecl())
8748 return ExceptSpec;
8749
8750 // Direct base-class constructors.
8751 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8752 BEnd = ClassDecl->bases_end();
8753 B != BEnd; ++B) {
8754 if (B->isVirtual()) // Handled below.
8755 continue;
8756
8757 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8758 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00008759 CXXConstructorDecl *Constructor =
8760 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008761 // If this is a deleted function, add it anyway. This might be conformant
8762 // with the standard. This might not. I'm not sure. It might not matter.
8763 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008764 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008765 }
8766 }
8767
8768 // Virtual base-class constructors.
8769 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8770 BEnd = ClassDecl->vbases_end();
8771 B != BEnd; ++B) {
8772 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8773 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00008774 CXXConstructorDecl *Constructor =
8775 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008776 // If this is a deleted function, add it anyway. This might be conformant
8777 // with the standard. This might not. I'm not sure. It might not matter.
8778 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008779 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008780 }
8781 }
8782
8783 // Field constructors.
8784 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8785 FEnd = ClassDecl->field_end();
8786 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008787 QualType FieldType = Context.getBaseElementType(F->getType());
8788 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
8789 CXXConstructorDecl *Constructor =
8790 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008791 // If this is a deleted function, add it anyway. This might be conformant
8792 // with the standard. This might not. I'm not sure. It might not matter.
8793 // In particular, the problem is that this function never gets called. It
8794 // might just be ill-formed because this function attempts to refer to
8795 // a deleted function here.
8796 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008797 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008798 }
8799 }
8800
8801 return ExceptSpec;
8802}
8803
8804CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8805 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008806 // C++11 [class.copy]p9:
8807 // If the definition of a class X does not explicitly declare a move
8808 // constructor, one will be implicitly declared as defaulted if and only if:
8809 //
8810 // - [first 4 bullets]
8811 assert(ClassDecl->needsImplicitMoveConstructor());
8812
8813 // [Checked after we build the declaration]
8814 // - the move assignment operator would not be implicitly defined as
8815 // deleted,
8816
8817 // [DR1402]:
8818 // - each of X's non-static data members and direct or virtual base classes
8819 // has a type that either has a move constructor or is trivially copyable.
8820 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8821 ClassDecl->setFailedImplicitMoveConstructor();
8822 return 0;
8823 }
8824
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008825 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8826 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008827
Richard Smith7756afa2012-06-10 05:43:50 +00008828 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8829 CXXMoveConstructor,
8830 false);
8831
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008832 DeclarationName Name
8833 = Context.DeclarationNames.getCXXConstructorName(
8834 Context.getCanonicalType(ClassType));
8835 SourceLocation ClassLoc = ClassDecl->getLocation();
8836 DeclarationNameInfo NameInfo(Name, ClassLoc);
8837
8838 // C++0x [class.copy]p11:
8839 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008840 // member of its class.
8841 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008842 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008843 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008844 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008845 MoveConstructor->setAccess(AS_public);
8846 MoveConstructor->setDefaulted();
8847 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008848
Richard Smithb9d0b762012-07-27 04:22:15 +00008849 // Build an exception specification pointing back at this member.
8850 FunctionProtoType::ExtProtoInfo EPI;
8851 EPI.ExceptionSpecType = EST_Unevaluated;
8852 EPI.ExceptionSpecDecl = MoveConstructor;
8853 MoveConstructor->setType(
8854 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8855
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008856 // Add the parameter to the constructor.
8857 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8858 ClassLoc, ClassLoc,
8859 /*IdentifierInfo=*/0,
8860 ArgType, /*TInfo=*/0,
8861 SC_None,
8862 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008863 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008864
8865 // C++0x [class.copy]p9:
8866 // If the definition of a class X does not explicitly declare a move
8867 // constructor, one will be implicitly declared as defaulted if and only if:
8868 // [...]
8869 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008870 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008871 // Cache this result so that we don't try to generate this over and over
8872 // on every lookup, leaking memory and wasting time.
8873 ClassDecl->setFailedImplicitMoveConstructor();
8874 return 0;
8875 }
8876
8877 // Note that we have declared this constructor.
8878 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8879
8880 if (Scope *S = getScopeForContext(ClassDecl))
8881 PushOnScopeChains(MoveConstructor, S, false);
8882 ClassDecl->addDecl(MoveConstructor);
8883
8884 return MoveConstructor;
8885}
8886
8887void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8888 CXXConstructorDecl *MoveConstructor) {
8889 assert((MoveConstructor->isDefaulted() &&
8890 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008891 !MoveConstructor->doesThisDeclarationHaveABody() &&
8892 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008893 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8894
8895 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8896 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8897
8898 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8899 DiagnosticErrorTrap Trap(Diags);
8900
8901 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8902 Trap.hasErrorOccurred()) {
8903 Diag(CurrentLocation, diag::note_member_synthesized_at)
8904 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8905 MoveConstructor->setInvalidDecl();
8906 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008907 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008908 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8909 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00008910 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008911 /*isStmtExpr=*/false)
8912 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008913 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008914 }
8915
8916 MoveConstructor->setUsed();
8917
8918 if (ASTMutationListener *L = getASTMutationListener()) {
8919 L->CompletedImplicitDefinition(MoveConstructor);
8920 }
8921}
8922
Douglas Gregore4e68d42012-02-15 19:33:52 +00008923bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8924 return FD->isDeleted() &&
8925 (FD->isDefaulted() || FD->isImplicit()) &&
8926 isa<CXXMethodDecl>(FD);
8927}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008928
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008929/// \brief Mark the call operator of the given lambda closure type as "used".
8930static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8931 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008932 = cast<CXXMethodDecl>(
8933 *Lambda->lookup(
8934 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008935 CallOperator->setReferenced();
8936 CallOperator->setUsed();
8937}
8938
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008939void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8940 SourceLocation CurrentLocation,
8941 CXXConversionDecl *Conv)
8942{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008943 CXXRecordDecl *Lambda = Conv->getParent();
8944
8945 // Make sure that the lambda call operator is marked used.
8946 markLambdaCallOperatorUsed(*this, Lambda);
8947
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008948 Conv->setUsed();
8949
8950 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8951 DiagnosticErrorTrap Trap(Diags);
8952
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008953 // Return the address of the __invoke function.
8954 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8955 CXXMethodDecl *Invoke
8956 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8957 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8958 VK_LValue, Conv->getLocation()).take();
8959 assert(FunctionRef && "Can't refer to __invoke function?");
8960 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8961 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8962 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008963 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008964
8965 // Fill in the __invoke function with a dummy implementation. IR generation
8966 // will fill in the actual details.
8967 Invoke->setUsed();
8968 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008969 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008970
8971 if (ASTMutationListener *L = getASTMutationListener()) {
8972 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008973 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008974 }
8975}
8976
8977void Sema::DefineImplicitLambdaToBlockPointerConversion(
8978 SourceLocation CurrentLocation,
8979 CXXConversionDecl *Conv)
8980{
8981 Conv->setUsed();
8982
8983 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8984 DiagnosticErrorTrap Trap(Diags);
8985
Douglas Gregorac1303e2012-02-22 05:02:47 +00008986 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008987 Expr *This = ActOnCXXThis(CurrentLocation).take();
8988 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008989
Eli Friedman23f02672012-03-01 04:01:32 +00008990 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8991 Conv->getLocation(),
8992 Conv, DerefThis);
8993
8994 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8995 // behavior. Note that only the general conversion function does this
8996 // (since it's unusable otherwise); in the case where we inline the
8997 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00008998 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00008999 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9000 CK_CopyAndAutoreleaseBlockObject,
9001 BuildBlock.get(), 0, VK_RValue);
9002
9003 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009004 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00009005 Conv->setInvalidDecl();
9006 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009007 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00009008
Douglas Gregorac1303e2012-02-22 05:02:47 +00009009 // Create the return statement that returns the block from the conversion
9010 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00009011 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00009012 if (Return.isInvalid()) {
9013 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9014 Conv->setInvalidDecl();
9015 return;
9016 }
9017
9018 // Set the body of the conversion function.
9019 Stmt *ReturnS = Return.take();
9020 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9021 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009022 Conv->getLocation()));
9023
Douglas Gregorac1303e2012-02-22 05:02:47 +00009024 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009025 if (ASTMutationListener *L = getASTMutationListener()) {
9026 L->CompletedImplicitDefinition(Conv);
9027 }
9028}
9029
Douglas Gregorf52757d2012-03-10 06:53:13 +00009030/// \brief Determine whether the given list arguments contains exactly one
9031/// "real" (non-default) argument.
9032static bool hasOneRealArgument(MultiExprArg Args) {
9033 switch (Args.size()) {
9034 case 0:
9035 return false;
9036
9037 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009038 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009039 return false;
9040
9041 // fall through
9042 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009043 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009044 }
9045
9046 return false;
9047}
9048
John McCall60d7b3a2010-08-24 06:29:42 +00009049ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009050Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009051 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009052 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009053 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009054 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009055 unsigned ConstructKind,
9056 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009057 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009058
Douglas Gregor2f599792010-04-02 18:24:57 +00009059 // C++0x [class.copy]p34:
9060 // When certain criteria are met, an implementation is allowed to
9061 // omit the copy/move construction of a class object, even if the
9062 // copy/move constructor and/or destructor for the object have
9063 // side effects. [...]
9064 // - when a temporary class object that has not been bound to a
9065 // reference (12.2) would be copied/moved to a class object
9066 // with the same cv-unqualified type, the copy/move operation
9067 // can be omitted by constructing the temporary object
9068 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009069 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009070 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009071 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009072 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009073 }
Mike Stump1eb44332009-09-09 15:08:12 +00009074
9075 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009076 Elidable, ExprArgs, HadMultipleCandidates,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009077 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009078}
9079
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009080/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9081/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009082ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009083Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9084 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009085 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009086 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009087 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009088 unsigned ConstructKind,
9089 SourceRange ParenRange) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00009090 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009091 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009092 Constructor, Elidable, ExprArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009093 HadMultipleCandidates, /*FIXME*/false,
9094 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009095 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9096 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009097}
9098
Mike Stump1eb44332009-09-09 15:08:12 +00009099bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009100 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009101 MultiExprArg Exprs,
9102 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009103 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009104 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009105 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009106 Exprs, HadMultipleCandidates, false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009107 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009108 if (TempResult.isInvalid())
9109 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009110
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009111 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009112 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009113 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009114 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009115 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009116
Anders Carlssonfe2de492009-08-25 05:18:00 +00009117 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009118}
9119
John McCall68c6c9a2010-02-02 09:10:11 +00009120void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009121 if (VD->isInvalidDecl()) return;
9122
John McCall68c6c9a2010-02-02 09:10:11 +00009123 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009124 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009125 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009126 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009127
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009128 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009129 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009130 CheckDestructorAccess(VD->getLocation(), Destructor,
9131 PDiag(diag::err_access_dtor_var)
9132 << VD->getDeclName()
9133 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009134 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009135
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009136 if (!VD->hasGlobalStorage()) return;
9137
9138 // Emit warning for non-trivial dtor in global scope (a real global,
9139 // class-static, function-static).
9140 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9141
9142 // TODO: this should be re-enabled for static locals by !CXAAtExit
9143 if (!VD->isStaticLocal())
9144 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009145}
9146
Douglas Gregor39da0b82009-09-09 23:08:42 +00009147/// \brief Given a constructor and the set of arguments provided for the
9148/// constructor, convert the arguments and add any required default arguments
9149/// to form a proper call to this constructor.
9150///
9151/// \returns true if an error occurred, false otherwise.
9152bool
9153Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9154 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009155 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009156 SmallVectorImpl<Expr*> &ConvertedArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009157 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009158 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9159 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009160 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009161
9162 const FunctionProtoType *Proto
9163 = Constructor->getType()->getAs<FunctionProtoType>();
9164 assert(Proto && "Constructor without a prototype?");
9165 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009166
9167 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009168 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009169 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009170 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009171 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009172
9173 VariadicCallType CallType =
9174 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009175 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009176 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9177 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009178 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009179 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009180
9181 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9182
Richard Smith831421f2012-06-25 20:30:08 +00009183 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9184 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009185
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009186 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009187}
9188
Anders Carlsson20d45d22009-12-12 00:32:00 +00009189static inline bool
9190CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9191 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009192 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009193 if (isa<NamespaceDecl>(DC)) {
9194 return SemaRef.Diag(FnDecl->getLocation(),
9195 diag::err_operator_new_delete_declared_in_namespace)
9196 << FnDecl->getDeclName();
9197 }
9198
9199 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009200 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009201 return SemaRef.Diag(FnDecl->getLocation(),
9202 diag::err_operator_new_delete_declared_static)
9203 << FnDecl->getDeclName();
9204 }
9205
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009206 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009207}
9208
Anders Carlsson156c78e2009-12-13 17:53:43 +00009209static inline bool
9210CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9211 CanQualType ExpectedResultType,
9212 CanQualType ExpectedFirstParamType,
9213 unsigned DependentParamTypeDiag,
9214 unsigned InvalidParamTypeDiag) {
9215 QualType ResultType =
9216 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9217
9218 // Check that the result type is not dependent.
9219 if (ResultType->isDependentType())
9220 return SemaRef.Diag(FnDecl->getLocation(),
9221 diag::err_operator_new_delete_dependent_result_type)
9222 << FnDecl->getDeclName() << ExpectedResultType;
9223
9224 // Check that the result type is what we expect.
9225 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9226 return SemaRef.Diag(FnDecl->getLocation(),
9227 diag::err_operator_new_delete_invalid_result_type)
9228 << FnDecl->getDeclName() << ExpectedResultType;
9229
9230 // A function template must have at least 2 parameters.
9231 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9232 return SemaRef.Diag(FnDecl->getLocation(),
9233 diag::err_operator_new_delete_template_too_few_parameters)
9234 << FnDecl->getDeclName();
9235
9236 // The function decl must have at least 1 parameter.
9237 if (FnDecl->getNumParams() == 0)
9238 return SemaRef.Diag(FnDecl->getLocation(),
9239 diag::err_operator_new_delete_too_few_parameters)
9240 << FnDecl->getDeclName();
9241
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009242 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009243 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9244 if (FirstParamType->isDependentType())
9245 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9246 << FnDecl->getDeclName() << ExpectedFirstParamType;
9247
9248 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009249 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009250 ExpectedFirstParamType)
9251 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9252 << FnDecl->getDeclName() << ExpectedFirstParamType;
9253
9254 return false;
9255}
9256
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009257static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009258CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009259 // C++ [basic.stc.dynamic.allocation]p1:
9260 // A program is ill-formed if an allocation function is declared in a
9261 // namespace scope other than global scope or declared static in global
9262 // scope.
9263 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9264 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009265
9266 CanQualType SizeTy =
9267 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9268
9269 // C++ [basic.stc.dynamic.allocation]p1:
9270 // The return type shall be void*. The first parameter shall have type
9271 // std::size_t.
9272 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9273 SizeTy,
9274 diag::err_operator_new_dependent_param_type,
9275 diag::err_operator_new_param_type))
9276 return true;
9277
9278 // C++ [basic.stc.dynamic.allocation]p1:
9279 // The first parameter shall not have an associated default argument.
9280 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009281 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009282 diag::err_operator_new_default_arg)
9283 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9284
9285 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009286}
9287
9288static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009289CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9290 // C++ [basic.stc.dynamic.deallocation]p1:
9291 // A program is ill-formed if deallocation functions are declared in a
9292 // namespace scope other than global scope or declared static in global
9293 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009294 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9295 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009296
9297 // C++ [basic.stc.dynamic.deallocation]p2:
9298 // Each deallocation function shall return void and its first parameter
9299 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009300 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9301 SemaRef.Context.VoidPtrTy,
9302 diag::err_operator_delete_dependent_param_type,
9303 diag::err_operator_delete_param_type))
9304 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009305
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009306 return false;
9307}
9308
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009309/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9310/// of this overloaded operator is well-formed. If so, returns false;
9311/// otherwise, emits appropriate diagnostics and returns true.
9312bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009313 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009314 "Expected an overloaded operator declaration");
9315
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009316 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9317
Mike Stump1eb44332009-09-09 15:08:12 +00009318 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009319 // The allocation and deallocation functions, operator new,
9320 // operator new[], operator delete and operator delete[], are
9321 // described completely in 3.7.3. The attributes and restrictions
9322 // found in the rest of this subclause do not apply to them unless
9323 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009324 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009325 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009326
Anders Carlssona3ccda52009-12-12 00:26:23 +00009327 if (Op == OO_New || Op == OO_Array_New)
9328 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009329
9330 // C++ [over.oper]p6:
9331 // An operator function shall either be a non-static member
9332 // function or be a non-member function and have at least one
9333 // parameter whose type is a class, a reference to a class, an
9334 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009335 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9336 if (MethodDecl->isStatic())
9337 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009338 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009339 } else {
9340 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009341 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9342 ParamEnd = FnDecl->param_end();
9343 Param != ParamEnd; ++Param) {
9344 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009345 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9346 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009347 ClassOrEnumParam = true;
9348 break;
9349 }
9350 }
9351
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009352 if (!ClassOrEnumParam)
9353 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009354 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009355 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009356 }
9357
9358 // C++ [over.oper]p8:
9359 // An operator function cannot have default arguments (8.3.6),
9360 // except where explicitly stated below.
9361 //
Mike Stump1eb44332009-09-09 15:08:12 +00009362 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009363 // (C++ [over.call]p1).
9364 if (Op != OO_Call) {
9365 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9366 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009367 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009368 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009369 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009370 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009371 }
9372 }
9373
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009374 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9375 { false, false, false }
9376#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9377 , { Unary, Binary, MemberOnly }
9378#include "clang/Basic/OperatorKinds.def"
9379 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009380
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009381 bool CanBeUnaryOperator = OperatorUses[Op][0];
9382 bool CanBeBinaryOperator = OperatorUses[Op][1];
9383 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009384
9385 // C++ [over.oper]p8:
9386 // [...] Operator functions cannot have more or fewer parameters
9387 // than the number required for the corresponding operator, as
9388 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009389 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009390 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009391 if (Op != OO_Call &&
9392 ((NumParams == 1 && !CanBeUnaryOperator) ||
9393 (NumParams == 2 && !CanBeBinaryOperator) ||
9394 (NumParams < 1) || (NumParams > 2))) {
9395 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009396 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009397 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009398 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009399 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009400 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009401 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009402 assert(CanBeBinaryOperator &&
9403 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009404 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009405 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009406
Chris Lattner416e46f2008-11-21 07:57:12 +00009407 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009408 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009409 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009410
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009411 // Overloaded operators other than operator() cannot be variadic.
9412 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009413 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009414 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009415 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009416 }
9417
9418 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009419 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9420 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009421 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009422 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009423 }
9424
9425 // C++ [over.inc]p1:
9426 // The user-defined function called operator++ implements the
9427 // prefix and postfix ++ operator. If this function is a member
9428 // function with no parameters, or a non-member function with one
9429 // parameter of class or enumeration type, it defines the prefix
9430 // increment operator ++ for objects of that type. If the function
9431 // is a member function with one parameter (which shall be of type
9432 // int) or a non-member function with two parameters (the second
9433 // of which shall be of type int), it defines the postfix
9434 // increment operator ++ for objects of that type.
9435 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9436 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9437 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009438 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009439 ParamIsInt = BT->getKind() == BuiltinType::Int;
9440
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009441 if (!ParamIsInt)
9442 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009443 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009444 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009445 }
9446
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009447 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009448}
Chris Lattner5a003a42008-12-17 07:09:26 +00009449
Sean Hunta6c058d2010-01-13 09:01:02 +00009450/// CheckLiteralOperatorDeclaration - Check whether the declaration
9451/// of this literal operator function is well-formed. If so, returns
9452/// false; otherwise, emits appropriate diagnostics and returns true.
9453bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009454 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009455 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9456 << FnDecl->getDeclName();
9457 return true;
9458 }
9459
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009460 if (FnDecl->isExternC()) {
9461 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9462 return true;
9463 }
9464
Sean Hunta6c058d2010-01-13 09:01:02 +00009465 bool Valid = false;
9466
Richard Smith36f5cfe2012-03-09 08:00:36 +00009467 // This might be the definition of a literal operator template.
9468 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9469 // This might be a specialization of a literal operator template.
9470 if (!TpDecl)
9471 TpDecl = FnDecl->getPrimaryTemplate();
9472
Sean Hunt216c2782010-04-07 23:11:06 +00009473 // template <char...> type operator "" name() is the only valid template
9474 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009475 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009476 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009477 // Must have only one template parameter
9478 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9479 if (Params->size() == 1) {
9480 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009481 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009482
Sean Hunt216c2782010-04-07 23:11:06 +00009483 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009484 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9485 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9486 Valid = true;
9487 }
9488 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009489 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009490 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009491 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9492
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009493 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009494
Sean Hunt30019c02010-04-07 22:57:35 +00009495 // unsigned long long int, long double, and any character type are allowed
9496 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009497 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9498 Context.hasSameType(T, Context.LongDoubleTy) ||
9499 Context.hasSameType(T, Context.CharTy) ||
9500 Context.hasSameType(T, Context.WCharTy) ||
9501 Context.hasSameType(T, Context.Char16Ty) ||
9502 Context.hasSameType(T, Context.Char32Ty)) {
9503 if (++Param == FnDecl->param_end())
9504 Valid = true;
9505 goto FinishedParams;
9506 }
9507
Sean Hunt30019c02010-04-07 22:57:35 +00009508 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009509 const PointerType *PT = T->getAs<PointerType>();
9510 if (!PT)
9511 goto FinishedParams;
9512 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009513 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009514 goto FinishedParams;
9515 T = T.getUnqualifiedType();
9516
9517 // Move on to the second parameter;
9518 ++Param;
9519
9520 // If there is no second parameter, the first must be a const char *
9521 if (Param == FnDecl->param_end()) {
9522 if (Context.hasSameType(T, Context.CharTy))
9523 Valid = true;
9524 goto FinishedParams;
9525 }
9526
9527 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9528 // are allowed as the first parameter to a two-parameter function
9529 if (!(Context.hasSameType(T, Context.CharTy) ||
9530 Context.hasSameType(T, Context.WCharTy) ||
9531 Context.hasSameType(T, Context.Char16Ty) ||
9532 Context.hasSameType(T, Context.Char32Ty)))
9533 goto FinishedParams;
9534
9535 // The second and final parameter must be an std::size_t
9536 T = (*Param)->getType().getUnqualifiedType();
9537 if (Context.hasSameType(T, Context.getSizeType()) &&
9538 ++Param == FnDecl->param_end())
9539 Valid = true;
9540 }
9541
9542 // FIXME: This diagnostic is absolutely terrible.
9543FinishedParams:
9544 if (!Valid) {
9545 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9546 << FnDecl->getDeclName();
9547 return true;
9548 }
9549
Richard Smitha9e88b22012-03-09 08:16:22 +00009550 // A parameter-declaration-clause containing a default argument is not
9551 // equivalent to any of the permitted forms.
9552 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9553 ParamEnd = FnDecl->param_end();
9554 Param != ParamEnd; ++Param) {
9555 if ((*Param)->hasDefaultArg()) {
9556 Diag((*Param)->getDefaultArgRange().getBegin(),
9557 diag::err_literal_operator_default_argument)
9558 << (*Param)->getDefaultArgRange();
9559 break;
9560 }
9561 }
9562
Richard Smith2fb4ae32012-03-08 02:39:21 +00009563 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009564 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9565 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009566 // C++11 [usrlit.suffix]p1:
9567 // Literal suffix identifiers that do not start with an underscore
9568 // are reserved for future standardization.
9569 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009570 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009571
Sean Hunta6c058d2010-01-13 09:01:02 +00009572 return false;
9573}
9574
Douglas Gregor074149e2009-01-05 19:45:36 +00009575/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9576/// linkage specification, including the language and (if present)
9577/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9578/// the location of the language string literal, which is provided
9579/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9580/// the '{' brace. Otherwise, this linkage specification does not
9581/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009582Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9583 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009584 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009585 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009586 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009587 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009588 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009589 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009590 Language = LinkageSpecDecl::lang_cxx;
9591 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009592 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009593 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009594 }
Mike Stump1eb44332009-09-09 15:08:12 +00009595
Chris Lattnercc98eac2008-12-17 07:13:27 +00009596 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009597
Douglas Gregor074149e2009-01-05 19:45:36 +00009598 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009599 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009600 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009601 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009602 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009603}
9604
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009605/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009606/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9607/// valid, it's the position of the closing '}' brace in a linkage
9608/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009609Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009610 Decl *LinkageSpec,
9611 SourceLocation RBraceLoc) {
9612 if (LinkageSpec) {
9613 if (RBraceLoc.isValid()) {
9614 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9615 LSDecl->setRBraceLoc(RBraceLoc);
9616 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009617 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009618 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009619 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009620}
9621
Douglas Gregord308e622009-05-18 20:51:54 +00009622/// \brief Perform semantic analysis for the variable declaration that
9623/// occurs within a C++ catch clause, returning the newly-created
9624/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009625VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009626 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009627 SourceLocation StartLoc,
9628 SourceLocation Loc,
9629 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009630 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009631 QualType ExDeclType = TInfo->getType();
9632
Sebastian Redl4b07b292008-12-22 19:15:10 +00009633 // Arrays and functions decay.
9634 if (ExDeclType->isArrayType())
9635 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9636 else if (ExDeclType->isFunctionType())
9637 ExDeclType = Context.getPointerType(ExDeclType);
9638
9639 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9640 // The exception-declaration shall not denote a pointer or reference to an
9641 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009642 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009643 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009644 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009645 Invalid = true;
9646 }
Douglas Gregord308e622009-05-18 20:51:54 +00009647
Sebastian Redl4b07b292008-12-22 19:15:10 +00009648 QualType BaseType = ExDeclType;
9649 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009650 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009651 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009652 BaseType = Ptr->getPointeeType();
9653 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009654 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009655 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009656 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009657 BaseType = Ref->getPointeeType();
9658 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009659 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009660 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009661 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009662 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009663 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009664
Mike Stump1eb44332009-09-09 15:08:12 +00009665 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009666 RequireNonAbstractType(Loc, ExDeclType,
9667 diag::err_abstract_type_in_decl,
9668 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009669 Invalid = true;
9670
John McCall5a180392010-07-24 00:37:23 +00009671 // Only the non-fragile NeXT runtime currently supports C++ catches
9672 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009673 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009674 QualType T = ExDeclType;
9675 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9676 T = RT->getPointeeType();
9677
9678 if (T->isObjCObjectType()) {
9679 Diag(Loc, diag::err_objc_object_catch);
9680 Invalid = true;
9681 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +00009682 // FIXME: should this be a test for macosx-fragile specifically?
9683 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009684 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009685 }
9686 }
9687
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009688 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9689 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009690 ExDecl->setExceptionVariable(true);
9691
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009692 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009693 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009694 Invalid = true;
9695
Douglas Gregorc41b8782011-07-06 18:14:43 +00009696 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009697 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009698 // C++ [except.handle]p16:
9699 // The object declared in an exception-declaration or, if the
9700 // exception-declaration does not specify a name, a temporary (12.2) is
9701 // copy-initialized (8.5) from the exception object. [...]
9702 // The object is destroyed when the handler exits, after the destruction
9703 // of any automatic objects initialized within the handler.
9704 //
9705 // We just pretend to initialize the object with itself, then make sure
9706 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009707 QualType initType = ExDeclType;
9708
9709 InitializedEntity entity =
9710 InitializedEntity::InitializeVariable(ExDecl);
9711 InitializationKind initKind =
9712 InitializationKind::CreateCopy(Loc, SourceLocation());
9713
9714 Expr *opaqueValue =
9715 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9716 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9717 ExprResult result = sequence.Perform(*this, entity, initKind,
9718 MultiExprArg(&opaqueValue, 1));
9719 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009720 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009721 else {
9722 // If the constructor used was non-trivial, set this as the
9723 // "initializer".
9724 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9725 if (!construct->getConstructor()->isTrivial()) {
9726 Expr *init = MaybeCreateExprWithCleanups(construct);
9727 ExDecl->setInit(init);
9728 }
9729
9730 // And make sure it's destructable.
9731 FinalizeVarWithDestructor(ExDecl, recordType);
9732 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009733 }
9734 }
9735
Douglas Gregord308e622009-05-18 20:51:54 +00009736 if (Invalid)
9737 ExDecl->setInvalidDecl();
9738
9739 return ExDecl;
9740}
9741
9742/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9743/// handler.
John McCalld226f652010-08-21 09:40:31 +00009744Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009745 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009746 bool Invalid = D.isInvalidType();
9747
9748 // Check for unexpanded parameter packs.
9749 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9750 UPPC_ExceptionType)) {
9751 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9752 D.getIdentifierLoc());
9753 Invalid = true;
9754 }
9755
Sebastian Redl4b07b292008-12-22 19:15:10 +00009756 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009757 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009758 LookupOrdinaryName,
9759 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009760 // The scope should be freshly made just for us. There is just no way
9761 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009762 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009763 if (PrevDecl->isTemplateParameter()) {
9764 // Maybe we will complain about the shadowed template parameter.
9765 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009766 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009767 }
9768 }
9769
Chris Lattnereaaebc72009-04-25 08:06:05 +00009770 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009771 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9772 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009773 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009774 }
9775
Douglas Gregor83cb9422010-09-09 17:09:21 +00009776 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009777 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009778 D.getIdentifierLoc(),
9779 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009780 if (Invalid)
9781 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009782
Sebastian Redl4b07b292008-12-22 19:15:10 +00009783 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009784 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009785 PushOnScopeChains(ExDecl, S);
9786 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009787 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009788
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009789 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009790 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009791}
Anders Carlssonfb311762009-03-14 00:25:26 +00009792
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009793Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009794 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +00009795 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009796 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +00009797 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +00009798
Richard Smithe3f470a2012-07-11 22:37:56 +00009799 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9800 return 0;
9801
9802 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
9803 AssertMessage, RParenLoc, false);
9804}
9805
9806Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9807 Expr *AssertExpr,
9808 StringLiteral *AssertMessage,
9809 SourceLocation RParenLoc,
9810 bool Failed) {
9811 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
9812 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +00009813 // In a static_assert-declaration, the constant-expression shall be a
9814 // constant expression that can be contextually converted to bool.
9815 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9816 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +00009817 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +00009818
Richard Smithdaaefc52011-12-14 23:32:26 +00009819 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +00009820 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009821 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +00009822 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +00009823 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +00009824
Richard Smithe3f470a2012-07-11 22:37:56 +00009825 if (!Failed && !Cond) {
Richard Smith0cc323c2012-03-05 23:20:05 +00009826 llvm::SmallString<256> MsgBuffer;
9827 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +00009828 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009829 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009830 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +00009831 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +00009832 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009833 }
Mike Stump1eb44332009-09-09 15:08:12 +00009834
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009835 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +00009836 AssertExpr, AssertMessage, RParenLoc,
9837 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +00009838
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009839 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009840 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009841}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009842
Douglas Gregor1d869352010-04-07 16:53:43 +00009843/// \brief Perform semantic analysis of the given friend type declaration.
9844///
9845/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009846FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9847 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009848 TypeSourceInfo *TSInfo) {
9849 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9850
9851 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009852 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009853
Richard Smith6b130222011-10-18 21:39:00 +00009854 // C++03 [class.friend]p2:
9855 // An elaborated-type-specifier shall be used in a friend declaration
9856 // for a class.*
9857 //
9858 // * The class-key of the elaborated-type-specifier is required.
9859 if (!ActiveTemplateInstantiations.empty()) {
9860 // Do not complain about the form of friend template types during
9861 // template instantiation; we will already have complained when the
9862 // template was declared.
9863 } else if (!T->isElaboratedTypeSpecifier()) {
9864 // If we evaluated the type to a record type, suggest putting
9865 // a tag in front.
9866 if (const RecordType *RT = T->getAs<RecordType>()) {
9867 RecordDecl *RD = RT->getDecl();
9868
9869 std::string InsertionText = std::string(" ") + RD->getKindName();
9870
9871 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009872 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009873 diag::warn_cxx98_compat_unelaborated_friend_type :
9874 diag::ext_unelaborated_friend_type)
9875 << (unsigned) RD->getTagKind()
9876 << T
9877 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9878 InsertionText);
9879 } else {
9880 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009881 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009882 diag::warn_cxx98_compat_nonclass_type_friend :
9883 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009884 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009885 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009886 }
Richard Smith6b130222011-10-18 21:39:00 +00009887 } else if (T->getAs<EnumType>()) {
9888 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009889 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009890 diag::warn_cxx98_compat_enum_friend :
9891 diag::ext_enum_friend)
9892 << T
9893 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009894 }
9895
Douglas Gregor06245bf2010-04-07 17:57:12 +00009896 // C++0x [class.friend]p3:
9897 // If the type specifier in a friend declaration designates a (possibly
9898 // cv-qualified) class type, that class is declared as a friend; otherwise,
9899 // the friend declaration is ignored.
9900
9901 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9902 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009903
Abramo Bagnara0216df82011-10-29 20:52:52 +00009904 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009905}
9906
John McCall9a34edb2010-10-19 01:40:49 +00009907/// Handle a friend tag declaration where the scope specifier was
9908/// templated.
9909Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9910 unsigned TagSpec, SourceLocation TagLoc,
9911 CXXScopeSpec &SS,
9912 IdentifierInfo *Name, SourceLocation NameLoc,
9913 AttributeList *Attr,
9914 MultiTemplateParamsArg TempParamLists) {
9915 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9916
9917 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009918 bool Invalid = false;
9919
9920 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009921 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +00009922 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +00009923 TempParamLists.size(),
9924 /*friend*/ true,
9925 isExplicitSpecialization,
9926 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009927 if (TemplateParams->size() > 0) {
9928 // This is a declaration of a class template.
9929 if (Invalid)
9930 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009931
Eric Christopher4110e132011-07-21 05:34:24 +00009932 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9933 SS, Name, NameLoc, Attr,
9934 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009935 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009936 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00009937 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009938 } else {
9939 // The "template<>" header is extraneous.
9940 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9941 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9942 isExplicitSpecialization = true;
9943 }
9944 }
9945
9946 if (Invalid) return 0;
9947
John McCall9a34edb2010-10-19 01:40:49 +00009948 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009949 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009950 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +00009951 isAllExplicitSpecializations = false;
9952 break;
9953 }
9954 }
9955
9956 // FIXME: don't ignore attributes.
9957
9958 // If it's explicit specializations all the way down, just forget
9959 // about the template header and build an appropriate non-templated
9960 // friend. TODO: for source fidelity, remember the headers.
9961 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009962 if (SS.isEmpty()) {
9963 bool Owned = false;
9964 bool IsDependent = false;
9965 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9966 Attr, AS_public,
9967 /*ModulePrivateLoc=*/SourceLocation(),
9968 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009969 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009970 /*ScopedEnumUsesClassTag=*/false,
9971 /*UnderlyingType=*/TypeResult());
9972 }
9973
Douglas Gregor2494dd02011-03-01 01:34:45 +00009974 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009975 ElaboratedTypeKeyword Keyword
9976 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009977 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009978 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009979 if (T.isNull())
9980 return 0;
9981
9982 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9983 if (isa<DependentNameType>(T)) {
9984 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009985 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009986 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009987 TL.setNameLoc(NameLoc);
9988 } else {
9989 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009990 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009991 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009992 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9993 }
9994
9995 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9996 TSI, FriendLoc);
9997 Friend->setAccess(AS_public);
9998 CurContext->addDecl(Friend);
9999 return Friend;
10000 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010001
10002 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10003
10004
John McCall9a34edb2010-10-19 01:40:49 +000010005
10006 // Handle the case of a templated-scope friend class. e.g.
10007 // template <class T> class A<T>::B;
10008 // FIXME: we don't support these right now.
10009 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10010 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10011 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10012 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010013 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010014 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010015 TL.setNameLoc(NameLoc);
10016
10017 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10018 TSI, FriendLoc);
10019 Friend->setAccess(AS_public);
10020 Friend->setUnsupportedFriend(true);
10021 CurContext->addDecl(Friend);
10022 return Friend;
10023}
10024
10025
John McCalldd4a3b02009-09-16 22:47:08 +000010026/// Handle a friend type declaration. This works in tandem with
10027/// ActOnTag.
10028///
10029/// Notes on friend class templates:
10030///
10031/// We generally treat friend class declarations as if they were
10032/// declaring a class. So, for example, the elaborated type specifier
10033/// in a friend declaration is required to obey the restrictions of a
10034/// class-head (i.e. no typedefs in the scope chain), template
10035/// parameters are required to match up with simple template-ids, &c.
10036/// However, unlike when declaring a template specialization, it's
10037/// okay to refer to a template specialization without an empty
10038/// template parameter declaration, e.g.
10039/// friend class A<T>::B<unsigned>;
10040/// We permit this as a special case; if there are any template
10041/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010042/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010043Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010044 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010045 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010046
10047 assert(DS.isFriendSpecified());
10048 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10049
John McCalldd4a3b02009-09-16 22:47:08 +000010050 // Try to convert the decl specifier to a type. This works for
10051 // friend templates because ActOnTag never produces a ClassTemplateDecl
10052 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010053 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010054 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10055 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010056 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010057 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010058
Douglas Gregor6ccab972010-12-16 01:14:37 +000010059 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10060 return 0;
10061
John McCalldd4a3b02009-09-16 22:47:08 +000010062 // This is definitely an error in C++98. It's probably meant to
10063 // be forbidden in C++0x, too, but the specification is just
10064 // poorly written.
10065 //
10066 // The problem is with declarations like the following:
10067 // template <T> friend A<T>::foo;
10068 // where deciding whether a class C is a friend or not now hinges
10069 // on whether there exists an instantiation of A that causes
10070 // 'foo' to equal C. There are restrictions on class-heads
10071 // (which we declare (by fiat) elaborated friend declarations to
10072 // be) that makes this tractable.
10073 //
10074 // FIXME: handle "template <> friend class A<T>;", which
10075 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010076 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010077 Diag(Loc, diag::err_tagless_friend_type_template)
10078 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010079 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010080 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010081
John McCall02cace72009-08-28 07:59:38 +000010082 // C++98 [class.friend]p1: A friend of a class is a function
10083 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010084 // This is fixed in DR77, which just barely didn't make the C++03
10085 // deadline. It's also a very silly restriction that seriously
10086 // affects inner classes and which nobody else seems to implement;
10087 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010088 //
10089 // But note that we could warn about it: it's always useless to
10090 // friend one of your own members (it's not, however, worthless to
10091 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010092
John McCalldd4a3b02009-09-16 22:47:08 +000010093 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010094 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010095 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010096 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010097 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010098 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010099 DS.getFriendSpecLoc());
10100 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010101 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010102
10103 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010104 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010105
John McCalldd4a3b02009-09-16 22:47:08 +000010106 D->setAccess(AS_public);
10107 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010108
John McCalld226f652010-08-21 09:40:31 +000010109 return D;
John McCall02cace72009-08-28 07:59:38 +000010110}
10111
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010112Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010113 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010114 const DeclSpec &DS = D.getDeclSpec();
10115
10116 assert(DS.isFriendSpecified());
10117 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10118
10119 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010120 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010121
10122 // C++ [class.friend]p1
10123 // A friend of a class is a function or class....
10124 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010125 // It *doesn't* see through dependent types, which is correct
10126 // according to [temp.arg.type]p3:
10127 // If a declaration acquires a function type through a
10128 // type dependent on a template-parameter and this causes
10129 // a declaration that does not use the syntactic form of a
10130 // function declarator to have a function type, the program
10131 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010132 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010133 Diag(Loc, diag::err_unexpected_friend);
10134
10135 // It might be worthwhile to try to recover by creating an
10136 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010137 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010138 }
10139
10140 // C++ [namespace.memdef]p3
10141 // - If a friend declaration in a non-local class first declares a
10142 // class or function, the friend class or function is a member
10143 // of the innermost enclosing namespace.
10144 // - The name of the friend is not found by simple name lookup
10145 // until a matching declaration is provided in that namespace
10146 // scope (either before or after the class declaration granting
10147 // friendship).
10148 // - If a friend function is called, its name may be found by the
10149 // name lookup that considers functions from namespaces and
10150 // classes associated with the types of the function arguments.
10151 // - When looking for a prior declaration of a class or a function
10152 // declared as a friend, scopes outside the innermost enclosing
10153 // namespace scope are not considered.
10154
John McCall337ec3d2010-10-12 23:13:28 +000010155 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010156 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10157 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010158 assert(Name);
10159
Douglas Gregor6ccab972010-12-16 01:14:37 +000010160 // Check for unexpanded parameter packs.
10161 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10162 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10163 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10164 return 0;
10165
John McCall67d1a672009-08-06 02:15:43 +000010166 // The context we found the declaration in, or in which we should
10167 // create the declaration.
10168 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010169 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010170 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010171 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010172
John McCall337ec3d2010-10-12 23:13:28 +000010173 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010174
John McCall337ec3d2010-10-12 23:13:28 +000010175 // There are four cases here.
10176 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010177 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010178 // there as appropriate.
10179 // Recover from invalid scope qualifiers as if they just weren't there.
10180 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010181 // C++0x [namespace.memdef]p3:
10182 // If the name in a friend declaration is neither qualified nor
10183 // a template-id and the declaration is a function or an
10184 // elaborated-type-specifier, the lookup to determine whether
10185 // the entity has been previously declared shall not consider
10186 // any scopes outside the innermost enclosing namespace.
10187 // C++0x [class.friend]p11:
10188 // If a friend declaration appears in a local class and the name
10189 // specified is an unqualified name, a prior declaration is
10190 // looked up without considering scopes that are outside the
10191 // innermost enclosing non-class scope. For a friend function
10192 // declaration, if there is no prior declaration, the program is
10193 // ill-formed.
10194 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010195 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010196
John McCall29ae6e52010-10-13 05:45:15 +000010197 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010198 DC = CurContext;
10199 while (true) {
10200 // Skip class contexts. If someone can cite chapter and verse
10201 // for this behavior, that would be nice --- it's what GCC and
10202 // EDG do, and it seems like a reasonable intent, but the spec
10203 // really only says that checks for unqualified existing
10204 // declarations should stop at the nearest enclosing namespace,
10205 // not that they should only consider the nearest enclosing
10206 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010207 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010208 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010209
John McCall68263142009-11-18 22:49:29 +000010210 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010211
10212 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010213 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010214 break;
John McCall29ae6e52010-10-13 05:45:15 +000010215
John McCall8a407372010-10-14 22:22:28 +000010216 if (isTemplateId) {
10217 if (isa<TranslationUnitDecl>(DC)) break;
10218 } else {
10219 if (DC->isFileContext()) break;
10220 }
John McCall67d1a672009-08-06 02:15:43 +000010221 DC = DC->getParent();
10222 }
10223
10224 // C++ [class.friend]p1: A friend of a class is a function or
10225 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010226 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010227 // Most C++ 98 compilers do seem to give an error here, so
10228 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010229 if (!Previous.empty() && DC->Equals(CurContext))
10230 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010231 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010232 diag::warn_cxx98_compat_friend_is_member :
10233 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010234
John McCall380aaa42010-10-13 06:22:15 +000010235 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010236
Douglas Gregor883af832011-10-10 01:11:59 +000010237 // C++ [class.friend]p6:
10238 // A function can be defined in a friend declaration of a class if and
10239 // only if the class is a non-local class (9.8), the function name is
10240 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010241 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010242 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10243 }
10244
John McCall337ec3d2010-10-12 23:13:28 +000010245 // - There's a non-dependent scope specifier, in which case we
10246 // compute it and do a previous lookup there for a function
10247 // or function template.
10248 } else if (!SS.getScopeRep()->isDependent()) {
10249 DC = computeDeclContext(SS);
10250 if (!DC) return 0;
10251
10252 if (RequireCompleteDeclContext(SS, DC)) return 0;
10253
10254 LookupQualifiedName(Previous, DC);
10255
10256 // Ignore things found implicitly in the wrong scope.
10257 // TODO: better diagnostics for this case. Suggesting the right
10258 // qualified scope would be nice...
10259 LookupResult::Filter F = Previous.makeFilter();
10260 while (F.hasNext()) {
10261 NamedDecl *D = F.next();
10262 if (!DC->InEnclosingNamespaceSetOf(
10263 D->getDeclContext()->getRedeclContext()))
10264 F.erase();
10265 }
10266 F.done();
10267
10268 if (Previous.empty()) {
10269 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010270 Diag(Loc, diag::err_qualified_friend_not_found)
10271 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010272 return 0;
10273 }
10274
10275 // C++ [class.friend]p1: A friend of a class is a function or
10276 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010277 if (DC->Equals(CurContext))
10278 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010279 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010280 diag::warn_cxx98_compat_friend_is_member :
10281 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010282
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010283 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010284 // C++ [class.friend]p6:
10285 // A function can be defined in a friend declaration of a class if and
10286 // only if the class is a non-local class (9.8), the function name is
10287 // unqualified, and the function has namespace scope.
10288 SemaDiagnosticBuilder DB
10289 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10290
10291 DB << SS.getScopeRep();
10292 if (DC->isFileContext())
10293 DB << FixItHint::CreateRemoval(SS.getRange());
10294 SS.clear();
10295 }
John McCall337ec3d2010-10-12 23:13:28 +000010296
10297 // - There's a scope specifier that does not match any template
10298 // parameter lists, in which case we use some arbitrary context,
10299 // create a method or method template, and wait for instantiation.
10300 // - There's a scope specifier that does match some template
10301 // parameter lists, which we don't handle right now.
10302 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010303 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010304 // C++ [class.friend]p6:
10305 // A function can be defined in a friend declaration of a class if and
10306 // only if the class is a non-local class (9.8), the function name is
10307 // unqualified, and the function has namespace scope.
10308 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10309 << SS.getScopeRep();
10310 }
10311
John McCall337ec3d2010-10-12 23:13:28 +000010312 DC = CurContext;
10313 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010314 }
Douglas Gregor883af832011-10-10 01:11:59 +000010315
John McCall29ae6e52010-10-13 05:45:15 +000010316 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010317 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010318 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10319 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10320 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010321 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010322 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10323 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010324 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010325 }
John McCall67d1a672009-08-06 02:15:43 +000010326 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010327
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010328 // FIXME: This is an egregious hack to cope with cases where the scope stack
10329 // does not contain the declaration context, i.e., in an out-of-line
10330 // definition of a class.
10331 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10332 if (!DCScope) {
10333 FakeDCScope.setEntity(DC);
10334 DCScope = &FakeDCScope;
10335 }
10336
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010337 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010338 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010339 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010340 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010341
Douglas Gregor182ddf02009-09-28 00:08:27 +000010342 assert(ND->getDeclContext() == DC);
10343 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010344
John McCallab88d972009-08-31 22:39:49 +000010345 // Add the function declaration to the appropriate lookup tables,
10346 // adjusting the redeclarations list as necessary. We don't
10347 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010348 //
John McCallab88d972009-08-31 22:39:49 +000010349 // Also update the scope-based lookup if the target context's
10350 // lookup context is in lexical scope.
10351 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010352 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010353 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010354 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010355 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010356 }
John McCall02cace72009-08-28 07:59:38 +000010357
10358 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010359 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010360 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010361 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010362 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010363
John McCall1f2e1a92012-08-10 03:15:35 +000010364 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010365 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010366 } else {
10367 if (DC->isRecord()) CheckFriendAccess(ND);
10368
John McCall6102ca12010-10-16 06:59:13 +000010369 FunctionDecl *FD;
10370 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10371 FD = FTD->getTemplatedDecl();
10372 else
10373 FD = cast<FunctionDecl>(ND);
10374
10375 // Mark templated-scope function declarations as unsupported.
10376 if (FD->getNumTemplateParameterLists())
10377 FrD->setUnsupportedFriend(true);
10378 }
John McCall337ec3d2010-10-12 23:13:28 +000010379
John McCalld226f652010-08-21 09:40:31 +000010380 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010381}
10382
John McCalld226f652010-08-21 09:40:31 +000010383void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10384 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010385
Sebastian Redl50de12f2009-03-24 22:27:57 +000010386 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10387 if (!Fn) {
10388 Diag(DelLoc, diag::err_deleted_non_function);
10389 return;
10390 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010391 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010392 // Don't consider the implicit declaration we generate for explicit
10393 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010394 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10395 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010396 Diag(DelLoc, diag::err_deleted_decl_not_first);
10397 Diag(Prev->getLocation(), diag::note_previous_declaration);
10398 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010399 // If the declaration wasn't the first, we delete the function anyway for
10400 // recovery.
10401 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010402 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010403
10404 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10405 if (!MD)
10406 return;
10407
10408 // A deleted special member function is trivial if the corresponding
10409 // implicitly-declared function would have been.
10410 switch (getSpecialMember(MD)) {
10411 case CXXInvalid:
10412 break;
10413 case CXXDefaultConstructor:
10414 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10415 break;
10416 case CXXCopyConstructor:
10417 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10418 break;
10419 case CXXMoveConstructor:
10420 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10421 break;
10422 case CXXCopyAssignment:
10423 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10424 break;
10425 case CXXMoveAssignment:
10426 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10427 break;
10428 case CXXDestructor:
10429 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10430 break;
10431 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010432}
Sebastian Redl13e88542009-04-27 21:33:24 +000010433
Sean Hunte4246a62011-05-12 06:15:49 +000010434void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10435 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10436
10437 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010438 if (MD->getParent()->isDependentType()) {
10439 MD->setDefaulted();
10440 MD->setExplicitlyDefaulted();
10441 return;
10442 }
10443
Sean Hunte4246a62011-05-12 06:15:49 +000010444 CXXSpecialMember Member = getSpecialMember(MD);
10445 if (Member == CXXInvalid) {
10446 Diag(DefaultLoc, diag::err_default_special_members);
10447 return;
10448 }
10449
10450 MD->setDefaulted();
10451 MD->setExplicitlyDefaulted();
10452
Sean Huntcd10dec2011-05-23 23:14:04 +000010453 // If this definition appears within the record, do the checking when
10454 // the record is complete.
10455 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010456 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010457 // Find the uninstantiated declaration that actually had the '= default'
10458 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010459 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010460
10461 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010462 return;
10463
Richard Smithb9d0b762012-07-27 04:22:15 +000010464 CheckExplicitlyDefaultedSpecialMember(MD);
10465
Sean Hunte4246a62011-05-12 06:15:49 +000010466 switch (Member) {
10467 case CXXDefaultConstructor: {
10468 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010469 if (!CD->isInvalidDecl())
10470 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10471 break;
10472 }
10473
10474 case CXXCopyConstructor: {
10475 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010476 if (!CD->isInvalidDecl())
10477 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010478 break;
10479 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010480
Sean Hunt2b188082011-05-14 05:23:28 +000010481 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010482 if (!MD->isInvalidDecl())
10483 DefineImplicitCopyAssignment(DefaultLoc, MD);
10484 break;
10485 }
10486
Sean Huntcb45a0f2011-05-12 22:46:25 +000010487 case CXXDestructor: {
10488 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010489 if (!DD->isInvalidDecl())
10490 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010491 break;
10492 }
10493
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010494 case CXXMoveConstructor: {
10495 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010496 if (!CD->isInvalidDecl())
10497 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010498 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010499 }
Sean Hunt82713172011-05-25 23:16:36 +000010500
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010501 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010502 if (!MD->isInvalidDecl())
10503 DefineImplicitMoveAssignment(DefaultLoc, MD);
10504 break;
10505 }
10506
10507 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010508 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010509 }
10510 } else {
10511 Diag(DefaultLoc, diag::err_default_special_members);
10512 }
10513}
10514
Sebastian Redl13e88542009-04-27 21:33:24 +000010515static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010516 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010517 Stmt *SubStmt = *CI;
10518 if (!SubStmt)
10519 continue;
10520 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010521 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010522 diag::err_return_in_constructor_handler);
10523 if (!isa<Expr>(SubStmt))
10524 SearchForReturnInStmt(Self, SubStmt);
10525 }
10526}
10527
10528void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10529 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10530 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10531 SearchForReturnInStmt(*this, Handler);
10532 }
10533}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010534
Mike Stump1eb44332009-09-09 15:08:12 +000010535bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010536 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010537 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10538 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010539
Chandler Carruth73857792010-02-15 11:53:20 +000010540 if (Context.hasSameType(NewTy, OldTy) ||
10541 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010542 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010543
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010544 // Check if the return types are covariant
10545 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010546
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010547 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010548 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10549 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010550 NewClassTy = NewPT->getPointeeType();
10551 OldClassTy = OldPT->getPointeeType();
10552 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010553 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10554 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10555 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10556 NewClassTy = NewRT->getPointeeType();
10557 OldClassTy = OldRT->getPointeeType();
10558 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010559 }
10560 }
Mike Stump1eb44332009-09-09 15:08:12 +000010561
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010562 // The return types aren't either both pointers or references to a class type.
10563 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010564 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010565 diag::err_different_return_type_for_overriding_virtual_function)
10566 << New->getDeclName() << NewTy << OldTy;
10567 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010568
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010569 return true;
10570 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010571
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010572 // C++ [class.virtual]p6:
10573 // If the return type of D::f differs from the return type of B::f, the
10574 // class type in the return type of D::f shall be complete at the point of
10575 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010576 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10577 if (!RT->isBeingDefined() &&
10578 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010579 diag::err_covariant_return_incomplete,
10580 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010581 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010582 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010583
Douglas Gregora4923eb2009-11-16 21:35:15 +000010584 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010585 // Check if the new class derives from the old class.
10586 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10587 Diag(New->getLocation(),
10588 diag::err_covariant_return_not_derived)
10589 << New->getDeclName() << NewTy << OldTy;
10590 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10591 return true;
10592 }
Mike Stump1eb44332009-09-09 15:08:12 +000010593
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010594 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010595 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010596 diag::err_covariant_return_inaccessible_base,
10597 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10598 // FIXME: Should this point to the return type?
10599 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010600 // FIXME: this note won't trigger for delayed access control
10601 // diagnostics, and it's impossible to get an undelayed error
10602 // here from access control during the original parse because
10603 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010604 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10605 return true;
10606 }
10607 }
Mike Stump1eb44332009-09-09 15:08:12 +000010608
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010609 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010610 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010611 Diag(New->getLocation(),
10612 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010613 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010614 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10615 return true;
10616 };
Mike Stump1eb44332009-09-09 15:08:12 +000010617
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010618
10619 // The new class type must have the same or less qualifiers as the old type.
10620 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10621 Diag(New->getLocation(),
10622 diag::err_covariant_return_type_class_type_more_qualified)
10623 << New->getDeclName() << NewTy << OldTy;
10624 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10625 return true;
10626 };
Mike Stump1eb44332009-09-09 15:08:12 +000010627
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010628 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010629}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010630
Douglas Gregor4ba31362009-12-01 17:24:26 +000010631/// \brief Mark the given method pure.
10632///
10633/// \param Method the method to be marked pure.
10634///
10635/// \param InitRange the source range that covers the "0" initializer.
10636bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010637 SourceLocation EndLoc = InitRange.getEnd();
10638 if (EndLoc.isValid())
10639 Method->setRangeEnd(EndLoc);
10640
Douglas Gregor4ba31362009-12-01 17:24:26 +000010641 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10642 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010643 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010644 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010645
10646 if (!Method->isInvalidDecl())
10647 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10648 << Method->getDeclName() << InitRange;
10649 return true;
10650}
10651
Douglas Gregor552e2992012-02-21 02:22:07 +000010652/// \brief Determine whether the given declaration is a static data member.
10653static bool isStaticDataMember(Decl *D) {
10654 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10655 if (!Var)
10656 return false;
10657
10658 return Var->isStaticDataMember();
10659}
John McCall731ad842009-12-19 09:28:58 +000010660/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10661/// an initializer for the out-of-line declaration 'Dcl'. The scope
10662/// is a fresh scope pushed for just this purpose.
10663///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010664/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10665/// static data member of class X, names should be looked up in the scope of
10666/// class X.
John McCalld226f652010-08-21 09:40:31 +000010667void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010668 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010669 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010670
John McCall731ad842009-12-19 09:28:58 +000010671 // We should only get called for declarations with scope specifiers, like:
10672 // int foo::bar;
10673 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010674 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010675
10676 // If we are parsing the initializer for a static data member, push a
10677 // new expression evaluation context that is associated with this static
10678 // data member.
10679 if (isStaticDataMember(D))
10680 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010681}
10682
10683/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010684/// initializer for the out-of-line declaration 'D'.
10685void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010686 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010687 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010688
Douglas Gregor552e2992012-02-21 02:22:07 +000010689 if (isStaticDataMember(D))
10690 PopExpressionEvaluationContext();
10691
John McCall731ad842009-12-19 09:28:58 +000010692 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010693 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010694}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010695
10696/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10697/// C++ if/switch/while/for statement.
10698/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010699DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010700 // C++ 6.4p2:
10701 // The declarator shall not specify a function or an array.
10702 // The type-specifier-seq shall not contain typedef and shall not declare a
10703 // new class or enumeration.
10704 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10705 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010706
10707 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010708 if (!Dcl)
10709 return true;
10710
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010711 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10712 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010713 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010714 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010715 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010716
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010717 return Dcl;
10718}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010719
Douglas Gregordfe65432011-07-28 19:11:31 +000010720void Sema::LoadExternalVTableUses() {
10721 if (!ExternalSource)
10722 return;
10723
10724 SmallVector<ExternalVTableUse, 4> VTables;
10725 ExternalSource->ReadUsedVTables(VTables);
10726 SmallVector<VTableUse, 4> NewUses;
10727 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10728 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10729 = VTablesUsed.find(VTables[I].Record);
10730 // Even if a definition wasn't required before, it may be required now.
10731 if (Pos != VTablesUsed.end()) {
10732 if (!Pos->second && VTables[I].DefinitionRequired)
10733 Pos->second = true;
10734 continue;
10735 }
10736
10737 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10738 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10739 }
10740
10741 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10742}
10743
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010744void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10745 bool DefinitionRequired) {
10746 // Ignore any vtable uses in unevaluated operands or for classes that do
10747 // not have a vtable.
10748 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10749 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010750 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010751 return;
10752
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010753 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010754 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010755 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10756 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10757 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10758 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010759 // If we already had an entry, check to see if we are promoting this vtable
10760 // to required a definition. If so, we need to reappend to the VTableUses
10761 // list, since we may have already processed the first entry.
10762 if (DefinitionRequired && !Pos.first->second) {
10763 Pos.first->second = true;
10764 } else {
10765 // Otherwise, we can early exit.
10766 return;
10767 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010768 }
10769
10770 // Local classes need to have their virtual members marked
10771 // immediately. For all other classes, we mark their virtual members
10772 // at the end of the translation unit.
10773 if (Class->isLocalClass())
10774 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010775 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010776 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010777}
10778
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010779bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010780 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010781 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010782 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010783
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010784 // Note: The VTableUses vector could grow as a result of marking
10785 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000010786 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010787 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010788 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010789 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010790 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010791 if (!Class)
10792 continue;
10793
10794 SourceLocation Loc = VTableUses[I].second;
10795
Richard Smithb9d0b762012-07-27 04:22:15 +000010796 bool DefineVTable = true;
10797
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010798 // If this class has a key function, but that key function is
10799 // defined in another translation unit, we don't need to emit the
10800 // vtable even though we're using it.
10801 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010802 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010803 switch (KeyFunction->getTemplateSpecializationKind()) {
10804 case TSK_Undeclared:
10805 case TSK_ExplicitSpecialization:
10806 case TSK_ExplicitInstantiationDeclaration:
10807 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000010808 DefineVTable = false;
10809 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010810
10811 case TSK_ExplicitInstantiationDefinition:
10812 case TSK_ImplicitInstantiation:
10813 // We will be instantiating the key function.
10814 break;
10815 }
10816 } else if (!KeyFunction) {
10817 // If we have a class with no key function that is the subject
10818 // of an explicit instantiation declaration, suppress the
10819 // vtable; it will live with the explicit instantiation
10820 // definition.
10821 bool IsExplicitInstantiationDeclaration
10822 = Class->getTemplateSpecializationKind()
10823 == TSK_ExplicitInstantiationDeclaration;
10824 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10825 REnd = Class->redecls_end();
10826 R != REnd; ++R) {
10827 TemplateSpecializationKind TSK
10828 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10829 if (TSK == TSK_ExplicitInstantiationDeclaration)
10830 IsExplicitInstantiationDeclaration = true;
10831 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10832 IsExplicitInstantiationDeclaration = false;
10833 break;
10834 }
10835 }
10836
10837 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000010838 DefineVTable = false;
10839 }
10840
10841 // The exception specifications for all virtual members may be needed even
10842 // if we are not providing an authoritative form of the vtable in this TU.
10843 // We may choose to emit it available_externally anyway.
10844 if (!DefineVTable) {
10845 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
10846 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010847 }
10848
10849 // Mark all of the virtual members of this class as referenced, so
10850 // that we can build a vtable. Then, tell the AST consumer that a
10851 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010852 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010853 MarkVirtualMembersReferenced(Loc, Class);
10854 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10855 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10856
10857 // Optionally warn if we're emitting a weak vtable.
10858 if (Class->getLinkage() == ExternalLinkage &&
10859 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010860 const FunctionDecl *KeyFunctionDef = 0;
10861 if (!KeyFunction ||
10862 (KeyFunction->hasBody(KeyFunctionDef) &&
10863 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010864 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10865 TSK_ExplicitInstantiationDefinition
10866 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10867 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010868 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010869 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010870 VTableUses.clear();
10871
Douglas Gregor78844032011-04-22 22:25:37 +000010872 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010873}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010874
Richard Smithb9d0b762012-07-27 04:22:15 +000010875void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
10876 const CXXRecordDecl *RD) {
10877 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
10878 E = RD->method_end(); I != E; ++I)
10879 if ((*I)->isVirtual() && !(*I)->isPure())
10880 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
10881}
10882
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010883void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10884 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000010885 // Mark all functions which will appear in RD's vtable as used.
10886 CXXFinalOverriderMap FinalOverriders;
10887 RD->getFinalOverriders(FinalOverriders);
10888 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
10889 E = FinalOverriders.end();
10890 I != E; ++I) {
10891 for (OverridingMethods::const_iterator OI = I->second.begin(),
10892 OE = I->second.end();
10893 OI != OE; ++OI) {
10894 assert(OI->second.size() > 0 && "no final overrider");
10895 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000010896
Richard Smithff817f72012-07-07 06:59:51 +000010897 // C++ [basic.def.odr]p2:
10898 // [...] A virtual member function is used if it is not pure. [...]
10899 if (!Overrider->isPure())
10900 MarkFunctionReferenced(Loc, Overrider);
10901 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010902 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010903
10904 // Only classes that have virtual bases need a VTT.
10905 if (RD->getNumVBases() == 0)
10906 return;
10907
10908 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10909 e = RD->bases_end(); i != e; ++i) {
10910 const CXXRecordDecl *Base =
10911 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010912 if (Base->getNumVBases() == 0)
10913 continue;
10914 MarkVirtualMembersReferenced(Loc, Base);
10915 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010916}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010917
10918/// SetIvarInitializers - This routine builds initialization ASTs for the
10919/// Objective-C implementation whose ivars need be initialized.
10920void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010921 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010922 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010923 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010924 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010925 CollectIvarsToConstructOrDestruct(OID, ivars);
10926 if (ivars.empty())
10927 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010928 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010929 for (unsigned i = 0; i < ivars.size(); i++) {
10930 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010931 if (Field->isInvalidDecl())
10932 continue;
10933
Sean Huntcbb67482011-01-08 20:30:50 +000010934 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010935 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10936 InitializationKind InitKind =
10937 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10938
10939 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010940 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010941 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010942 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010943 // Note, MemberInit could actually come back empty if no initialization
10944 // is required (e.g., because it would call a trivial default constructor)
10945 if (!MemberInit.get() || MemberInit.isInvalid())
10946 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010947
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010948 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010949 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10950 SourceLocation(),
10951 MemberInit.takeAs<Expr>(),
10952 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010953 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010954
10955 // Be sure that the destructor is accessible and is marked as referenced.
10956 if (const RecordType *RecordTy
10957 = Context.getBaseElementType(Field->getType())
10958 ->getAs<RecordType>()) {
10959 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010960 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010961 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010962 CheckDestructorAccess(Field->getLocation(), Destructor,
10963 PDiag(diag::err_access_dtor_ivar)
10964 << Context.getBaseElementType(Field->getType()));
10965 }
10966 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010967 }
10968 ObjCImplementation->setIvarInitializers(Context,
10969 AllToInit.data(), AllToInit.size());
10970 }
10971}
Sean Huntfe57eef2011-05-04 05:57:24 +000010972
Sean Huntebcbe1d2011-05-04 23:29:54 +000010973static
10974void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10975 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10976 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10977 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10978 Sema &S) {
10979 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10980 CE = Current.end();
10981 if (Ctor->isInvalidDecl())
10982 return;
10983
Richard Smitha8eaf002012-08-23 06:16:52 +000010984 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
10985
10986 // Target may not be determinable yet, for instance if this is a dependent
10987 // call in an uninstantiated template.
10988 if (Target) {
10989 const FunctionDecl *FNTarget = 0;
10990 (void)Target->hasBody(FNTarget);
10991 Target = const_cast<CXXConstructorDecl*>(
10992 cast_or_null<CXXConstructorDecl>(FNTarget));
10993 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010994
10995 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10996 // Avoid dereferencing a null pointer here.
10997 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10998
10999 if (!Current.insert(Canonical))
11000 return;
11001
11002 // We know that beyond here, we aren't chaining into a cycle.
11003 if (!Target || !Target->isDelegatingConstructor() ||
11004 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11005 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11006 Valid.insert(*CI);
11007 Current.clear();
11008 // We've hit a cycle.
11009 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11010 Current.count(TCanonical)) {
11011 // If we haven't diagnosed this cycle yet, do so now.
11012 if (!Invalid.count(TCanonical)) {
11013 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011014 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011015 << Ctor;
11016
Richard Smitha8eaf002012-08-23 06:16:52 +000011017 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011018 if (TCanonical != Canonical)
11019 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11020
11021 CXXConstructorDecl *C = Target;
11022 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011023 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011024 (void)C->getTargetConstructor()->hasBody(FNTarget);
11025 assert(FNTarget && "Ctor cycle through bodiless function");
11026
Richard Smitha8eaf002012-08-23 06:16:52 +000011027 C = const_cast<CXXConstructorDecl*>(
11028 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011029 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11030 }
11031 }
11032
11033 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11034 Invalid.insert(*CI);
11035 Current.clear();
11036 } else {
11037 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11038 }
11039}
11040
11041
Sean Huntfe57eef2011-05-04 05:57:24 +000011042void Sema::CheckDelegatingCtorCycles() {
11043 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11044
Sean Huntebcbe1d2011-05-04 23:29:54 +000011045 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11046 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011047
Douglas Gregor0129b562011-07-27 21:57:17 +000011048 for (DelegatingCtorDeclsType::iterator
11049 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011050 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011051 I != E; ++I)
11052 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011053
11054 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11055 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011056}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011057
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011058namespace {
11059 /// \brief AST visitor that finds references to the 'this' expression.
11060 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11061 Sema &S;
11062
11063 public:
11064 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11065
11066 bool VisitCXXThisExpr(CXXThisExpr *E) {
11067 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11068 << E->isImplicit();
11069 return false;
11070 }
11071 };
11072}
11073
11074bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11075 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11076 if (!TSInfo)
11077 return false;
11078
11079 TypeLoc TL = TSInfo->getTypeLoc();
11080 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11081 if (!ProtoTL)
11082 return false;
11083
11084 // C++11 [expr.prim.general]p3:
11085 // [The expression this] shall not appear before the optional
11086 // cv-qualifier-seq and it shall not appear within the declaration of a
11087 // static member function (although its type and value category are defined
11088 // within a static member function as they are within a non-static member
11089 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011090 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011091 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11092 FindCXXThisExpr Finder(*this);
11093
11094 // If the return type came after the cv-qualifier-seq, check it now.
11095 if (Proto->hasTrailingReturn() &&
11096 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11097 return true;
11098
11099 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011100 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11101 return true;
11102
11103 return checkThisInStaticMemberFunctionAttributes(Method);
11104}
11105
11106bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11107 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11108 if (!TSInfo)
11109 return false;
11110
11111 TypeLoc TL = TSInfo->getTypeLoc();
11112 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11113 if (!ProtoTL)
11114 return false;
11115
11116 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11117 FindCXXThisExpr Finder(*this);
11118
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011119 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011120 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011121 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011122 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011123 case EST_DynamicNone:
11124 case EST_MSAny:
11125 case EST_None:
11126 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011127
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011128 case EST_ComputedNoexcept:
11129 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11130 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011131
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011132 case EST_Dynamic:
11133 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011134 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011135 E != EEnd; ++E) {
11136 if (!Finder.TraverseType(*E))
11137 return true;
11138 }
11139 break;
11140 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011141
11142 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011143}
11144
11145bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11146 FindCXXThisExpr Finder(*this);
11147
11148 // Check attributes.
11149 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11150 A != AEnd; ++A) {
11151 // FIXME: This should be emitted by tblgen.
11152 Expr *Arg = 0;
11153 ArrayRef<Expr *> Args;
11154 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11155 Arg = G->getArg();
11156 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11157 Arg = G->getArg();
11158 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11159 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11160 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11161 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11162 else if (ExclusiveLockFunctionAttr *ELF
11163 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11164 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11165 else if (SharedLockFunctionAttr *SLF
11166 = dyn_cast<SharedLockFunctionAttr>(*A))
11167 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11168 else if (ExclusiveTrylockFunctionAttr *ETLF
11169 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11170 Arg = ETLF->getSuccessValue();
11171 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11172 } else if (SharedTrylockFunctionAttr *STLF
11173 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11174 Arg = STLF->getSuccessValue();
11175 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11176 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11177 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11178 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11179 Arg = LR->getArg();
11180 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11181 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11182 else if (ExclusiveLocksRequiredAttr *ELR
11183 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11184 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11185 else if (SharedLocksRequiredAttr *SLR
11186 = dyn_cast<SharedLocksRequiredAttr>(*A))
11187 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11188
11189 if (Arg && !Finder.TraverseStmt(Arg))
11190 return true;
11191
11192 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11193 if (!Finder.TraverseStmt(Args[I]))
11194 return true;
11195 }
11196 }
11197
11198 return false;
11199}
11200
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011201void
11202Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11203 ArrayRef<ParsedType> DynamicExceptions,
11204 ArrayRef<SourceRange> DynamicExceptionRanges,
11205 Expr *NoexceptExpr,
11206 llvm::SmallVectorImpl<QualType> &Exceptions,
11207 FunctionProtoType::ExtProtoInfo &EPI) {
11208 Exceptions.clear();
11209 EPI.ExceptionSpecType = EST;
11210 if (EST == EST_Dynamic) {
11211 Exceptions.reserve(DynamicExceptions.size());
11212 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11213 // FIXME: Preserve type source info.
11214 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11215
11216 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11217 collectUnexpandedParameterPacks(ET, Unexpanded);
11218 if (!Unexpanded.empty()) {
11219 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11220 UPPC_ExceptionType,
11221 Unexpanded);
11222 continue;
11223 }
11224
11225 // Check that the type is valid for an exception spec, and
11226 // drop it if not.
11227 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11228 Exceptions.push_back(ET);
11229 }
11230 EPI.NumExceptions = Exceptions.size();
11231 EPI.Exceptions = Exceptions.data();
11232 return;
11233 }
11234
11235 if (EST == EST_ComputedNoexcept) {
11236 // If an error occurred, there's no expression here.
11237 if (NoexceptExpr) {
11238 assert((NoexceptExpr->isTypeDependent() ||
11239 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11240 Context.BoolTy) &&
11241 "Parser should have made sure that the expression is boolean");
11242 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11243 EPI.ExceptionSpecType = EST_BasicNoexcept;
11244 return;
11245 }
11246
11247 if (!NoexceptExpr->isValueDependent())
11248 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011249 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011250 /*AllowFold*/ false).take();
11251 EPI.NoexceptExpr = NoexceptExpr;
11252 }
11253 return;
11254 }
11255}
11256
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011257/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11258Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11259 // Implicitly declared functions (e.g. copy constructors) are
11260 // __host__ __device__
11261 if (D->isImplicit())
11262 return CFT_HostDevice;
11263
11264 if (D->hasAttr<CUDAGlobalAttr>())
11265 return CFT_Global;
11266
11267 if (D->hasAttr<CUDADeviceAttr>()) {
11268 if (D->hasAttr<CUDAHostAttr>())
11269 return CFT_HostDevice;
11270 else
11271 return CFT_Device;
11272 }
11273
11274 return CFT_Host;
11275}
11276
11277bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11278 CUDAFunctionTarget CalleeTarget) {
11279 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11280 // Callable from the device only."
11281 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11282 return true;
11283
11284 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11285 // Callable from the host only."
11286 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11287 // Callable from the host only."
11288 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11289 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11290 return true;
11291
11292 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11293 return true;
11294
11295 return false;
11296}