blob: ee6b19eb0b341bfe343d3c24b04f74f266403058 [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 }
675 return true;
676}
677
678// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
Richard Smith86c3ae42012-02-13 03:54:03 +0000679// the requirements of a constexpr function definition or a constexpr
680// constructor definition. If so, return true. If not, produce appropriate
681// diagnostics and return false.
Richard Smith9f569cc2011-10-01 02:31:28 +0000682//
Richard Smith86c3ae42012-02-13 03:54:03 +0000683// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
684bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
Richard Smith35340502012-01-13 04:54:00 +0000685 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
686 if (MD && MD->isInstance()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000687 // C++11 [dcl.constexpr]p4:
688 // The definition of a constexpr constructor shall satisfy the following
689 // constraints:
Richard Smith9f569cc2011-10-01 02:31:28 +0000690 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000691 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000692 if (RD->getNumVBases()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000693 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
694 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
695 << RD->getNumVBases();
696 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
697 E = RD->vbases_end(); I != E; ++I)
Daniel Dunbar96a00142012-03-09 18:35:03 +0000698 Diag(I->getLocStart(),
Richard Smith86c3ae42012-02-13 03:54:03 +0000699 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
Richard Smith9f569cc2011-10-01 02:31:28 +0000700 return false;
701 }
Richard Smith35340502012-01-13 04:54:00 +0000702 }
703
704 if (!isa<CXXConstructorDecl>(NewFD)) {
705 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000706 // The definition of a constexpr function shall satisfy the following
707 // constraints:
708 // - it shall not be virtual;
709 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
710 if (Method && Method->isVirtual()) {
Richard Smith86c3ae42012-02-13 03:54:03 +0000711 Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
Richard Smith9f569cc2011-10-01 02:31:28 +0000712
Richard Smith86c3ae42012-02-13 03:54:03 +0000713 // If it's not obvious why this function is virtual, find an overridden
714 // function which uses the 'virtual' keyword.
715 const CXXMethodDecl *WrittenVirtual = Method;
716 while (!WrittenVirtual->isVirtualAsWritten())
717 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
718 if (WrittenVirtual != Method)
719 Diag(WrittenVirtual->getLocation(),
720 diag::note_overridden_virtual_function);
Richard Smith9f569cc2011-10-01 02:31:28 +0000721 return false;
722 }
723
724 // - its return type shall be a literal type;
725 QualType RT = NewFD->getResultType();
726 if (!RT->isDependentType() &&
Richard Smith86c3ae42012-02-13 03:54:03 +0000727 RequireLiteralType(NewFD->getLocation(), RT,
Douglas Gregorf502d8e2012-05-04 16:48:41 +0000728 diag::err_constexpr_non_literal_return))
Richard Smith9f569cc2011-10-01 02:31:28 +0000729 return false;
Richard Smith9f569cc2011-10-01 02:31:28 +0000730 }
731
Richard Smith35340502012-01-13 04:54:00 +0000732 // - each of its parameter types shall be a literal type;
Richard Smith86c3ae42012-02-13 03:54:03 +0000733 if (!CheckConstexprParameterTypes(*this, NewFD))
Richard Smith35340502012-01-13 04:54:00 +0000734 return false;
735
Richard Smith9f569cc2011-10-01 02:31:28 +0000736 return true;
737}
738
739/// Check the given declaration statement is legal within a constexpr function
740/// body. C++0x [dcl.constexpr]p3,p4.
741///
742/// \return true if the body is OK, false if we have diagnosed a problem.
743static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
744 DeclStmt *DS) {
745 // C++0x [dcl.constexpr]p3 and p4:
746 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
747 // contain only
748 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
749 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
750 switch ((*DclIt)->getKind()) {
751 case Decl::StaticAssert:
752 case Decl::Using:
753 case Decl::UsingShadow:
754 case Decl::UsingDirective:
755 case Decl::UnresolvedUsingTypename:
756 // - static_assert-declarations
757 // - using-declarations,
758 // - using-directives,
759 continue;
760
761 case Decl::Typedef:
762 case Decl::TypeAlias: {
763 // - typedef declarations and alias-declarations that do not define
764 // classes or enumerations,
765 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
766 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
767 // Don't allow variably-modified types in constexpr functions.
768 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
769 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
770 << TL.getSourceRange() << TL.getType()
771 << isa<CXXConstructorDecl>(Dcl);
772 return false;
773 }
774 continue;
775 }
776
777 case Decl::Enum:
778 case Decl::CXXRecord:
779 // As an extension, we allow the declaration (but not the definition) of
780 // classes and enumerations in all declarations, not just in typedef and
781 // alias declarations.
782 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
783 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
784 << isa<CXXConstructorDecl>(Dcl);
785 return false;
786 }
787 continue;
788
789 case Decl::Var:
790 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
791 << isa<CXXConstructorDecl>(Dcl);
792 return false;
793
794 default:
795 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
796 << isa<CXXConstructorDecl>(Dcl);
797 return false;
798 }
799 }
800
801 return true;
802}
803
804/// Check that the given field is initialized within a constexpr constructor.
805///
806/// \param Dcl The constexpr constructor being checked.
807/// \param Field The field being checked. This may be a member of an anonymous
808/// struct or union nested within the class being checked.
809/// \param Inits All declarations, including anonymous struct/union members and
810/// indirect members, for which any initialization was provided.
811/// \param Diagnosed Set to true if an error is produced.
812static void CheckConstexprCtorInitializer(Sema &SemaRef,
813 const FunctionDecl *Dcl,
814 FieldDecl *Field,
815 llvm::SmallSet<Decl*, 16> &Inits,
816 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000817 if (Field->isUnnamedBitfield())
818 return;
Richard Smith30ecfad2012-02-09 06:40:58 +0000819
820 if (Field->isAnonymousStructOrUnion() &&
821 Field->getType()->getAsCXXRecordDecl()->isEmpty())
822 return;
823
Richard Smith9f569cc2011-10-01 02:31:28 +0000824 if (!Inits.count(Field)) {
825 if (!Diagnosed) {
826 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
827 Diagnosed = true;
828 }
829 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
830 } else if (Field->isAnonymousStructOrUnion()) {
831 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
832 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
833 I != E; ++I)
834 // If an anonymous union contains an anonymous struct of which any member
835 // is initialized, all members must be initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000836 if (!RD->isUnion() || Inits.count(*I))
837 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000838 }
839}
840
841/// Check the body for the given constexpr function declaration only contains
842/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
843///
844/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith86c3ae42012-02-13 03:54:03 +0000845bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000846 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000847 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000848 // The definition of a constexpr function shall satisfy the following
849 // constraints: [...]
850 // - its function-body shall be = delete, = default, or a
851 // compound-statement
852 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000853 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000854 // In the definition of a constexpr constructor, [...]
855 // - its function-body shall not be a function-try-block;
856 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
857 << isa<CXXConstructorDecl>(Dcl);
858 return false;
859 }
860
861 // - its function-body shall be [...] a compound-statement that contains only
862 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
863
864 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
865 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
866 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
867 switch ((*BodyIt)->getStmtClass()) {
868 case Stmt::NullStmtClass:
869 // - null statements,
870 continue;
871
872 case Stmt::DeclStmtClass:
873 // - static_assert-declarations
874 // - using-declarations,
875 // - using-directives,
876 // - typedef declarations and alias-declarations that do not define
877 // classes or enumerations,
878 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
879 return false;
880 continue;
881
882 case Stmt::ReturnStmtClass:
883 // - and exactly one return statement;
884 if (isa<CXXConstructorDecl>(Dcl))
885 break;
886
887 ReturnStmts.push_back((*BodyIt)->getLocStart());
Richard Smith9f569cc2011-10-01 02:31:28 +0000888 continue;
889
890 default:
891 break;
892 }
893
894 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
895 << isa<CXXConstructorDecl>(Dcl);
896 return false;
897 }
898
899 if (const CXXConstructorDecl *Constructor
900 = dyn_cast<CXXConstructorDecl>(Dcl)) {
901 const CXXRecordDecl *RD = Constructor->getParent();
Richard Smith30ecfad2012-02-09 06:40:58 +0000902 // DR1359:
903 // - every non-variant non-static data member and base class sub-object
904 // shall be initialized;
905 // - if the class is a non-empty union, or for each non-empty anonymous
906 // union member of a non-union class, exactly one non-static data member
907 // shall be initialized;
Richard Smith9f569cc2011-10-01 02:31:28 +0000908 if (RD->isUnion()) {
Richard Smith30ecfad2012-02-09 06:40:58 +0000909 if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000910 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
911 return false;
912 }
Richard Smith6e433752011-10-10 16:38:04 +0000913 } else if (!Constructor->isDependentContext() &&
914 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000915 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
916
917 // Skip detailed checking if we have enough initializers, and we would
918 // allow at most one initializer per member.
919 bool AnyAnonStructUnionMembers = false;
920 unsigned Fields = 0;
921 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
922 E = RD->field_end(); I != E; ++I, ++Fields) {
David Blaikie262bc182012-04-30 02:36:29 +0000923 if (I->isAnonymousStructOrUnion()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000924 AnyAnonStructUnionMembers = true;
925 break;
926 }
927 }
928 if (AnyAnonStructUnionMembers ||
929 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
930 // Check initialization of non-static data members. Base classes are
931 // always initialized so do not need to be checked. Dependent bases
932 // might not have initializers in the member initializer list.
933 llvm::SmallSet<Decl*, 16> Inits;
934 for (CXXConstructorDecl::init_const_iterator
935 I = Constructor->init_begin(), E = Constructor->init_end();
936 I != E; ++I) {
937 if (FieldDecl *FD = (*I)->getMember())
938 Inits.insert(FD);
939 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
940 Inits.insert(ID->chain_begin(), ID->chain_end());
941 }
942
943 bool Diagnosed = false;
944 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
945 E = RD->field_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000946 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
Richard Smith9f569cc2011-10-01 02:31:28 +0000947 if (Diagnosed)
948 return false;
949 }
950 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000951 } else {
952 if (ReturnStmts.empty()) {
953 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
954 return false;
955 }
956 if (ReturnStmts.size() > 1) {
957 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
958 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
959 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
960 return false;
961 }
962 }
963
Richard Smith5ba73e12012-02-04 00:33:54 +0000964 // C++11 [dcl.constexpr]p5:
965 // if no function argument values exist such that the function invocation
966 // substitution would produce a constant expression, the program is
967 // ill-formed; no diagnostic required.
968 // C++11 [dcl.constexpr]p3:
969 // - every constructor call and implicit conversion used in initializing the
970 // return value shall be one of those allowed in a constant expression.
971 // C++11 [dcl.constexpr]p4:
972 // - every constructor involved in initializing non-static data members and
973 // base class sub-objects shall be a constexpr constructor.
Richard Smith745f5142012-01-27 01:14:48 +0000974 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith86c3ae42012-02-13 03:54:03 +0000975 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000976 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
977 << isa<CXXConstructorDecl>(Dcl);
978 for (size_t I = 0, N = Diags.size(); I != N; ++I)
979 Diag(Diags[I].first, Diags[I].second);
980 return false;
981 }
982
Richard Smith9f569cc2011-10-01 02:31:28 +0000983 return true;
984}
985
Douglas Gregorb48fe382008-10-31 09:07:45 +0000986/// isCurrentClassName - Determine whether the identifier II is the
987/// name of the class type currently being defined. In the case of
988/// nested classes, this will only return true if II is the name of
989/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000990bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
991 const CXXScopeSpec *SS) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000992 assert(getLangOpts().CPlusPlus && "No class names in C!");
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000993
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000994 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000995 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000996 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000997 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
998 } else
999 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1000
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001001 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001002 return &II == CurDecl->getIdentifier();
1003 else
1004 return false;
1005}
1006
Mike Stump1eb44332009-09-09 15:08:12 +00001007/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001008///
1009/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1010/// and returns NULL otherwise.
1011CXXBaseSpecifier *
1012Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1013 SourceRange SpecifierRange,
1014 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001015 TypeSourceInfo *TInfo,
1016 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001017 QualType BaseType = TInfo->getType();
1018
Douglas Gregor2943aed2009-03-03 04:44:36 +00001019 // C++ [class.union]p1:
1020 // A union shall not have base classes.
1021 if (Class->isUnion()) {
1022 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1023 << SpecifierRange;
1024 return 0;
1025 }
1026
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001027 if (EllipsisLoc.isValid() &&
1028 !TInfo->getType()->containsUnexpandedParameterPack()) {
1029 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1030 << TInfo->getTypeLoc().getSourceRange();
1031 EllipsisLoc = SourceLocation();
1032 }
1033
Douglas Gregor2943aed2009-03-03 04:44:36 +00001034 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001035 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001036 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001037 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001038
1039 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001040
1041 // Base specifiers must be record types.
1042 if (!BaseType->isRecordType()) {
1043 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1044 return 0;
1045 }
1046
1047 // C++ [class.union]p1:
1048 // A union shall not be used as a base class.
1049 if (BaseType->isUnionType()) {
1050 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1051 return 0;
1052 }
1053
1054 // C++ [class.derived]p2:
1055 // The class-name in a base-specifier shall not be an incompletely
1056 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001057 if (RequireCompleteType(BaseLoc, BaseType,
Douglas Gregord10099e2012-05-04 16:32:21 +00001058 diag::err_incomplete_base_class, SpecifierRange)) {
John McCall572fc622010-08-17 07:23:57 +00001059 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001060 return 0;
John McCall572fc622010-08-17 07:23:57 +00001061 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001062
Eli Friedman1d954f62009-08-15 21:55:26 +00001063 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001064 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001065 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001066 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001067 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001068 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1069 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001070
Anders Carlsson1d209272011-03-25 14:55:14 +00001071 // C++ [class]p3:
1072 // If a class is marked final and it appears as a base-type-specifier in
1073 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001074 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001075 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1076 << CXXBaseDecl->getDeclName();
1077 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1078 << CXXBaseDecl->getDeclName();
1079 return 0;
1080 }
1081
John McCall572fc622010-08-17 07:23:57 +00001082 if (BaseDecl->isInvalidDecl())
1083 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001084
1085 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001086 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001087 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001088 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001089}
1090
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001091/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1092/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001093/// example:
1094/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001095/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001096BaseResult
John McCalld226f652010-08-21 09:40:31 +00001097Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001098 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001099 ParsedType basetype, SourceLocation BaseLoc,
1100 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001101 if (!classdecl)
1102 return true;
1103
Douglas Gregor40808ce2009-03-09 23:48:35 +00001104 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001105 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001106 if (!Class)
1107 return true;
1108
Nick Lewycky56062202010-07-26 16:56:01 +00001109 TypeSourceInfo *TInfo = 0;
1110 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001111
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001112 if (EllipsisLoc.isInvalid() &&
1113 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001114 UPPC_BaseType))
1115 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001116
Douglas Gregor2943aed2009-03-03 04:44:36 +00001117 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001118 Virtual, Access, TInfo,
1119 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001120 return BaseSpec;
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001121 else
1122 Class->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Douglas Gregor2943aed2009-03-03 04:44:36 +00001124 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001125}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001126
Douglas Gregor2943aed2009-03-03 04:44:36 +00001127/// \brief Performs the actual work of attaching the given base class
1128/// specifiers to a C++ class.
1129bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1130 unsigned NumBases) {
1131 if (NumBases == 0)
1132 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001133
1134 // Used to keep track of which base types we have already seen, so
1135 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001136 // that the key is always the unqualified canonical type of the base
1137 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001138 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1139
1140 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001141 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001142 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001143 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001144 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001145 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001146 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Benjamin Kramer52c16682012-03-05 17:20:04 +00001147
1148 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1149 if (KnownBase) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001150 // C++ [class.mi]p3:
1151 // A class shall not be specified as a direct base class of a
1152 // derived class more than once.
Daniel Dunbar96a00142012-03-09 18:35:03 +00001153 Diag(Bases[idx]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001154 diag::err_duplicate_base_class)
Benjamin Kramer52c16682012-03-05 17:20:04 +00001155 << KnownBase->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001156 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001157
1158 // Delete the duplicate base class specifier; we're going to
1159 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001160 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001161
1162 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001163 } else {
1164 // Okay, add this new base class.
Benjamin Kramer52c16682012-03-05 17:20:04 +00001165 KnownBase = Bases[idx];
Douglas Gregor2943aed2009-03-03 04:44:36 +00001166 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001167 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001168 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1169 if (RD->hasAttr<WeakAttr>())
1170 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001171 }
1172 }
1173
1174 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001175 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001176
1177 // Delete the remaining (good) base class specifiers, since their
1178 // data has been copied into the CXXRecordDecl.
1179 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001180 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001181
1182 return Invalid;
1183}
1184
1185/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1186/// class, after checking whether there are any duplicate base
1187/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001188void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001189 unsigned NumBases) {
1190 if (!ClassDecl || !Bases || !NumBases)
1191 return;
1192
1193 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001194 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001195 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001196}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001197
John McCall3cb0ebd2010-03-10 03:28:59 +00001198static CXXRecordDecl *GetClassForType(QualType T) {
1199 if (const RecordType *RT = T->getAs<RecordType>())
1200 return cast<CXXRecordDecl>(RT->getDecl());
1201 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1202 return ICT->getDecl();
1203 else
1204 return 0;
1205}
1206
Douglas Gregora8f32e02009-10-06 17:59:45 +00001207/// \brief Determine whether the type \p Derived is a C++ class that is
1208/// derived from the type \p Base.
1209bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001210 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001211 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001212
1213 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1214 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001215 return false;
1216
John McCall3cb0ebd2010-03-10 03:28:59 +00001217 CXXRecordDecl *BaseRD = GetClassForType(Base);
1218 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001219 return false;
1220
John McCall86ff3082010-02-04 22:26:26 +00001221 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1222 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001223}
1224
1225/// \brief Determine whether the type \p Derived is a C++ class that is
1226/// derived from the type \p Base.
1227bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001228 if (!getLangOpts().CPlusPlus)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001229 return false;
1230
John McCall3cb0ebd2010-03-10 03:28:59 +00001231 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1232 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001233 return false;
1234
John McCall3cb0ebd2010-03-10 03:28:59 +00001235 CXXRecordDecl *BaseRD = GetClassForType(Base);
1236 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001237 return false;
1238
Douglas Gregora8f32e02009-10-06 17:59:45 +00001239 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1240}
1241
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001242void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001243 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001244 assert(BasePathArray.empty() && "Base path array must be empty!");
1245 assert(Paths.isRecordingPaths() && "Must record paths!");
1246
1247 const CXXBasePath &Path = Paths.front();
1248
1249 // We first go backward and check if we have a virtual base.
1250 // FIXME: It would be better if CXXBasePath had the base specifier for
1251 // the nearest virtual base.
1252 unsigned Start = 0;
1253 for (unsigned I = Path.size(); I != 0; --I) {
1254 if (Path[I - 1].Base->isVirtual()) {
1255 Start = I - 1;
1256 break;
1257 }
1258 }
1259
1260 // Now add all bases.
1261 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001262 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001263}
1264
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001265/// \brief Determine whether the given base path includes a virtual
1266/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001267bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1268 for (CXXCastPath::const_iterator B = BasePath.begin(),
1269 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001270 B != BEnd; ++B)
1271 if ((*B)->isVirtual())
1272 return true;
1273
1274 return false;
1275}
1276
Douglas Gregora8f32e02009-10-06 17:59:45 +00001277/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1278/// conversion (where Derived and Base are class types) is
1279/// well-formed, meaning that the conversion is unambiguous (and
1280/// that all of the base classes are accessible). Returns true
1281/// and emits a diagnostic if the code is ill-formed, returns false
1282/// otherwise. Loc is the location where this routine should point to
1283/// if there is an error, and Range is the source range to highlight
1284/// if there is an error.
1285bool
1286Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001287 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001288 unsigned AmbigiousBaseConvID,
1289 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001290 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001291 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001292 // First, determine whether the path from Derived to Base is
1293 // ambiguous. This is slightly more expensive than checking whether
1294 // the Derived to Base conversion exists, because here we need to
1295 // explore multiple paths to determine if there is an ambiguity.
1296 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1297 /*DetectVirtual=*/false);
1298 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1299 assert(DerivationOkay &&
1300 "Can only be used with a derived-to-base conversion");
1301 (void)DerivationOkay;
1302
1303 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001304 if (InaccessibleBaseID) {
1305 // Check that the base class can be accessed.
1306 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1307 InaccessibleBaseID)) {
1308 case AR_inaccessible:
1309 return true;
1310 case AR_accessible:
1311 case AR_dependent:
1312 case AR_delayed:
1313 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001314 }
John McCall6b2accb2010-02-10 09:31:12 +00001315 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001316
1317 // Build a base path if necessary.
1318 if (BasePath)
1319 BuildBasePathArray(Paths, *BasePath);
1320 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001321 }
1322
1323 // We know that the derived-to-base conversion is ambiguous, and
1324 // we're going to produce a diagnostic. Perform the derived-to-base
1325 // search just one more time to compute all of the possible paths so
1326 // that we can print them out. This is more expensive than any of
1327 // the previous derived-to-base checks we've done, but at this point
1328 // performance isn't as much of an issue.
1329 Paths.clear();
1330 Paths.setRecordingPaths(true);
1331 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1332 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1333 (void)StillOkay;
1334
1335 // Build up a textual representation of the ambiguous paths, e.g.,
1336 // D -> B -> A, that will be used to illustrate the ambiguous
1337 // conversions in the diagnostic. We only print one of the paths
1338 // to each base class subobject.
1339 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1340
1341 Diag(Loc, AmbigiousBaseConvID)
1342 << Derived << Base << PathDisplayStr << Range << Name;
1343 return true;
1344}
1345
1346bool
1347Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001348 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001349 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001350 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001351 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001352 IgnoreAccess ? 0
1353 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001354 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001355 Loc, Range, DeclarationName(),
1356 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001357}
1358
1359
1360/// @brief Builds a string representing ambiguous paths from a
1361/// specific derived class to different subobjects of the same base
1362/// class.
1363///
1364/// This function builds a string that can be used in error messages
1365/// to show the different paths that one can take through the
1366/// inheritance hierarchy to go from the derived class to different
1367/// subobjects of a base class. The result looks something like this:
1368/// @code
1369/// struct D -> struct B -> struct A
1370/// struct D -> struct C -> struct A
1371/// @endcode
1372std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1373 std::string PathDisplayStr;
1374 std::set<unsigned> DisplayedPaths;
1375 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1376 Path != Paths.end(); ++Path) {
1377 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1378 // We haven't displayed a path to this particular base
1379 // class subobject yet.
1380 PathDisplayStr += "\n ";
1381 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1382 for (CXXBasePath::const_iterator Element = Path->begin();
1383 Element != Path->end(); ++Element)
1384 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1385 }
1386 }
1387
1388 return PathDisplayStr;
1389}
1390
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001391//===----------------------------------------------------------------------===//
1392// C++ class member Handling
1393//===----------------------------------------------------------------------===//
1394
Abramo Bagnara6206d532010-06-05 05:09:32 +00001395/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001396bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1397 SourceLocation ASLoc,
1398 SourceLocation ColonLoc,
1399 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001400 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001401 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001402 ASLoc, ColonLoc);
1403 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001404 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001405}
1406
Richard Smitha4b39652012-08-06 03:25:17 +00001407/// CheckOverrideControl - Check C++11 override control semantics.
1408void Sema::CheckOverrideControl(Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001409 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001410
Richard Smitha4b39652012-08-06 03:25:17 +00001411 // Do we know which functions this declaration might be overriding?
1412 bool OverridesAreKnown = !MD ||
1413 (!MD->getParent()->hasAnyDependentBases() &&
1414 !MD->getType()->isDependentType());
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001415
Richard Smitha4b39652012-08-06 03:25:17 +00001416 if (!MD || !MD->isVirtual()) {
1417 if (OverridesAreKnown) {
1418 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1419 Diag(OA->getLocation(),
1420 diag::override_keyword_only_allowed_on_virtual_member_functions)
1421 << "override" << FixItHint::CreateRemoval(OA->getLocation());
1422 D->dropAttr<OverrideAttr>();
1423 }
1424 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1425 Diag(FA->getLocation(),
1426 diag::override_keyword_only_allowed_on_virtual_member_functions)
1427 << "final" << FixItHint::CreateRemoval(FA->getLocation());
1428 D->dropAttr<FinalAttr>();
1429 }
1430 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001431 return;
1432 }
Richard Smitha4b39652012-08-06 03:25:17 +00001433
1434 if (!OverridesAreKnown)
1435 return;
1436
1437 // C++11 [class.virtual]p5:
1438 // If a virtual function is marked with the virt-specifier override and
1439 // does not override a member function of a base class, the program is
1440 // ill-formed.
1441 bool HasOverriddenMethods =
1442 MD->begin_overridden_methods() != MD->end_overridden_methods();
1443 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1444 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1445 << MD->getDeclName();
Anders Carlsson9e682d92011-01-20 05:57:14 +00001446}
1447
Richard Smitha4b39652012-08-06 03:25:17 +00001448/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001449/// function overrides a virtual member function marked 'final', according to
Richard Smitha4b39652012-08-06 03:25:17 +00001450/// C++11 [class.virtual]p4.
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001451bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1452 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001453 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001454 return false;
1455
1456 Diag(New->getLocation(), diag::err_final_function_overridden)
1457 << New->getDeclName();
1458 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1459 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001460}
1461
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001462static bool InitializationHasSideEffects(const FieldDecl &FD) {
Richard Smith0b8220a2012-08-07 21:30:42 +00001463 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1464 // FIXME: Destruction of ObjC lifetime types has side-effects.
1465 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1466 return !RD->isCompleteDefinition() ||
1467 !RD->hasTrivialDefaultConstructor() ||
1468 !RD->hasTrivialDestructor();
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001469 return false;
1470}
1471
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001472/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1473/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001474/// bitfield width if there is one, 'InitExpr' specifies the initializer if
Richard Smithca523302012-06-10 03:12:00 +00001475/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1476/// present (but parsing it has been deferred).
John McCalld226f652010-08-21 09:40:31 +00001477Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001478Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001479 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001480 Expr *BW, const VirtSpecifiers &VS,
Richard Smithca523302012-06-10 03:12:00 +00001481 InClassInitStyle InitStyle) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001482 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001483 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1484 DeclarationName Name = NameInfo.getName();
1485 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001486
1487 // For anonymous bitfields, the location should point to the type.
1488 if (Loc.isInvalid())
Daniel Dunbar96a00142012-03-09 18:35:03 +00001489 Loc = D.getLocStart();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001490
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001491 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001492
John McCall4bde1e12010-06-04 08:34:12 +00001493 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001494 assert(!DS.isFriendSpecified());
1495
Richard Smith1ab0d902011-06-25 02:28:38 +00001496 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001497
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001498 // C++ 9.2p6: A member shall not be declared to have automatic storage
1499 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001500 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1501 // data members and cannot be applied to names declared const or static,
1502 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001503 switch (DS.getStorageClassSpec()) {
1504 case DeclSpec::SCS_unspecified:
1505 case DeclSpec::SCS_typedef:
1506 case DeclSpec::SCS_static:
1507 // FALL THROUGH.
1508 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001509 case DeclSpec::SCS_mutable:
1510 if (isFunc) {
1511 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001512 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001513 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001514 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001515
Sebastian Redla11f42f2008-11-17 23:24:37 +00001516 // FIXME: It would be nicer if the keyword was ignored only for this
1517 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001518 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001519 }
1520 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001521 default:
1522 if (DS.getStorageClassSpecLoc().isValid())
1523 Diag(DS.getStorageClassSpecLoc(),
1524 diag::err_storageclass_invalid_for_member);
1525 else
1526 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1527 D.getMutableDeclSpec().ClearStorageClassSpecs();
1528 }
1529
Sebastian Redl669d5d72008-11-14 23:42:31 +00001530 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1531 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001532 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001533
1534 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001535 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001536 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001537
1538 // Data members must have identifiers for names.
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001539 if (!Name.isIdentifier()) {
Douglas Gregorb5a01872011-10-09 18:55:59 +00001540 Diag(Loc, diag::err_bad_variable_name)
1541 << Name;
1542 return 0;
1543 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001544
Benjamin Kramerc1aa40c2012-05-19 16:34:46 +00001545 IdentifierInfo *II = Name.getAsIdentifierInfo();
1546
Douglas Gregorf2503652011-09-21 14:40:46 +00001547 // Member field could not be with "template" keyword.
1548 // So TemplateParameterLists should be empty in this case.
1549 if (TemplateParameterLists.size()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001550 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
Douglas Gregorf2503652011-09-21 14:40:46 +00001551 if (TemplateParams->size()) {
1552 // There is no such thing as a member field template.
1553 Diag(D.getIdentifierLoc(), diag::err_template_member)
1554 << II
1555 << SourceRange(TemplateParams->getTemplateLoc(),
1556 TemplateParams->getRAngleLoc());
1557 } else {
1558 // There is an extraneous 'template<>' for this member.
1559 Diag(TemplateParams->getTemplateLoc(),
1560 diag::err_template_member_noparams)
1561 << II
1562 << SourceRange(TemplateParams->getTemplateLoc(),
1563 TemplateParams->getRAngleLoc());
1564 }
1565 return 0;
1566 }
1567
Douglas Gregor922fff22010-10-13 22:19:53 +00001568 if (SS.isSet() && !SS.isInvalid()) {
1569 // The user provided a superfluous scope specifier inside a class
1570 // definition:
1571 //
1572 // class X {
1573 // int X::member;
1574 // };
Douglas Gregor69605872012-03-28 16:01:27 +00001575 if (DeclContext *DC = computeDeclContext(SS, false))
1576 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
Douglas Gregor922fff22010-10-13 22:19:53 +00001577 else
1578 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1579 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001580
Douglas Gregor922fff22010-10-13 22:19:53 +00001581 SS.clear();
1582 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001583
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001584 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smithca523302012-06-10 03:12:00 +00001585 InitStyle, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001586 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001587 } else {
Richard Smithca523302012-06-10 03:12:00 +00001588 assert(InitStyle == ICIS_NoInit);
Richard Smith7a614d82011-06-11 17:19:42 +00001589
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001590 Member = HandleDeclarator(S, D, TemplateParameterLists);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001591 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001592 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001593 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001594
1595 // Non-instance-fields can't have a bitfield.
1596 if (BitWidth) {
1597 if (Member->isInvalidDecl()) {
1598 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001599 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001600 // C++ 9.6p3: A bit-field shall not be a static member.
1601 // "static member 'A' cannot be a bit-field"
1602 Diag(Loc, diag::err_static_not_bitfield)
1603 << Name << BitWidth->getSourceRange();
1604 } else if (isa<TypedefDecl>(Member)) {
1605 // "typedef member 'x' cannot be a bit-field"
1606 Diag(Loc, diag::err_typedef_not_bitfield)
1607 << Name << BitWidth->getSourceRange();
1608 } else {
1609 // A function typedef ("typedef int f(); f a;").
1610 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1611 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001612 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001613 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001614 }
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Chris Lattner8b963ef2009-03-05 23:01:03 +00001616 BitWidth = 0;
1617 Member->setInvalidDecl();
1618 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001619
1620 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Douglas Gregor37b372b2009-08-20 22:52:58 +00001622 // If we have declared a member function template, set the access of the
1623 // templated declaration as well.
1624 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1625 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001626 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001627
Richard Smitha4b39652012-08-06 03:25:17 +00001628 if (VS.isOverrideSpecified())
1629 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1630 if (VS.isFinalSpecified())
1631 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson9e682d92011-01-20 05:57:14 +00001632
Douglas Gregorf5251602011-03-08 17:10:18 +00001633 if (VS.getLastLocation().isValid()) {
1634 // Update the end location of a method that has a virt-specifiers.
1635 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1636 MD->setRangeEnd(VS.getLastLocation());
1637 }
Richard Smitha4b39652012-08-06 03:25:17 +00001638
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001639 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001640
Douglas Gregor10bd3682008-11-17 22:58:34 +00001641 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001642
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001643 if (isInstField) {
1644 FieldDecl *FD = cast<FieldDecl>(Member);
1645 FieldCollector->Add(FD);
1646
1647 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1648 FD->getLocation())
1649 != DiagnosticsEngine::Ignored) {
1650 // Remember all explicit private FieldDecls that have a name, no side
1651 // effects and are not part of a dependent type declaration.
1652 if (!FD->isImplicit() && FD->getDeclName() &&
1653 FD->getAccess() == AS_private &&
Daniel Jasper568eae42012-06-13 18:31:09 +00001654 !FD->hasAttr<UnusedAttr>() &&
Richard Smith0b8220a2012-08-07 21:30:42 +00001655 !FD->getParent()->isDependentContext() &&
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001656 !InitializationHasSideEffects(*FD))
1657 UnusedPrivateFields.insert(FD);
1658 }
1659 }
1660
John McCalld226f652010-08-21 09:40:31 +00001661 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001662}
1663
Richard Smith7a614d82011-06-11 17:19:42 +00001664/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001665/// in-class initializer for a non-static C++ class member, and after
1666/// instantiating an in-class initializer in a class template. Such actions
1667/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001668void
Richard Smithca523302012-06-10 03:12:00 +00001669Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
Richard Smith7a614d82011-06-11 17:19:42 +00001670 Expr *InitExpr) {
1671 FieldDecl *FD = cast<FieldDecl>(D);
Richard Smithca523302012-06-10 03:12:00 +00001672 assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1673 "must set init style when field is created");
Richard Smith7a614d82011-06-11 17:19:42 +00001674
1675 if (!InitExpr) {
1676 FD->setInvalidDecl();
1677 FD->removeInClassInitializer();
1678 return;
1679 }
1680
Peter Collingbournefef21892011-10-23 18:59:44 +00001681 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1682 FD->setInvalidDecl();
1683 FD->removeInClassInitializer();
1684 return;
1685 }
1686
Richard Smith7a614d82011-06-11 17:19:42 +00001687 ExprResult Init = InitExpr;
1688 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
Sebastian Redl772291a2012-02-19 16:31:05 +00001689 if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
Sebastian Redl33deb352012-02-22 10:50:08 +00001690 Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
Sebastian Redl772291a2012-02-19 16:31:05 +00001691 << /*at end of ctor*/1 << InitExpr->getSourceRange();
1692 }
Sebastian Redl33deb352012-02-22 10:50:08 +00001693 Expr **Inits = &InitExpr;
1694 unsigned NumInits = 1;
1695 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
Richard Smithca523302012-06-10 03:12:00 +00001696 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
Sebastian Redl33deb352012-02-22 10:50:08 +00001697 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
Richard Smithca523302012-06-10 03:12:00 +00001698 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
Sebastian Redl33deb352012-02-22 10:50:08 +00001699 InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1700 Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
Richard Smith7a614d82011-06-11 17:19:42 +00001701 if (Init.isInvalid()) {
1702 FD->setInvalidDecl();
1703 return;
1704 }
1705
Richard Smithca523302012-06-10 03:12:00 +00001706 CheckImplicitConversions(Init.get(), InitLoc);
Richard Smith7a614d82011-06-11 17:19:42 +00001707 }
1708
1709 // C++0x [class.base.init]p7:
1710 // The initialization of each base and member constitutes a
1711 // full-expression.
1712 Init = MaybeCreateExprWithCleanups(Init);
1713 if (Init.isInvalid()) {
1714 FD->setInvalidDecl();
1715 return;
1716 }
1717
1718 InitExpr = Init.release();
1719
1720 FD->setInClassInitializer(InitExpr);
1721}
1722
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001723/// \brief Find the direct and/or virtual base specifiers that
1724/// correspond to the given base type, for use in base initialization
1725/// within a constructor.
1726static bool FindBaseInitializer(Sema &SemaRef,
1727 CXXRecordDecl *ClassDecl,
1728 QualType BaseType,
1729 const CXXBaseSpecifier *&DirectBaseSpec,
1730 const CXXBaseSpecifier *&VirtualBaseSpec) {
1731 // First, check for a direct base class.
1732 DirectBaseSpec = 0;
1733 for (CXXRecordDecl::base_class_const_iterator Base
1734 = ClassDecl->bases_begin();
1735 Base != ClassDecl->bases_end(); ++Base) {
1736 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1737 // We found a direct base of this type. That's what we're
1738 // initializing.
1739 DirectBaseSpec = &*Base;
1740 break;
1741 }
1742 }
1743
1744 // Check for a virtual base class.
1745 // FIXME: We might be able to short-circuit this if we know in advance that
1746 // there are no virtual bases.
1747 VirtualBaseSpec = 0;
1748 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1749 // We haven't found a base yet; search the class hierarchy for a
1750 // virtual base class.
1751 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1752 /*DetectVirtual=*/false);
1753 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1754 BaseType, Paths)) {
1755 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1756 Path != Paths.end(); ++Path) {
1757 if (Path->back().Base->isVirtual()) {
1758 VirtualBaseSpec = Path->back().Base;
1759 break;
1760 }
1761 }
1762 }
1763 }
1764
1765 return DirectBaseSpec || VirtualBaseSpec;
1766}
1767
Sebastian Redl6df65482011-09-24 17:48:25 +00001768/// \brief Handle a C++ member initializer using braced-init-list syntax.
1769MemInitResult
1770Sema::ActOnMemInitializer(Decl *ConstructorD,
1771 Scope *S,
1772 CXXScopeSpec &SS,
1773 IdentifierInfo *MemberOrBase,
1774 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001775 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001776 SourceLocation IdLoc,
1777 Expr *InitList,
1778 SourceLocation EllipsisLoc) {
1779 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001780 DS, IdLoc, InitList,
David Blaikief2116622012-01-24 06:03:59 +00001781 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001782}
1783
1784/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001785MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001786Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001787 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001788 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001789 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001790 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001791 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001792 SourceLocation IdLoc,
1793 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001794 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001795 SourceLocation RParenLoc,
1796 SourceLocation EllipsisLoc) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001797 Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1798 RParenLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001799 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001800 DS, IdLoc, List, EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001801}
1802
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001803namespace {
1804
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001805// Callback to only accept typo corrections that can be a valid C++ member
1806// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001807class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1808 public:
1809 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1810 : ClassDecl(ClassDecl) {}
1811
1812 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1813 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1814 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1815 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1816 else
1817 return isa<TypeDecl>(ND);
1818 }
1819 return false;
1820 }
1821
1822 private:
1823 CXXRecordDecl *ClassDecl;
1824};
1825
1826}
1827
Sebastian Redl6df65482011-09-24 17:48:25 +00001828/// \brief Handle a C++ member initializer.
1829MemInitResult
1830Sema::BuildMemInitializer(Decl *ConstructorD,
1831 Scope *S,
1832 CXXScopeSpec &SS,
1833 IdentifierInfo *MemberOrBase,
1834 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001835 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001836 SourceLocation IdLoc,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001837 Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00001838 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001839 if (!ConstructorD)
1840 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001842 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001843
1844 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001845 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001846 if (!Constructor) {
1847 // The user wrote a constructor initializer on a function that is
1848 // not a C++ constructor. Ignore the error for now, because we may
1849 // have more member initializers coming; we'll diagnose it just
1850 // once in ActOnMemInitializers.
1851 return true;
1852 }
1853
1854 CXXRecordDecl *ClassDecl = Constructor->getParent();
1855
1856 // C++ [class.base.init]p2:
1857 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001858 // constructor's class and, if not found in that scope, are looked
1859 // up in the scope containing the constructor's definition.
1860 // [Note: if the constructor's class contains a member with the
1861 // same name as a direct or virtual base class of the class, a
1862 // mem-initializer-id naming the member or base class and composed
1863 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001864 // mem-initializer-id for the hidden base class may be specified
1865 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001866 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001867 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001868 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001869 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001870 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001871 ValueDecl *Member;
1872 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1873 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001874 if (EllipsisLoc.isValid())
1875 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001876 << MemberOrBase
1877 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00001878
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001879 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001880 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001881 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001882 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001883 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001884 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001885 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001886
1887 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001888 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001889 } else if (DS.getTypeSpecType() == TST_decltype) {
1890 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001891 } else {
1892 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1893 LookupParsedName(R, S, &SS);
1894
1895 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1896 if (!TyD) {
1897 if (R.isAmbiguous()) return true;
1898
John McCallfd225442010-04-09 19:01:14 +00001899 // We don't want access-control diagnostics here.
1900 R.suppressDiagnostics();
1901
Douglas Gregor7a886e12010-01-19 06:46:48 +00001902 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1903 bool NotUnknownSpecialization = false;
1904 DeclContext *DC = computeDeclContext(SS, false);
1905 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1906 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1907
1908 if (!NotUnknownSpecialization) {
1909 // When the scope specifier can refer to a member of an unknown
1910 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001911 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1912 SS.getWithLocInContext(Context),
1913 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001914 if (BaseType.isNull())
1915 return true;
1916
Douglas Gregor7a886e12010-01-19 06:46:48 +00001917 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001918 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001919 }
1920 }
1921
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001922 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001923 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001924 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001925 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001926 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001927 Validator, ClassDecl))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001928 std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1929 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001930 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001931 // We have found a non-static data member with a similar
1932 // name to what was typed; complain and initialize that
1933 // member.
1934 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1935 << MemberOrBase << true << CorrectedQuotedStr
1936 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1937 Diag(Member->getLocation(), diag::note_previous_decl)
1938 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001939
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001940 return BuildMemberInitializer(Member, Init, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001941 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001942 const CXXBaseSpecifier *DirectBaseSpec;
1943 const CXXBaseSpecifier *VirtualBaseSpec;
1944 if (FindBaseInitializer(*this, ClassDecl,
1945 Context.getTypeDeclType(Type),
1946 DirectBaseSpec, VirtualBaseSpec)) {
1947 // We have found a direct or virtual base class with a
1948 // similar name to what was typed; complain and initialize
1949 // that base class.
1950 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001951 << MemberOrBase << false << CorrectedQuotedStr
1952 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001953
1954 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1955 : VirtualBaseSpec;
Daniel Dunbar96a00142012-03-09 18:35:03 +00001956 Diag(BaseSpec->getLocStart(),
Douglas Gregor0d535c82010-01-07 00:26:25 +00001957 diag::note_base_class_specified_here)
1958 << BaseSpec->getType()
1959 << BaseSpec->getSourceRange();
1960
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001961 TyD = Type;
1962 }
1963 }
1964 }
1965
Douglas Gregor7a886e12010-01-19 06:46:48 +00001966 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001967 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001968 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001969 return true;
1970 }
John McCall2b194412009-12-21 10:41:20 +00001971 }
1972
Douglas Gregor7a886e12010-01-19 06:46:48 +00001973 if (BaseType.isNull()) {
1974 BaseType = Context.getTypeDeclType(TyD);
1975 if (SS.isSet()) {
1976 NestedNameSpecifier *Qualifier =
1977 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001978
Douglas Gregor7a886e12010-01-19 06:46:48 +00001979 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001980 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001981 }
John McCall2b194412009-12-21 10:41:20 +00001982 }
1983 }
Mike Stump1eb44332009-09-09 15:08:12 +00001984
John McCalla93c9342009-12-07 02:54:59 +00001985 if (!TInfo)
1986 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001987
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001988 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001989}
1990
Chandler Carruth81c64772011-09-03 01:14:15 +00001991/// Checks a member initializer expression for cases where reference (or
1992/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001993static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1994 Expr *Init,
1995 SourceLocation IdLoc) {
1996 QualType MemberTy = Member->getType();
1997
1998 // We only handle pointers and references currently.
1999 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2000 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2001 return;
2002
2003 const bool IsPointer = MemberTy->isPointerType();
2004 if (IsPointer) {
2005 if (const UnaryOperator *Op
2006 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2007 // The only case we're worried about with pointers requires taking the
2008 // address.
2009 if (Op->getOpcode() != UO_AddrOf)
2010 return;
2011
2012 Init = Op->getSubExpr();
2013 } else {
2014 // We only handle address-of expression initializers for pointers.
2015 return;
2016 }
2017 }
2018
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002019 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2020 // Taking the address of a temporary will be diagnosed as a hard error.
2021 if (IsPointer)
2022 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002023
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002024 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2025 << Member << Init->getSourceRange();
2026 } else if (const DeclRefExpr *DRE
2027 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2028 // We only warn when referring to a non-reference parameter declaration.
2029 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2030 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002031 return;
2032
2033 S.Diag(Init->getExprLoc(),
2034 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2035 : diag::warn_bind_ref_member_to_parameter)
2036 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002037 } else {
2038 // Other initializers are fine.
2039 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002040 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002041
2042 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2043 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002044}
2045
Richard Trieude5e75c2012-06-14 23:11:34 +00002046namespace {
2047 class UninitializedFieldVisitor
2048 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2049 Sema &S;
2050 ValueDecl *VD;
2051 public:
2052 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2053 UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2054 S(S), VD(VD) {
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002055 }
2056
Richard Trieude5e75c2012-06-14 23:11:34 +00002057 void HandleExpr(Expr *E) {
2058 if (!E) return;
2059
2060 // Expressions like x(x) sometimes lack the surrounding expressions
2061 // but need to be checked anyways.
2062 HandleValue(E);
2063 Visit(E);
2064 }
2065
2066 void HandleValue(Expr *E) {
2067 E = E->IgnoreParens();
2068
Richard Trieue0991252012-06-14 23:18:09 +00002069 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
Richard Trieude5e75c2012-06-14 23:11:34 +00002070 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2071 return;
Richard Trieue0991252012-06-14 23:18:09 +00002072 Expr *Base = E;
Richard Trieude5e75c2012-06-14 23:11:34 +00002073 while (isa<MemberExpr>(Base)) {
2074 ME = dyn_cast<MemberExpr>(Base);
2075 if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl()))
2076 if (VarD->hasGlobalStorage())
2077 return;
2078 Base = ME->getBase();
2079 }
2080
2081 if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
Hans Wennborg5965b7c2012-08-20 08:52:22 +00002082 unsigned diag = VD->getType()->isReferenceType()
2083 ? diag::warn_reference_field_is_uninit
2084 : diag::warn_field_is_uninit;
2085 S.Diag(ME->getExprLoc(), diag);
Richard Trieude5e75c2012-06-14 23:11:34 +00002086 return;
2087 }
John McCallb4190042009-11-04 23:02:40 +00002088 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002089
2090 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2091 HandleValue(CO->getTrueExpr());
2092 HandleValue(CO->getFalseExpr());
2093 return;
2094 }
2095
2096 if (BinaryConditionalOperator *BCO =
2097 dyn_cast<BinaryConditionalOperator>(E)) {
2098 HandleValue(BCO->getCommon());
2099 HandleValue(BCO->getFalseExpr());
2100 return;
2101 }
2102
2103 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2104 switch (BO->getOpcode()) {
2105 default:
2106 return;
2107 case(BO_PtrMemD):
2108 case(BO_PtrMemI):
2109 HandleValue(BO->getLHS());
2110 return;
2111 case(BO_Comma):
2112 HandleValue(BO->getRHS());
2113 return;
2114 }
2115 }
John McCallb4190042009-11-04 23:02:40 +00002116 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002117
2118 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2119 if (E->getCastKind() == CK_LValueToRValue)
2120 HandleValue(E->getSubExpr());
2121
2122 Inherited::VisitImplicitCastExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002123 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002124
2125 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2126 Expr *Callee = E->getCallee();
2127 if (isa<MemberExpr>(Callee))
2128 HandleValue(Callee);
2129
2130 Inherited::VisitCXXMemberCallExpr(E);
2131 }
2132 };
2133 static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2134 ValueDecl *VD) {
2135 UninitializedFieldVisitor(S, VD).HandleExpr(E);
John McCallb4190042009-11-04 23:02:40 +00002136 }
Richard Trieude5e75c2012-06-14 23:11:34 +00002137} // namespace
John McCallb4190042009-11-04 23:02:40 +00002138
John McCallf312b1e2010-08-26 23:41:50 +00002139MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002140Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
Sebastian Redl6df65482011-09-24 17:48:25 +00002141 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002142 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2143 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2144 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002145 "Member must be a FieldDecl or IndirectFieldDecl");
2146
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002147 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Peter Collingbournefef21892011-10-23 18:59:44 +00002148 return true;
2149
Douglas Gregor464b2f02010-11-05 22:21:31 +00002150 if (Member->isInvalidDecl())
2151 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002152
John McCallb4190042009-11-04 23:02:40 +00002153 // Diagnose value-uses of fields to initialize themselves, e.g.
2154 // foo(foo)
2155 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002156 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002157 Expr **Args;
2158 unsigned NumArgs;
2159 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2160 Args = ParenList->getExprs();
2161 NumArgs = ParenList->getNumExprs();
2162 } else {
2163 InitListExpr *InitList = cast<InitListExpr>(Init);
2164 Args = InitList->getInits();
2165 NumArgs = InitList->getNumInits();
2166 }
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00002167
Richard Trieude5e75c2012-06-14 23:11:34 +00002168 if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2169 != DiagnosticsEngine::Ignored)
2170 for (unsigned i = 0; i < NumArgs; ++i)
2171 // FIXME: Warn about the case when other fields are used before being
John McCallb4190042009-11-04 23:02:40 +00002172 // uninitialized. For example, let this field be the i'th field. When
2173 // initializing the i'th field, throw a warning if any of the >= i'th
2174 // fields are used, as they are not yet initialized.
2175 // Right now we are only handling the case where the i'th field uses
2176 // itself in its initializer.
Richard Trieude5e75c2012-06-14 23:11:34 +00002177 CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
John McCallb4190042009-11-04 23:02:40 +00002178
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002179 SourceRange InitRange = Init->getSourceRange();
Eli Friedman59c04372009-07-29 19:44:27 +00002180
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002181 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002182 // Can't check initialization for a member of dependent type or when
2183 // any of the arguments are type-dependent expressions.
John McCallf85e1932011-06-15 23:02:42 +00002184 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002185 } else {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002186 bool InitList = false;
2187 if (isa<InitListExpr>(Init)) {
2188 InitList = true;
2189 Args = &Init;
2190 NumArgs = 1;
Sebastian Redl772291a2012-02-19 16:31:05 +00002191
2192 if (isStdInitializerList(Member->getType(), 0)) {
2193 Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2194 << /*at end of ctor*/1 << InitRange;
2195 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002196 }
2197
Chandler Carruth894aed92010-12-06 09:23:57 +00002198 // Initialize the member.
2199 InitializedEntity MemberEntity =
2200 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2201 : InitializedEntity::InitializeMember(IndirectMember, 0);
2202 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002203 InitList ? InitializationKind::CreateDirectList(IdLoc)
2204 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2205 InitRange.getEnd());
John McCallb4eb64d2010-10-08 02:01:28 +00002206
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002207 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2208 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002209 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002210 0);
Chandler Carruth894aed92010-12-06 09:23:57 +00002211 if (MemberInit.isInvalid())
2212 return true;
2213
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002214 CheckImplicitConversions(MemberInit.get(),
2215 InitRange.getBegin());
Chandler Carruth894aed92010-12-06 09:23:57 +00002216
2217 // C++0x [class.base.init]p7:
2218 // The initialization of each base and member constitutes a
2219 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002220 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002221 if (MemberInit.isInvalid())
2222 return true;
2223
2224 // If we are in a dependent context, template instantiation will
2225 // perform this type-checking again. Just save the arguments that we
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002226 // received.
Chandler Carruth894aed92010-12-06 09:23:57 +00002227 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2228 // of the information that we have about the member
2229 // initializer. However, deconstructing the ASTs is a dicey process,
2230 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002231 if (CurContext->isDependentContext()) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002232 // The existing Init will do fine.
Chandler Carruth81c64772011-09-03 01:14:15 +00002233 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002234 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002235 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2236 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002237 }
2238
Chandler Carruth894aed92010-12-06 09:23:57 +00002239 if (DirectMember) {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002240 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2241 InitRange.getBegin(), Init,
2242 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002243 } else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002244 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2245 InitRange.getBegin(), Init,
2246 InitRange.getEnd());
Chandler Carruth894aed92010-12-06 09:23:57 +00002247 }
Eli Friedman59c04372009-07-29 19:44:27 +00002248}
2249
John McCallf312b1e2010-08-26 23:41:50 +00002250MemInitResult
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002251Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
Sean Hunt41717662011-02-26 19:13:13 +00002252 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002253 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002254 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002255 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002256 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002257 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002258
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002259 bool InitList = true;
2260 Expr **Args = &Init;
2261 unsigned NumArgs = 1;
2262 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2263 InitList = false;
2264 Args = ParenList->getExprs();
2265 NumArgs = ParenList->getNumExprs();
2266 }
2267
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002268 SourceRange InitRange = Init->getSourceRange();
Sean Hunt41717662011-02-26 19:13:13 +00002269 // Initialize the object.
2270 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2271 QualType(ClassDecl->getTypeForDecl(), 0));
2272 InitializationKind Kind =
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002273 InitList ? InitializationKind::CreateDirectList(NameLoc)
2274 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2275 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002276 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2277 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002278 MultiExprArg(Args, NumArgs),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002279 0);
Sean Hunt41717662011-02-26 19:13:13 +00002280 if (DelegationInit.isInvalid())
2281 return true;
2282
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002283 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2284 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002285
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002286 CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
Sean Hunt41717662011-02-26 19:13:13 +00002287
2288 // C++0x [class.base.init]p7:
2289 // The initialization of each base and member constitutes a
2290 // full-expression.
2291 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2292 if (DelegationInit.isInvalid())
2293 return true;
2294
Eli Friedmand21016f2012-05-19 23:35:23 +00002295 // If we are in a dependent context, template instantiation will
2296 // perform this type-checking again. Just save the arguments that we
2297 // received in a ParenListExpr.
2298 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2299 // of the information that we have about the base
2300 // initializer. However, deconstructing the ASTs is a dicey process,
2301 // and this approach is far more likely to get the corner cases right.
2302 if (CurContext->isDependentContext())
2303 DelegationInit = Owned(Init);
2304
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002305 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
Sean Hunt41717662011-02-26 19:13:13 +00002306 DelegationInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002307 InitRange.getEnd());
Sean Hunt97fcc492011-01-08 19:20:43 +00002308}
2309
2310MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002311Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002312 Expr *Init, CXXRecordDecl *ClassDecl,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002313 SourceLocation EllipsisLoc) {
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002314 SourceLocation BaseLoc
2315 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002316
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002317 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2318 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2319 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2320
2321 // C++ [class.base.init]p2:
2322 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002323 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002324 // of that class, the mem-initializer is ill-formed. A
2325 // mem-initializer-list can initialize a base class using any
2326 // name that denotes that base class type.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002327 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002328
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002329 SourceRange InitRange = Init->getSourceRange();
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002330 if (EllipsisLoc.isValid()) {
2331 // This is a pack expansion.
2332 if (!BaseType->containsUnexpandedParameterPack()) {
2333 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002334 << SourceRange(BaseLoc, InitRange.getEnd());
Sebastian Redl6df65482011-09-24 17:48:25 +00002335
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002336 EllipsisLoc = SourceLocation();
2337 }
2338 } else {
2339 // Check for any unexpanded parameter packs.
2340 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2341 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002342
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002343 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
Sebastian Redl6df65482011-09-24 17:48:25 +00002344 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002345 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002346
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002347 // Check for direct and virtual base classes.
2348 const CXXBaseSpecifier *DirectBaseSpec = 0;
2349 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2350 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002351 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2352 BaseType))
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002353 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002354
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002355 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2356 VirtualBaseSpec);
2357
2358 // C++ [base.class.init]p2:
2359 // Unless the mem-initializer-id names a nonstatic data member of the
2360 // constructor's class or a direct or virtual base of that class, the
2361 // mem-initializer is ill-formed.
2362 if (!DirectBaseSpec && !VirtualBaseSpec) {
2363 // If the class has any dependent bases, then it's possible that
2364 // one of those types will resolve to the same type as
2365 // BaseType. Therefore, just treat this as a dependent base
2366 // class initialization. FIXME: Should we try to check the
2367 // initialization anyway? It seems odd.
2368 if (ClassDecl->hasAnyDependentBases())
2369 Dependent = true;
2370 else
2371 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2372 << BaseType << Context.getTypeDeclType(ClassDecl)
2373 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2374 }
2375 }
2376
2377 if (Dependent) {
John McCallf85e1932011-06-15 23:02:42 +00002378 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Sebastian Redl6df65482011-09-24 17:48:25 +00002380 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2381 /*IsVirtual=*/false,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002382 InitRange.getBegin(), Init,
2383 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002384 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002385
2386 // C++ [base.class.init]p2:
2387 // If a mem-initializer-id is ambiguous because it designates both
2388 // a direct non-virtual base class and an inherited virtual base
2389 // class, the mem-initializer is ill-formed.
2390 if (DirectBaseSpec && VirtualBaseSpec)
2391 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002392 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002393
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002394 CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002395 if (!BaseSpec)
2396 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2397
2398 // Initialize the base.
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002399 bool InitList = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002400 Expr **Args = &Init;
2401 unsigned NumArgs = 1;
2402 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002403 InitList = false;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002404 Args = ParenList->getExprs();
2405 NumArgs = ParenList->getNumExprs();
2406 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00002407
2408 InitializedEntity BaseEntity =
2409 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2410 InitializationKind Kind =
2411 InitList ? InitializationKind::CreateDirectList(BaseLoc)
2412 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2413 InitRange.getEnd());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002414 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2415 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
Benjamin Kramer5354e772012-08-23 23:38:35 +00002416 MultiExprArg(Args, NumArgs), 0);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002417 if (BaseInit.isInvalid())
2418 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002419
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002420 CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
Sebastian Redl6df65482011-09-24 17:48:25 +00002421
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002422 // C++0x [class.base.init]p7:
2423 // The initialization of each base and member constitutes a
2424 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002425 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002426 if (BaseInit.isInvalid())
2427 return true;
2428
2429 // If we are in a dependent context, template instantiation will
2430 // perform this type-checking again. Just save the arguments that we
2431 // received in a ParenListExpr.
2432 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2433 // of the information that we have about the base
2434 // initializer. However, deconstructing the ASTs is a dicey process,
2435 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002436 if (CurContext->isDependentContext())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002437 BaseInit = Owned(Init);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002438
Sean Huntcbb67482011-01-08 20:30:50 +00002439 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002440 BaseSpec->isVirtual(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002441 InitRange.getBegin(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002442 BaseInit.takeAs<Expr>(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002443 InitRange.getEnd(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002444}
2445
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002446// Create a static_cast\<T&&>(expr).
2447static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2448 QualType ExprType = E->getType();
2449 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2450 SourceLocation ExprLoc = E->getLocStart();
2451 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2452 TargetType, ExprLoc);
2453
2454 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2455 SourceRange(ExprLoc, ExprLoc),
2456 E->getSourceRange()).take();
2457}
2458
Anders Carlssone5ef7402010-04-23 03:10:23 +00002459/// ImplicitInitializerKind - How an implicit base or member initializer should
2460/// initialize its base or member.
2461enum ImplicitInitializerKind {
2462 IIK_Default,
2463 IIK_Copy,
2464 IIK_Move
2465};
2466
Anders Carlssondefefd22010-04-23 02:00:02 +00002467static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002468BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002469 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002470 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002471 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002472 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002473 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002474 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2475 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002476
John McCall60d7b3a2010-08-24 06:29:42 +00002477 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002478
2479 switch (ImplicitInitKind) {
2480 case IIK_Default: {
2481 InitializationKind InitKind
2482 = InitializationKind::CreateDefault(Constructor->getLocation());
2483 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
Benjamin Kramer5354e772012-08-23 23:38:35 +00002484 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002485 break;
2486 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002487
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002488 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002489 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002490 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002491 ParmVarDecl *Param = Constructor->getParamDecl(0);
2492 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002493
Anders Carlssone5ef7402010-04-23 03:10:23 +00002494 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002495 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002496 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002497 Constructor->getLocation(), ParamType,
2498 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002499
Eli Friedman5f2987c2012-02-02 03:46:19 +00002500 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2501
Anders Carlssonc7957502010-04-24 22:02:54 +00002502 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002503 QualType ArgTy =
2504 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2505 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002506
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002507 if (Moving) {
2508 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2509 }
2510
John McCallf871d0c2010-08-07 06:22:56 +00002511 CXXCastPath BasePath;
2512 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002513 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2514 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002515 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002516 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002517
Anders Carlssone5ef7402010-04-23 03:10:23 +00002518 InitializationKind InitKind
2519 = InitializationKind::CreateDirect(Constructor->getLocation(),
2520 SourceLocation(), SourceLocation());
2521 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2522 &CopyCtorArg, 1);
2523 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002524 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002525 break;
2526 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002527 }
John McCall9ae2f072010-08-23 23:25:46 +00002528
Douglas Gregor53c374f2010-12-07 00:41:46 +00002529 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002530 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002531 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002532
Anders Carlssondefefd22010-04-23 02:00:02 +00002533 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002534 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002535 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2536 SourceLocation()),
2537 BaseSpec->isVirtual(),
2538 SourceLocation(),
2539 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002540 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002541 SourceLocation());
2542
Anders Carlssondefefd22010-04-23 02:00:02 +00002543 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002544}
2545
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002546static bool RefersToRValueRef(Expr *MemRef) {
2547 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2548 return Referenced->getType()->isRValueReferenceType();
2549}
2550
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002551static bool
2552BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002553 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002554 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002555 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002556 if (Field->isInvalidDecl())
2557 return true;
2558
Chandler Carruthf186b542010-06-29 23:50:44 +00002559 SourceLocation Loc = Constructor->getLocation();
2560
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002561 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2562 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002563 ParmVarDecl *Param = Constructor->getParamDecl(0);
2564 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002565
2566 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002567 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2568 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002569
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002570 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002571 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
John McCallf4b88a42012-03-10 09:33:50 +00002572 SourceLocation(), Param, false,
John McCallf89e55a2010-11-18 06:31:45 +00002573 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002574
Eli Friedman5f2987c2012-02-02 03:46:19 +00002575 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2576
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002577 if (Moving) {
2578 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2579 }
2580
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002581 // Build a reference to this field within the parameter.
2582 CXXScopeSpec SS;
2583 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2584 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002585 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2586 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002587 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002588 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002589 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002590 ParamType, Loc,
2591 /*IsArrow=*/false,
2592 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002593 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002594 /*FirstQualifierInScope=*/0,
2595 MemberLookup,
2596 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002597 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002598 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002599
2600 // C++11 [class.copy]p15:
2601 // - if a member m has rvalue reference type T&&, it is direct-initialized
2602 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002603 if (RefersToRValueRef(CtorArg.get())) {
2604 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002605 }
2606
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002607 // When the field we are copying is an array, create index variables for
2608 // each dimension of the array. We use these index variables to subscript
2609 // the source array, and other clients (e.g., CodeGen) will perform the
2610 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002611 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002612 QualType BaseType = Field->getType();
2613 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002614 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002615 while (const ConstantArrayType *Array
2616 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002617 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002618 // Create the iteration variable for this array index.
2619 IdentifierInfo *IterationVarName = 0;
2620 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002621 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002622 llvm::raw_svector_ostream OS(Str);
2623 OS << "__i" << IndexVariables.size();
2624 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2625 }
2626 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002627 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002628 IterationVarName, SizeType,
2629 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002630 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002631 IndexVariables.push_back(IterationVar);
2632
2633 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002634 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002635 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002636 assert(!IterationVarRef.isInvalid() &&
2637 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002638 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2639 assert(!IterationVarRef.isInvalid() &&
2640 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002641
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002642 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002643 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002644 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002645 Loc);
2646 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002647 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002648
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002649 BaseType = Array->getElementType();
2650 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002651
2652 // The array subscript expression is an lvalue, which is wrong for moving.
2653 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002654 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002655
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002656 // Construct the entity that we will be initializing. For an array, this
2657 // will be first element in the array, which may require several levels
2658 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002659 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002660 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002661 if (Indirect)
2662 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2663 else
2664 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002665 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2666 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2667 0,
2668 Entities.back()));
2669
2670 // Direct-initialize to use the copy constructor.
2671 InitializationKind InitKind =
2672 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2673
Sebastian Redl74e611a2011-09-04 18:14:28 +00002674 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002675 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002676 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002677
John McCall60d7b3a2010-08-24 06:29:42 +00002678 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002679 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002680 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002681 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002682 if (MemberInit.isInvalid())
2683 return true;
2684
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002685 if (Indirect) {
2686 assert(IndexVariables.size() == 0 &&
2687 "Indirect field improperly initialized");
2688 CXXMemberInit
2689 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2690 Loc, Loc,
2691 MemberInit.takeAs<Expr>(),
2692 Loc);
2693 } else
2694 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2695 Loc, MemberInit.takeAs<Expr>(),
2696 Loc,
2697 IndexVariables.data(),
2698 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002699 return false;
2700 }
2701
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002702 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2703
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002704 QualType FieldBaseElementType =
2705 SemaRef.Context.getBaseElementType(Field->getType());
2706
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002707 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002708 InitializedEntity InitEntity
2709 = Indirect? InitializedEntity::InitializeMember(Indirect)
2710 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002711 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002712 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002713
2714 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002715 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002716 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002717
Douglas Gregor53c374f2010-12-07 00:41:46 +00002718 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002719 if (MemberInit.isInvalid())
2720 return true;
2721
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002722 if (Indirect)
2723 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2724 Indirect, Loc,
2725 Loc,
2726 MemberInit.get(),
2727 Loc);
2728 else
2729 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2730 Field, Loc, Loc,
2731 MemberInit.get(),
2732 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002733 return false;
2734 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002735
Sean Hunt1f2f3842011-05-17 00:19:05 +00002736 if (!Field->getParent()->isUnion()) {
2737 if (FieldBaseElementType->isReferenceType()) {
2738 SemaRef.Diag(Constructor->getLocation(),
2739 diag::err_uninitialized_member_in_ctor)
2740 << (int)Constructor->isImplicit()
2741 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2742 << 0 << Field->getDeclName();
2743 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2744 return true;
2745 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002746
Sean Hunt1f2f3842011-05-17 00:19:05 +00002747 if (FieldBaseElementType.isConstQualified()) {
2748 SemaRef.Diag(Constructor->getLocation(),
2749 diag::err_uninitialized_member_in_ctor)
2750 << (int)Constructor->isImplicit()
2751 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2752 << 1 << Field->getDeclName();
2753 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2754 return true;
2755 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002756 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002757
David Blaikie4e4d0842012-03-11 07:00:24 +00002758 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002759 FieldBaseElementType->isObjCRetainableType() &&
2760 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2761 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
Douglas Gregor3fe52ff2012-07-23 04:23:39 +00002762 // ARC:
John McCallf85e1932011-06-15 23:02:42 +00002763 // Default-initialize Objective-C pointers to NULL.
2764 CXXMemberInit
2765 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2766 Loc, Loc,
2767 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2768 Loc);
2769 return false;
2770 }
2771
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002772 // Nothing to initialize.
2773 CXXMemberInit = 0;
2774 return false;
2775}
John McCallf1860e52010-05-20 23:23:51 +00002776
2777namespace {
2778struct BaseAndFieldInfo {
2779 Sema &S;
2780 CXXConstructorDecl *Ctor;
2781 bool AnyErrorsInInits;
2782 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002783 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002784 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002785
2786 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2787 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002788 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2789 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002790 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002791 else if (Generated && Ctor->isMoveConstructor())
2792 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002793 else
2794 IIK = IIK_Default;
2795 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002796
2797 bool isImplicitCopyOrMove() const {
2798 switch (IIK) {
2799 case IIK_Copy:
2800 case IIK_Move:
2801 return true;
2802
2803 case IIK_Default:
2804 return false;
2805 }
David Blaikie30263482012-01-20 21:50:17 +00002806
2807 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002808 }
Richard Smith0b8220a2012-08-07 21:30:42 +00002809
2810 bool addFieldInitializer(CXXCtorInitializer *Init) {
2811 AllToInit.push_back(Init);
2812
2813 // Check whether this initializer makes the field "used".
2814 if (Init->getInit() && Init->getInit()->HasSideEffects(S.Context))
2815 S.UnusedPrivateFields.remove(Init->getAnyMember());
2816
2817 return false;
2818 }
John McCallf1860e52010-05-20 23:23:51 +00002819};
2820}
2821
Richard Smitha4950662011-09-19 13:34:43 +00002822/// \brief Determine whether the given indirect field declaration is somewhere
2823/// within an anonymous union.
2824static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2825 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2826 CEnd = F->chain_end();
2827 C != CEnd; ++C)
2828 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2829 if (Record->isUnion())
2830 return true;
2831
2832 return false;
2833}
2834
Douglas Gregorddb21472011-11-02 23:04:16 +00002835/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2836/// array type.
2837static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2838 if (T->isIncompleteArrayType())
2839 return true;
2840
2841 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2842 if (!ArrayT->getSize())
2843 return true;
2844
2845 T = ArrayT->getElementType();
2846 }
2847
2848 return false;
2849}
2850
Richard Smith7a614d82011-06-11 17:19:42 +00002851static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002852 FieldDecl *Field,
2853 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002854
Chandler Carruthe861c602010-06-30 02:59:29 +00002855 // Overwhelmingly common case: we have a direct initializer for this field.
Richard Smith0b8220a2012-08-07 21:30:42 +00002856 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
2857 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002858
Richard Smith0b8220a2012-08-07 21:30:42 +00002859 // C++11 [class.base.init]p8: if the entity is a non-static data member that
Richard Smith7a614d82011-06-11 17:19:42 +00002860 // has a brace-or-equal-initializer, the entity is initialized as specified
2861 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002862 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002863 CXXCtorInitializer *Init;
2864 if (Indirect)
2865 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2866 SourceLocation(),
2867 SourceLocation(), 0,
2868 SourceLocation());
2869 else
2870 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2871 SourceLocation(),
2872 SourceLocation(), 0,
2873 SourceLocation());
Richard Smith0b8220a2012-08-07 21:30:42 +00002874 return Info.addFieldInitializer(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002875 }
2876
Richard Smithc115f632011-09-18 11:14:50 +00002877 // Don't build an implicit initializer for union members if none was
2878 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002879 if (Field->getParent()->isUnion() ||
2880 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002881 return false;
2882
Douglas Gregorddb21472011-11-02 23:04:16 +00002883 // Don't initialize incomplete or zero-length arrays.
2884 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2885 return false;
2886
John McCallf1860e52010-05-20 23:23:51 +00002887 // Don't try to build an implicit initializer if there were semantic
2888 // errors in any of the initializers (and therefore we might be
2889 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002890 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002891 return false;
2892
Sean Huntcbb67482011-01-08 20:30:50 +00002893 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002894 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2895 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002896 return true;
John McCallf1860e52010-05-20 23:23:51 +00002897
Richard Smith0b8220a2012-08-07 21:30:42 +00002898 if (!Init)
2899 return false;
Francois Pichet00eb3f92010-12-04 09:14:42 +00002900
Richard Smith0b8220a2012-08-07 21:30:42 +00002901 return Info.addFieldInitializer(Init);
John McCallf1860e52010-05-20 23:23:51 +00002902}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002903
2904bool
2905Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2906 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002907 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002908 Constructor->setNumCtorInitializers(1);
2909 CXXCtorInitializer **initializer =
2910 new (Context) CXXCtorInitializer*[1];
2911 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2912 Constructor->setCtorInitializers(initializer);
2913
Sean Huntb76af9c2011-05-03 23:05:34 +00002914 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002915 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002916 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2917 }
2918
Sean Huntc1598702011-05-05 00:05:47 +00002919 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002920
Sean Hunt059ce0d2011-05-01 07:04:31 +00002921 return false;
2922}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002923
John McCallb77115d2011-06-17 00:18:42 +00002924bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2925 CXXCtorInitializer **Initializers,
2926 unsigned NumInitializers,
2927 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002928 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002929 // Just store the initializers as written, they will be checked during
2930 // instantiation.
2931 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002932 Constructor->setNumCtorInitializers(NumInitializers);
2933 CXXCtorInitializer **baseOrMemberInitializers =
2934 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002935 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002936 NumInitializers * sizeof(CXXCtorInitializer*));
2937 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002938 }
2939
2940 return false;
2941 }
2942
John McCallf1860e52010-05-20 23:23:51 +00002943 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002944
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002945 // We need to build the initializer AST according to order of construction
2946 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002947 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002948 if (!ClassDecl)
2949 return true;
2950
Eli Friedman80c30da2009-11-09 19:20:36 +00002951 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002952
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002953 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002954 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002955
2956 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002957 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002958 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002959 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002960 }
2961
Anders Carlsson711f34a2010-04-21 19:52:01 +00002962 // Keep track of the direct virtual bases.
2963 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2964 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2965 E = ClassDecl->bases_end(); I != E; ++I) {
2966 if (I->isVirtual())
2967 DirectVBases.insert(I);
2968 }
2969
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002970 // Push virtual bases before others.
2971 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2972 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2973
Sean Huntcbb67482011-01-08 20:30:50 +00002974 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002975 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2976 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002977 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002978 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002979 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002980 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002981 VBase, IsInheritedVirtualBase,
2982 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002983 HadError = true;
2984 continue;
2985 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002986
John McCallf1860e52010-05-20 23:23:51 +00002987 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002988 }
2989 }
Mike Stump1eb44332009-09-09 15:08:12 +00002990
John McCallf1860e52010-05-20 23:23:51 +00002991 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002992 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2993 E = ClassDecl->bases_end(); Base != E; ++Base) {
2994 // Virtuals are in the virtual base list and already constructed.
2995 if (Base->isVirtual())
2996 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002997
Sean Huntcbb67482011-01-08 20:30:50 +00002998 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002999 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3000 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003001 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00003002 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00003003 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00003004 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00003005 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003006 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003007 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00003008 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00003009
John McCallf1860e52010-05-20 23:23:51 +00003010 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003011 }
3012 }
Mike Stump1eb44332009-09-09 15:08:12 +00003013
John McCallf1860e52010-05-20 23:23:51 +00003014 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003015 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3016 MemEnd = ClassDecl->decls_end();
3017 Mem != MemEnd; ++Mem) {
3018 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00003019 // C++ [class.bit]p2:
3020 // A declaration for a bit-field that omits the identifier declares an
3021 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
3022 // initialized.
3023 if (F->isUnnamedBitfield())
3024 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003025
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003026 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003027 // handle anonymous struct/union fields based on their individual
3028 // indirect fields.
3029 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3030 continue;
3031
3032 if (CollectFieldInitializer(*this, Info, F))
3033 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003034 continue;
3035 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003036
3037 // Beyond this point, we only consider default initialization.
3038 if (Info.IIK != IIK_Default)
3039 continue;
3040
3041 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3042 if (F->getType()->isIncompleteArrayType()) {
3043 assert(ClassDecl->hasFlexibleArrayMember() &&
3044 "Incomplete array type is not valid");
3045 continue;
3046 }
3047
Douglas Gregor4dc41c92011-08-10 15:22:55 +00003048 // Initialize each field of an anonymous struct individually.
3049 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3050 HadError = true;
3051
3052 continue;
3053 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00003054 }
Mike Stump1eb44332009-09-09 15:08:12 +00003055
John McCallf1860e52010-05-20 23:23:51 +00003056 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003057 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00003058 Constructor->setNumCtorInitializers(NumInitializers);
3059 CXXCtorInitializer **baseOrMemberInitializers =
3060 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00003061 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00003062 NumInitializers * sizeof(CXXCtorInitializer*));
3063 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00003064
John McCallef027fe2010-03-16 21:39:52 +00003065 // Constructors implicitly reference the base and member
3066 // destructors.
3067 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3068 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003069 }
Eli Friedman80c30da2009-11-09 19:20:36 +00003070
3071 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00003072}
3073
Eli Friedman6347f422009-07-21 19:28:10 +00003074static void *GetKeyForTopLevelField(FieldDecl *Field) {
3075 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00003076 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00003077 if (RT->getDecl()->isAnonymousStructOrUnion())
3078 return static_cast<void *>(RT->getDecl());
3079 }
3080 return static_cast<void *>(Field);
3081}
3082
Anders Carlssonea356fb2010-04-02 05:42:15 +00003083static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00003084 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00003085}
3086
Anders Carlssonea356fb2010-04-02 05:42:15 +00003087static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00003088 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003089 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00003090 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003091
Eli Friedman6347f422009-07-21 19:28:10 +00003092 // For fields injected into the class via declaration of an anonymous union,
3093 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00003094 FieldDecl *Field = Member->getAnyMember();
3095
John McCall3c3ccdb2010-04-10 09:28:51 +00003096 // If the field is a member of an anonymous struct or union, our key
3097 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003098 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003099 if (RD->isAnonymousStructOrUnion()) {
3100 while (true) {
3101 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3102 if (Parent->isAnonymousStructOrUnion())
3103 RD = Parent;
3104 else
3105 break;
3106 }
3107
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003108 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003109 }
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003111 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003112}
3113
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003114static void
3115DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003116 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003117 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003118 unsigned NumInits) {
3119 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003120 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003121
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003122 // Don't check initializers order unless the warning is enabled at the
3123 // location of at least one initializer.
3124 bool ShouldCheckOrder = false;
3125 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003126 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003127 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3128 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003129 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003130 ShouldCheckOrder = true;
3131 break;
3132 }
3133 }
3134 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003135 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003136
John McCalld6ca8da2010-04-10 07:37:23 +00003137 // Build the list of bases and members in the order that they'll
3138 // actually be initialized. The explicit initializers should be in
3139 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003140 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Anders Carlsson071d6102010-04-02 03:38:04 +00003142 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3143
John McCalld6ca8da2010-04-10 07:37:23 +00003144 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003145 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003146 ClassDecl->vbases_begin(),
3147 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003148 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003149
John McCalld6ca8da2010-04-10 07:37:23 +00003150 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003151 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003152 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003153 if (Base->isVirtual())
3154 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003155 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003156 }
Mike Stump1eb44332009-09-09 15:08:12 +00003157
John McCalld6ca8da2010-04-10 07:37:23 +00003158 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003159 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003160 E = ClassDecl->field_end(); Field != E; ++Field) {
3161 if (Field->isUnnamedBitfield())
3162 continue;
3163
David Blaikie581deb32012-06-06 20:45:41 +00003164 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003165 }
3166
John McCalld6ca8da2010-04-10 07:37:23 +00003167 unsigned NumIdealInits = IdealInitKeys.size();
3168 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003169
Sean Huntcbb67482011-01-08 20:30:50 +00003170 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003171 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003172 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003173 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003174
3175 // Scan forward to try to find this initializer in the idealized
3176 // initializers list.
3177 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3178 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003179 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003180
3181 // If we didn't find this initializer, it must be because we
3182 // scanned past it on a previous iteration. That can only
3183 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003184 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003185 Sema::SemaDiagnosticBuilder D =
3186 SemaRef.Diag(PrevInit->getSourceLocation(),
3187 diag::warn_initializer_out_of_order);
3188
Francois Pichet00eb3f92010-12-04 09:14:42 +00003189 if (PrevInit->isAnyMemberInitializer())
3190 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003191 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003192 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003193
Francois Pichet00eb3f92010-12-04 09:14:42 +00003194 if (Init->isAnyMemberInitializer())
3195 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003196 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003197 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003198
3199 // Move back to the initializer's location in the ideal list.
3200 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3201 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003202 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003203
3204 assert(IdealIndex != NumIdealInits &&
3205 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003206 }
John McCalld6ca8da2010-04-10 07:37:23 +00003207
3208 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003209 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003210}
3211
John McCall3c3ccdb2010-04-10 09:28:51 +00003212namespace {
3213bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003214 CXXCtorInitializer *Init,
3215 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003216 if (!PrevInit) {
3217 PrevInit = Init;
3218 return false;
3219 }
3220
3221 if (FieldDecl *Field = Init->getMember())
3222 S.Diag(Init->getSourceLocation(),
3223 diag::err_multiple_mem_initialization)
3224 << Field->getDeclName()
3225 << Init->getSourceRange();
3226 else {
John McCallf4c73712011-01-19 06:33:43 +00003227 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003228 assert(BaseClass && "neither field nor base");
3229 S.Diag(Init->getSourceLocation(),
3230 diag::err_multiple_base_initialization)
3231 << QualType(BaseClass, 0)
3232 << Init->getSourceRange();
3233 }
3234 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3235 << 0 << PrevInit->getSourceRange();
3236
3237 return true;
3238}
3239
Sean Huntcbb67482011-01-08 20:30:50 +00003240typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003241typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3242
3243bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003244 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003245 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003246 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003247 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003248 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003249
3250 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003251 if (Parent->isUnion()) {
3252 UnionEntry &En = Unions[Parent];
3253 if (En.first && En.first != Child) {
3254 S.Diag(Init->getSourceLocation(),
3255 diag::err_multiple_mem_union_initialization)
3256 << Field->getDeclName()
3257 << Init->getSourceRange();
3258 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3259 << 0 << En.second->getSourceRange();
3260 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003261 }
3262 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003263 En.first = Child;
3264 En.second = Init;
3265 }
David Blaikie6fe29652011-11-17 06:01:57 +00003266 if (!Parent->isAnonymousStructOrUnion())
3267 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003268 }
3269
3270 Child = Parent;
3271 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003272 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003273
3274 return false;
3275}
3276}
3277
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003278/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003279void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003280 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003281 CXXCtorInitializer **meminits,
3282 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003283 bool AnyErrors) {
3284 if (!ConstructorDecl)
3285 return;
3286
3287 AdjustDeclIfTemplate(ConstructorDecl);
3288
3289 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003290 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003291
3292 if (!Constructor) {
3293 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3294 return;
3295 }
3296
Sean Huntcbb67482011-01-08 20:30:50 +00003297 CXXCtorInitializer **MemInits =
3298 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003299
3300 // Mapping for the duplicate initializers check.
3301 // For member initializers, this is keyed with a FieldDecl*.
3302 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003303 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003304
3305 // Mapping for the inconsistent anonymous-union initializers check.
3306 RedundantUnionMap MemberUnions;
3307
Anders Carlssonea356fb2010-04-02 05:42:15 +00003308 bool HadError = false;
3309 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003310 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003311
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003312 // Set the source order index.
3313 Init->setSourceOrder(i);
3314
Francois Pichet00eb3f92010-12-04 09:14:42 +00003315 if (Init->isAnyMemberInitializer()) {
3316 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003317 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3318 CheckRedundantUnionInit(*this, Init, MemberUnions))
3319 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003320 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003321 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3322 if (CheckRedundantInit(*this, Init, Members[Key]))
3323 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003324 } else {
3325 assert(Init->isDelegatingInitializer());
3326 // This must be the only initializer
3327 if (i != 0 || NumMemInits > 1) {
3328 Diag(MemInits[0]->getSourceLocation(),
3329 diag::err_delegating_initializer_alone)
3330 << MemInits[0]->getSourceRange();
3331 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003332 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003333 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003334 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003335 // Return immediately as the initializer is set.
3336 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003337 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003338 }
3339
Anders Carlssonea356fb2010-04-02 05:42:15 +00003340 if (HadError)
3341 return;
3342
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003343 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003344
Sean Huntcbb67482011-01-08 20:30:50 +00003345 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003346}
3347
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003348void
John McCallef027fe2010-03-16 21:39:52 +00003349Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3350 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003351 // Ignore dependent contexts. Also ignore unions, since their members never
3352 // have destructors implicitly called.
3353 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003354 return;
John McCall58e6f342010-03-16 05:22:47 +00003355
3356 // FIXME: all the access-control diagnostics are positioned on the
3357 // field/base declaration. That's probably good; that said, the
3358 // user might reasonably want to know why the destructor is being
3359 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003360
Anders Carlsson9f853df2009-11-17 04:44:12 +00003361 // Non-static data members.
3362 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3363 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00003364 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003365 if (Field->isInvalidDecl())
3366 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003367
3368 // Don't destroy incomplete or zero-length arrays.
3369 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3370 continue;
3371
Anders Carlsson9f853df2009-11-17 04:44:12 +00003372 QualType FieldType = Context.getBaseElementType(Field->getType());
3373
3374 const RecordType* RT = FieldType->getAs<RecordType>();
3375 if (!RT)
3376 continue;
3377
3378 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003379 if (FieldClassDecl->isInvalidDecl())
3380 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003381 if (FieldClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003382 continue;
Richard Smith9a561d52012-02-26 09:11:52 +00003383 // The destructor for an implicit anonymous union member is never invoked.
3384 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3385 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003386
Douglas Gregordb89f282010-07-01 22:47:18 +00003387 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003388 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003389 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003390 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003391 << Field->getDeclName()
3392 << FieldType);
3393
Eli Friedman5f2987c2012-02-02 03:46:19 +00003394 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003395 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003396 }
3397
John McCall58e6f342010-03-16 05:22:47 +00003398 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3399
Anders Carlsson9f853df2009-11-17 04:44:12 +00003400 // Bases.
3401 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3402 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003403 // Bases are always records in a well-formed non-dependent class.
3404 const RecordType *RT = Base->getType()->getAs<RecordType>();
3405
3406 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003407 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003408 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003409
John McCall58e6f342010-03-16 05:22:47 +00003410 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003411 // If our base class is invalid, we probably can't get its dtor anyway.
3412 if (BaseClassDecl->isInvalidDecl())
3413 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003414 if (BaseClassDecl->hasIrrelevantDestructor())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003415 continue;
John McCall58e6f342010-03-16 05:22:47 +00003416
Douglas Gregordb89f282010-07-01 22:47:18 +00003417 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003418 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003419
3420 // FIXME: caret should be on the start of the class name
Daniel Dunbar96a00142012-03-09 18:35:03 +00003421 CheckDestructorAccess(Base->getLocStart(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003422 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003423 << Base->getType()
John McCallb9abd8722012-04-07 03:04:20 +00003424 << Base->getSourceRange(),
3425 Context.getTypeDeclType(ClassDecl));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003426
Eli Friedman5f2987c2012-02-02 03:46:19 +00003427 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003428 DiagnoseUseOfDecl(Dtor, Location);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003429 }
3430
3431 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003432 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3433 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003434
3435 // Bases are always records in a well-formed non-dependent class.
John McCall63f55782012-04-09 21:51:56 +00003436 const RecordType *RT = VBase->getType()->castAs<RecordType>();
John McCall58e6f342010-03-16 05:22:47 +00003437
3438 // Ignore direct virtual bases.
3439 if (DirectVirtualBases.count(RT))
3440 continue;
3441
John McCall58e6f342010-03-16 05:22:47 +00003442 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003443 // If our base class is invalid, we probably can't get its dtor anyway.
3444 if (BaseClassDecl->isInvalidDecl())
3445 continue;
Richard Smith213d70b2012-02-18 04:13:32 +00003446 if (BaseClassDecl->hasIrrelevantDestructor())
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003447 continue;
John McCall58e6f342010-03-16 05:22:47 +00003448
Douglas Gregordb89f282010-07-01 22:47:18 +00003449 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003450 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003451 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003452 PDiag(diag::err_access_dtor_vbase)
John McCall63f55782012-04-09 21:51:56 +00003453 << VBase->getType(),
3454 Context.getTypeDeclType(ClassDecl));
John McCall58e6f342010-03-16 05:22:47 +00003455
Eli Friedman5f2987c2012-02-02 03:46:19 +00003456 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith213d70b2012-02-18 04:13:32 +00003457 DiagnoseUseOfDecl(Dtor, Location);
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003458 }
3459}
3460
John McCalld226f652010-08-21 09:40:31 +00003461void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003462 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003463 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003464
Mike Stump1eb44332009-09-09 15:08:12 +00003465 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003466 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003467 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003468}
3469
Mike Stump1eb44332009-09-09 15:08:12 +00003470bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003471 unsigned DiagID, AbstractDiagSelID SelID) {
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003472 class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3473 unsigned DiagID;
3474 AbstractDiagSelID SelID;
3475
3476 public:
3477 NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3478 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3479
3480 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Eli Friedman2217f852012-08-14 02:06:07 +00003481 if (Suppressed) return;
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003482 if (SelID == -1)
3483 S.Diag(Loc, DiagID) << T;
3484 else
3485 S.Diag(Loc, DiagID) << SelID << T;
3486 }
3487 } Diagnoser(DiagID, SelID);
3488
3489 return RequireNonAbstractType(Loc, T, Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003490}
3491
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003492bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003493 TypeDiagnoser &Diagnoser) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003494 if (!getLangOpts().CPlusPlus)
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003495 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003496
Anders Carlsson11f21a02009-03-23 19:10:31 +00003497 if (const ArrayType *AT = Context.getAsArrayType(T))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003498 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Mike Stump1eb44332009-09-09 15:08:12 +00003499
Ted Kremenek6217b802009-07-29 21:53:49 +00003500 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003501 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003502 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003503 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003504
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003505 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003506 return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003507 }
Mike Stump1eb44332009-09-09 15:08:12 +00003508
Ted Kremenek6217b802009-07-29 21:53:49 +00003509 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003510 if (!RT)
3511 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003512
John McCall86ff3082010-02-04 22:26:26 +00003513 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003514
John McCall94c3b562010-08-18 09:41:07 +00003515 // We can't answer whether something is abstract until it has a
3516 // definition. If it's currently being defined, we'll walk back
3517 // over all the declarations when we have a full definition.
3518 const CXXRecordDecl *Def = RD->getDefinition();
3519 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003520 return false;
3521
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003522 if (!RD->isAbstract())
3523 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003524
Douglas Gregor6a26e2e2012-05-04 17:09:59 +00003525 Diagnoser.diagnose(*this, Loc, T);
John McCall94c3b562010-08-18 09:41:07 +00003526 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003527
John McCall94c3b562010-08-18 09:41:07 +00003528 return true;
3529}
3530
3531void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3532 // Check if we've already emitted the list of pure virtual functions
3533 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003534 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003535 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003537 CXXFinalOverriderMap FinalOverriders;
3538 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003539
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003540 // Keep a set of seen pure methods so we won't diagnose the same method
3541 // more than once.
3542 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3543
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003544 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3545 MEnd = FinalOverriders.end();
3546 M != MEnd;
3547 ++M) {
3548 for (OverridingMethods::iterator SO = M->second.begin(),
3549 SOEnd = M->second.end();
3550 SO != SOEnd; ++SO) {
3551 // C++ [class.abstract]p4:
3552 // A class is abstract if it contains or inherits at least one
3553 // pure virtual function for which the final overrider is pure
3554 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003555
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003556 //
3557 if (SO->second.size() != 1)
3558 continue;
3559
3560 if (!SO->second.front().Method->isPure())
3561 continue;
3562
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003563 if (!SeenPureMethods.insert(SO->second.front().Method))
3564 continue;
3565
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003566 Diag(SO->second.front().Method->getLocation(),
3567 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003568 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003569 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003570 }
3571
3572 if (!PureVirtualClassDiagSet)
3573 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3574 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003575}
3576
Anders Carlsson8211eff2009-03-24 01:19:16 +00003577namespace {
John McCall94c3b562010-08-18 09:41:07 +00003578struct AbstractUsageInfo {
3579 Sema &S;
3580 CXXRecordDecl *Record;
3581 CanQualType AbstractType;
3582 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003583
John McCall94c3b562010-08-18 09:41:07 +00003584 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3585 : S(S), Record(Record),
3586 AbstractType(S.Context.getCanonicalType(
3587 S.Context.getTypeDeclType(Record))),
3588 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003589
John McCall94c3b562010-08-18 09:41:07 +00003590 void DiagnoseAbstractType() {
3591 if (Invalid) return;
3592 S.DiagnoseAbstractType(Record);
3593 Invalid = true;
3594 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003595
John McCall94c3b562010-08-18 09:41:07 +00003596 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3597};
3598
3599struct CheckAbstractUsage {
3600 AbstractUsageInfo &Info;
3601 const NamedDecl *Ctx;
3602
3603 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3604 : Info(Info), Ctx(Ctx) {}
3605
3606 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3607 switch (TL.getTypeLocClass()) {
3608#define ABSTRACT_TYPELOC(CLASS, PARENT)
3609#define TYPELOC(CLASS, PARENT) \
3610 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3611#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003612 }
John McCall94c3b562010-08-18 09:41:07 +00003613 }
Mike Stump1eb44332009-09-09 15:08:12 +00003614
John McCall94c3b562010-08-18 09:41:07 +00003615 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3616 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3617 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003618 if (!TL.getArg(I))
3619 continue;
3620
John McCall94c3b562010-08-18 09:41:07 +00003621 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3622 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003623 }
John McCall94c3b562010-08-18 09:41:07 +00003624 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003625
John McCall94c3b562010-08-18 09:41:07 +00003626 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3627 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3628 }
Mike Stump1eb44332009-09-09 15:08:12 +00003629
John McCall94c3b562010-08-18 09:41:07 +00003630 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3631 // Visit the type parameters from a permissive context.
3632 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3633 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3634 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3635 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3636 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3637 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003638 }
John McCall94c3b562010-08-18 09:41:07 +00003639 }
Mike Stump1eb44332009-09-09 15:08:12 +00003640
John McCall94c3b562010-08-18 09:41:07 +00003641 // Visit pointee types from a permissive context.
3642#define CheckPolymorphic(Type) \
3643 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3644 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3645 }
3646 CheckPolymorphic(PointerTypeLoc)
3647 CheckPolymorphic(ReferenceTypeLoc)
3648 CheckPolymorphic(MemberPointerTypeLoc)
3649 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003650 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003651
John McCall94c3b562010-08-18 09:41:07 +00003652 /// Handle all the types we haven't given a more specific
3653 /// implementation for above.
3654 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3655 // Every other kind of type that we haven't called out already
3656 // that has an inner type is either (1) sugar or (2) contains that
3657 // inner type in some way as a subobject.
3658 if (TypeLoc Next = TL.getNextTypeLoc())
3659 return Visit(Next, Sel);
3660
3661 // If there's no inner type and we're in a permissive context,
3662 // don't diagnose.
3663 if (Sel == Sema::AbstractNone) return;
3664
3665 // Check whether the type matches the abstract type.
3666 QualType T = TL.getType();
3667 if (T->isArrayType()) {
3668 Sel = Sema::AbstractArrayType;
3669 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003670 }
John McCall94c3b562010-08-18 09:41:07 +00003671 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3672 if (CT != Info.AbstractType) return;
3673
3674 // It matched; do some magic.
3675 if (Sel == Sema::AbstractArrayType) {
3676 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3677 << T << TL.getSourceRange();
3678 } else {
3679 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3680 << Sel << T << TL.getSourceRange();
3681 }
3682 Info.DiagnoseAbstractType();
3683 }
3684};
3685
3686void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3687 Sema::AbstractDiagSelID Sel) {
3688 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3689}
3690
3691}
3692
3693/// Check for invalid uses of an abstract type in a method declaration.
3694static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3695 CXXMethodDecl *MD) {
3696 // No need to do the check on definitions, which require that
3697 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003698 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003699 return;
3700
3701 // For safety's sake, just ignore it if we don't have type source
3702 // information. This should never happen for non-implicit methods,
3703 // but...
3704 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3705 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3706}
3707
3708/// Check for invalid uses of an abstract type within a class definition.
3709static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3710 CXXRecordDecl *RD) {
3711 for (CXXRecordDecl::decl_iterator
3712 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3713 Decl *D = *I;
3714 if (D->isImplicit()) continue;
3715
3716 // Methods and method templates.
3717 if (isa<CXXMethodDecl>(D)) {
3718 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3719 } else if (isa<FunctionTemplateDecl>(D)) {
3720 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3721 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3722
3723 // Fields and static variables.
3724 } else if (isa<FieldDecl>(D)) {
3725 FieldDecl *FD = cast<FieldDecl>(D);
3726 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3727 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3728 } else if (isa<VarDecl>(D)) {
3729 VarDecl *VD = cast<VarDecl>(D);
3730 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3731 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3732
3733 // Nested classes and class templates.
3734 } else if (isa<CXXRecordDecl>(D)) {
3735 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3736 } else if (isa<ClassTemplateDecl>(D)) {
3737 CheckAbstractClassUsage(Info,
3738 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3739 }
3740 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003741}
3742
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003743/// \brief Perform semantic checks on a class definition that has been
3744/// completing, introducing implicitly-declared members, checking for
3745/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003746void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003747 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003748 return;
3749
John McCall94c3b562010-08-18 09:41:07 +00003750 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3751 AbstractUsageInfo Info(*this, Record);
3752 CheckAbstractClassUsage(Info, Record);
3753 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003754
3755 // If this is not an aggregate type and has no user-declared constructor,
3756 // complain about any non-static data members of reference or const scalar
3757 // type, since they will never get initializers.
3758 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregor5e058eb2012-02-09 02:20:38 +00003759 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3760 !Record->isLambda()) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003761 bool Complained = false;
3762 for (RecordDecl::field_iterator F = Record->field_begin(),
3763 FEnd = Record->field_end();
3764 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003765 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003766 continue;
3767
Douglas Gregor325e5932010-04-15 00:00:53 +00003768 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003769 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003770 if (!Complained) {
3771 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3772 << Record->getTagKind() << Record;
3773 Complained = true;
3774 }
3775
3776 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3777 << F->getType()->isReferenceType()
3778 << F->getDeclName();
3779 }
3780 }
3781 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003782
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003783 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003784 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003785
3786 if (Record->getIdentifier()) {
3787 // C++ [class.mem]p13:
3788 // If T is the name of a class, then each of the following shall have a
3789 // name different from T:
3790 // - every member of every anonymous union that is a member of class T.
3791 //
3792 // C++ [class.mem]p14:
3793 // In addition, if class T has a user-declared constructor (12.1), every
3794 // non-static data member of class T shall have a name different from T.
3795 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003796 R.first != R.second; ++R.first) {
3797 NamedDecl *D = *R.first;
3798 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3799 isa<IndirectFieldDecl>(D)) {
3800 Diag(D->getLocation(), diag::err_member_name_of_class)
3801 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003802 break;
3803 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003804 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003805 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003806
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003807 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003808 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003809 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003810 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003811 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3812 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3813 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003814
3815 // See if a method overloads virtual methods in a base
3816 /// class without overriding any.
3817 if (!Record->isDependentType()) {
3818 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3819 MEnd = Record->method_end();
3820 M != MEnd; ++M) {
David Blaikie262bc182012-04-30 02:36:29 +00003821 if (!M->isStatic())
David Blaikie581deb32012-06-06 20:45:41 +00003822 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003823 }
3824 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003825
Richard Smith9f569cc2011-10-01 02:31:28 +00003826 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3827 // function that is not a constructor declares that member function to be
3828 // const. [...] The class of which that function is a member shall be
3829 // a literal type.
3830 //
Richard Smith9f569cc2011-10-01 02:31:28 +00003831 // If the class has virtual bases, any constexpr members will already have
3832 // been diagnosed by the checks performed on the member declaration, so
3833 // suppress this (less useful) diagnostic.
3834 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3835 !Record->isLiteral() && !Record->getNumVBases()) {
3836 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3837 MEnd = Record->method_end();
3838 M != MEnd; ++M) {
Richard Smith86c3ae42012-02-13 03:54:03 +00003839 if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003840 switch (Record->getTemplateSpecializationKind()) {
3841 case TSK_ImplicitInstantiation:
3842 case TSK_ExplicitInstantiationDeclaration:
3843 case TSK_ExplicitInstantiationDefinition:
3844 // If a template instantiates to a non-literal type, but its members
3845 // instantiate to constexpr functions, the template is technically
Richard Smith86c3ae42012-02-13 03:54:03 +00003846 // ill-formed, but we allow it for sanity.
Richard Smith9f569cc2011-10-01 02:31:28 +00003847 continue;
3848
3849 case TSK_Undeclared:
3850 case TSK_ExplicitSpecialization:
David Blaikie262bc182012-04-30 02:36:29 +00003851 RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
Douglas Gregorf502d8e2012-05-04 16:48:41 +00003852 diag::err_constexpr_method_non_literal);
Richard Smith9f569cc2011-10-01 02:31:28 +00003853 break;
3854 }
3855
3856 // Only produce one error per class.
3857 break;
3858 }
3859 }
3860 }
3861
Sebastian Redlf677ea32011-02-05 19:23:19 +00003862 // Declare inherited constructors. We do this eagerly here because:
3863 // - The standard requires an eager diagnostic for conflicting inherited
3864 // constructors from different classes.
3865 // - The lazy declaration of the other implicit constructors is so as to not
3866 // waste space and performance on classes that are not meant to be
3867 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3868 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003869 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003870}
3871
3872void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003873 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3874 ME = Record->method_end();
Richard Smith3003e1d2012-05-15 04:39:51 +00003875 MI != ME; ++MI)
3876 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
David Blaikie581deb32012-06-06 20:45:41 +00003877 CheckExplicitlyDefaultedSpecialMember(*MI);
Sean Hunt001cad92011-05-10 00:49:42 +00003878}
3879
Richard Smith7756afa2012-06-10 05:43:50 +00003880/// Is the special member function which would be selected to perform the
3881/// specified operation on the specified class type a constexpr constructor?
3882static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3883 Sema::CXXSpecialMember CSM,
3884 bool ConstArg) {
3885 Sema::SpecialMemberOverloadResult *SMOR =
3886 S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
3887 false, false, false, false);
3888 if (!SMOR || !SMOR->getMethod())
3889 // A constructor we wouldn't select can't be "involved in initializing"
3890 // anything.
3891 return true;
3892 return SMOR->getMethod()->isConstexpr();
3893}
3894
3895/// Determine whether the specified special member function would be constexpr
3896/// if it were implicitly defined.
3897static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3898 Sema::CXXSpecialMember CSM,
3899 bool ConstArg) {
3900 if (!S.getLangOpts().CPlusPlus0x)
3901 return false;
3902
3903 // C++11 [dcl.constexpr]p4:
3904 // In the definition of a constexpr constructor [...]
3905 switch (CSM) {
3906 case Sema::CXXDefaultConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003907 // Since default constructor lookup is essentially trivial (and cannot
3908 // involve, for instance, template instantiation), we compute whether a
3909 // defaulted default constructor is constexpr directly within CXXRecordDecl.
3910 //
3911 // This is important for performance; we need to know whether the default
3912 // constructor is constexpr to determine whether the type is a literal type.
3913 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
3914
Richard Smith7756afa2012-06-10 05:43:50 +00003915 case Sema::CXXCopyConstructor:
3916 case Sema::CXXMoveConstructor:
Richard Smithd3861ce2012-06-10 07:07:24 +00003917 // For copy or move constructors, we need to perform overload resolution.
Richard Smith7756afa2012-06-10 05:43:50 +00003918 break;
3919
3920 case Sema::CXXCopyAssignment:
3921 case Sema::CXXMoveAssignment:
3922 case Sema::CXXDestructor:
3923 case Sema::CXXInvalid:
3924 return false;
3925 }
3926
3927 // -- if the class is a non-empty union, or for each non-empty anonymous
3928 // union member of a non-union class, exactly one non-static data member
3929 // shall be initialized; [DR1359]
Richard Smithd3861ce2012-06-10 07:07:24 +00003930 //
3931 // If we squint, this is guaranteed, since exactly one non-static data member
3932 // will be initialized (if the constructor isn't deleted), we just don't know
3933 // which one.
Richard Smith7756afa2012-06-10 05:43:50 +00003934 if (ClassDecl->isUnion())
Richard Smithd3861ce2012-06-10 07:07:24 +00003935 return true;
Richard Smith7756afa2012-06-10 05:43:50 +00003936
3937 // -- the class shall not have any virtual base classes;
3938 if (ClassDecl->getNumVBases())
3939 return false;
3940
3941 // -- every constructor involved in initializing [...] base class
3942 // sub-objects shall be a constexpr constructor;
3943 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
3944 BEnd = ClassDecl->bases_end();
3945 B != BEnd; ++B) {
3946 const RecordType *BaseType = B->getType()->getAs<RecordType>();
3947 if (!BaseType) continue;
3948
3949 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3950 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
3951 return false;
3952 }
3953
3954 // -- every constructor involved in initializing non-static data members
3955 // [...] shall be a constexpr constructor;
3956 // -- every non-static data member and base class sub-object shall be
3957 // initialized
3958 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
3959 FEnd = ClassDecl->field_end();
3960 F != FEnd; ++F) {
3961 if (F->isInvalidDecl())
3962 continue;
Richard Smithd3861ce2012-06-10 07:07:24 +00003963 if (const RecordType *RecordTy =
3964 S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Richard Smith7756afa2012-06-10 05:43:50 +00003965 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
3966 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
3967 return false;
Richard Smith7756afa2012-06-10 05:43:50 +00003968 }
3969 }
3970
3971 // All OK, it's constexpr!
3972 return true;
3973}
3974
Richard Smithb9d0b762012-07-27 04:22:15 +00003975static Sema::ImplicitExceptionSpecification
3976computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
3977 switch (S.getSpecialMember(MD)) {
3978 case Sema::CXXDefaultConstructor:
3979 return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
3980 case Sema::CXXCopyConstructor:
3981 return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
3982 case Sema::CXXCopyAssignment:
3983 return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
3984 case Sema::CXXMoveConstructor:
3985 return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
3986 case Sema::CXXMoveAssignment:
3987 return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
3988 case Sema::CXXDestructor:
3989 return S.ComputeDefaultedDtorExceptionSpec(MD);
3990 case Sema::CXXInvalid:
3991 break;
3992 }
3993 llvm_unreachable("only special members have implicit exception specs");
3994}
3995
Richard Smithdd25e802012-07-30 23:48:14 +00003996static void
3997updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
3998 const Sema::ImplicitExceptionSpecification &ExceptSpec) {
3999 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4000 ExceptSpec.getEPI(EPI);
4001 const FunctionProtoType *NewFPT = cast<FunctionProtoType>(
4002 S.Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
4003 FPT->getNumArgs(), EPI));
4004 FD->setType(QualType(NewFPT, 0));
4005}
4006
Richard Smithb9d0b762012-07-27 04:22:15 +00004007void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4008 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4009 if (FPT->getExceptionSpecType() != EST_Unevaluated)
4010 return;
4011
Richard Smithdd25e802012-07-30 23:48:14 +00004012 // Evaluate the exception specification.
4013 ImplicitExceptionSpecification ExceptSpec =
4014 computeImplicitExceptionSpec(*this, Loc, MD);
4015
4016 // Update the type of the special member to use it.
4017 updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4018
4019 // A user-provided destructor can be defined outside the class. When that
4020 // happens, be sure to update the exception specification on both
4021 // declarations.
4022 const FunctionProtoType *CanonicalFPT =
4023 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4024 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4025 updateExceptionSpec(*this, MD->getCanonicalDecl(),
4026 CanonicalFPT, ExceptSpec);
Richard Smithb9d0b762012-07-27 04:22:15 +00004027}
4028
4029static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4030static bool isImplicitCopyAssignmentArgConst(Sema &S, CXXRecordDecl *ClassDecl);
4031
Richard Smith3003e1d2012-05-15 04:39:51 +00004032void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4033 CXXRecordDecl *RD = MD->getParent();
4034 CXXSpecialMember CSM = getSpecialMember(MD);
Sean Hunt001cad92011-05-10 00:49:42 +00004035
Richard Smith3003e1d2012-05-15 04:39:51 +00004036 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4037 "not an explicitly-defaulted special member");
Sean Hunt49634cf2011-05-13 06:10:58 +00004038
4039 // Whether this was the first-declared instance of the constructor.
Richard Smith3003e1d2012-05-15 04:39:51 +00004040 // This affects whether we implicitly add an exception spec and constexpr.
Sean Hunt2b188082011-05-14 05:23:28 +00004041 bool First = MD == MD->getCanonicalDecl();
4042
4043 bool HadError = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004044
4045 // C++11 [dcl.fct.def.default]p1:
4046 // A function that is explicitly defaulted shall
4047 // -- be a special member function (checked elsewhere),
4048 // -- have the same type (except for ref-qualifiers, and except that a
4049 // copy operation can take a non-const reference) as an implicit
4050 // declaration, and
4051 // -- not have default arguments.
4052 unsigned ExpectedParams = 1;
4053 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4054 ExpectedParams = 0;
4055 if (MD->getNumParams() != ExpectedParams) {
4056 // This also checks for default arguments: a copy or move constructor with a
4057 // default argument is classified as a default constructor, and assignment
4058 // operations and destructors can't have default arguments.
4059 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4060 << CSM << MD->getSourceRange();
Sean Hunt2b188082011-05-14 05:23:28 +00004061 HadError = true;
4062 }
4063
Richard Smith3003e1d2012-05-15 04:39:51 +00004064 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
Sean Hunt2b188082011-05-14 05:23:28 +00004065
Richard Smithb9d0b762012-07-27 04:22:15 +00004066 // Compute argument constness, constexpr, and triviality.
Richard Smith7756afa2012-06-10 05:43:50 +00004067 bool CanHaveConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004068 bool Trivial;
4069 switch (CSM) {
4070 case CXXDefaultConstructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004071 Trivial = RD->hasTrivialDefaultConstructor();
4072 break;
4073 case CXXCopyConstructor:
Richard Smithb9d0b762012-07-27 04:22:15 +00004074 CanHaveConstParam = isImplicitCopyCtorArgConst(*this, RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004075 Trivial = RD->hasTrivialCopyConstructor();
4076 break;
4077 case CXXCopyAssignment:
Richard Smithb9d0b762012-07-27 04:22:15 +00004078 CanHaveConstParam = isImplicitCopyAssignmentArgConst(*this, RD);
Richard Smith3003e1d2012-05-15 04:39:51 +00004079 Trivial = RD->hasTrivialCopyAssignment();
4080 break;
4081 case CXXMoveConstructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004082 Trivial = RD->hasTrivialMoveConstructor();
4083 break;
4084 case CXXMoveAssignment:
Richard Smith3003e1d2012-05-15 04:39:51 +00004085 Trivial = RD->hasTrivialMoveAssignment();
4086 break;
4087 case CXXDestructor:
Richard Smith3003e1d2012-05-15 04:39:51 +00004088 Trivial = RD->hasTrivialDestructor();
4089 break;
4090 case CXXInvalid:
4091 llvm_unreachable("non-special member explicitly defaulted!");
4092 }
Sean Hunt2b188082011-05-14 05:23:28 +00004093
Richard Smith3003e1d2012-05-15 04:39:51 +00004094 QualType ReturnType = Context.VoidTy;
4095 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4096 // Check for return type matching.
4097 ReturnType = Type->getResultType();
4098 QualType ExpectedReturnType =
4099 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4100 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4101 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4102 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4103 HadError = true;
4104 }
4105
4106 // A defaulted special member cannot have cv-qualifiers.
4107 if (Type->getTypeQuals()) {
4108 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4109 << (CSM == CXXMoveAssignment);
4110 HadError = true;
4111 }
4112 }
4113
4114 // Check for parameter type matching.
4115 QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
Richard Smith7756afa2012-06-10 05:43:50 +00004116 bool HasConstParam = false;
Richard Smith3003e1d2012-05-15 04:39:51 +00004117 if (ExpectedParams && ArgType->isReferenceType()) {
4118 // Argument must be reference to possibly-const T.
4119 QualType ReferentType = ArgType->getPointeeType();
Richard Smith7756afa2012-06-10 05:43:50 +00004120 HasConstParam = ReferentType.isConstQualified();
Richard Smith3003e1d2012-05-15 04:39:51 +00004121
4122 if (ReferentType.isVolatileQualified()) {
4123 Diag(MD->getLocation(),
4124 diag::err_defaulted_special_member_volatile_param) << CSM;
4125 HadError = true;
4126 }
4127
Richard Smith7756afa2012-06-10 05:43:50 +00004128 if (HasConstParam && !CanHaveConstParam) {
Richard Smith3003e1d2012-05-15 04:39:51 +00004129 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4130 Diag(MD->getLocation(),
4131 diag::err_defaulted_special_member_copy_const_param)
4132 << (CSM == CXXCopyAssignment);
4133 // FIXME: Explain why this special member can't be const.
4134 } else {
4135 Diag(MD->getLocation(),
4136 diag::err_defaulted_special_member_move_const_param)
4137 << (CSM == CXXMoveAssignment);
4138 }
4139 HadError = true;
4140 }
4141
4142 // If a function is explicitly defaulted on its first declaration, it shall
4143 // have the same parameter type as if it had been implicitly declared.
4144 // (Presumably this is to prevent it from being trivial?)
Richard Smith7756afa2012-06-10 05:43:50 +00004145 if (!HasConstParam && CanHaveConstParam && First)
Richard Smith3003e1d2012-05-15 04:39:51 +00004146 Diag(MD->getLocation(),
4147 diag::err_defaulted_special_member_copy_non_const_param)
4148 << (CSM == CXXCopyAssignment);
4149 } else if (ExpectedParams) {
4150 // A copy assignment operator can take its argument by value, but a
4151 // defaulted one cannot.
4152 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
Sean Huntbe631222011-05-17 20:44:43 +00004153 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004154 HadError = true;
4155 }
Sean Huntbe631222011-05-17 20:44:43 +00004156
Richard Smithb9d0b762012-07-27 04:22:15 +00004157 // Rebuild the type with the implicit exception specification added, if we
4158 // are going to need it.
4159 const FunctionProtoType *ImplicitType = 0;
4160 if (First || Type->hasExceptionSpec()) {
4161 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4162 computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4163 ImplicitType = cast<FunctionProtoType>(
4164 Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4165 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004166
Richard Smith61802452011-12-22 02:22:31 +00004167 // C++11 [dcl.fct.def.default]p2:
4168 // An explicitly-defaulted function may be declared constexpr only if it
4169 // would have been implicitly declared as constexpr,
Richard Smith3003e1d2012-05-15 04:39:51 +00004170 // Do not apply this rule to members of class templates, since core issue 1358
4171 // makes such functions always instantiate to constexpr functions. For
4172 // non-constructors, this is checked elsewhere.
Richard Smith7756afa2012-06-10 05:43:50 +00004173 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4174 HasConstParam);
Richard Smith3003e1d2012-05-15 04:39:51 +00004175 if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4176 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4177 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
Richard Smith7756afa2012-06-10 05:43:50 +00004178 // FIXME: Explain why the constructor can't be constexpr.
Richard Smith3003e1d2012-05-15 04:39:51 +00004179 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004180 }
4181 // and may have an explicit exception-specification only if it is compatible
4182 // with the exception-specification on the implicit declaration.
Richard Smith3003e1d2012-05-15 04:39:51 +00004183 if (Type->hasExceptionSpec() &&
4184 CheckEquivalentExceptionSpec(
4185 PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4186 PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4187 HadError = true;
Richard Smith61802452011-12-22 02:22:31 +00004188
4189 // If a function is explicitly defaulted on its first declaration,
4190 if (First) {
4191 // -- it is implicitly considered to be constexpr if the implicit
4192 // definition would be,
Richard Smith3003e1d2012-05-15 04:39:51 +00004193 MD->setConstexpr(Constexpr);
Richard Smith61802452011-12-22 02:22:31 +00004194
Richard Smith3003e1d2012-05-15 04:39:51 +00004195 // -- it is implicitly considered to have the same exception-specification
4196 // as if it had been implicitly declared,
4197 MD->setType(QualType(ImplicitType, 0));
Richard Smithe653ba22012-02-26 00:31:33 +00004198
4199 // Such a function is also trivial if the implicitly-declared function
4200 // would have been.
Richard Smith3003e1d2012-05-15 04:39:51 +00004201 MD->setTrivial(Trivial);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004202 }
4203
Richard Smith3003e1d2012-05-15 04:39:51 +00004204 if (ShouldDeleteSpecialMember(MD, CSM)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004205 if (First) {
4206 MD->setDeletedAsWritten();
4207 } else {
Richard Smith3003e1d2012-05-15 04:39:51 +00004208 // C++11 [dcl.fct.def.default]p4:
4209 // [For a] user-provided explicitly-defaulted function [...] if such a
4210 // function is implicitly defined as deleted, the program is ill-formed.
4211 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4212 HadError = true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004213 }
4214 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004215
Richard Smith3003e1d2012-05-15 04:39:51 +00004216 if (HadError)
4217 MD->setInvalidDecl();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004218}
4219
Richard Smith7d5088a2012-02-18 02:02:13 +00004220namespace {
4221struct SpecialMemberDeletionInfo {
4222 Sema &S;
4223 CXXMethodDecl *MD;
4224 Sema::CXXSpecialMember CSM;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004225 bool Diagnose;
Richard Smith7d5088a2012-02-18 02:02:13 +00004226
4227 // Properties of the special member, computed for convenience.
4228 bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4229 SourceLocation Loc;
4230
4231 bool AllFieldsAreConst;
4232
4233 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004234 Sema::CXXSpecialMember CSM, bool Diagnose)
4235 : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
Richard Smith7d5088a2012-02-18 02:02:13 +00004236 IsConstructor(false), IsAssignment(false), IsMove(false),
4237 ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4238 AllFieldsAreConst(true) {
4239 switch (CSM) {
4240 case Sema::CXXDefaultConstructor:
4241 case Sema::CXXCopyConstructor:
4242 IsConstructor = true;
4243 break;
4244 case Sema::CXXMoveConstructor:
4245 IsConstructor = true;
4246 IsMove = true;
4247 break;
4248 case Sema::CXXCopyAssignment:
4249 IsAssignment = true;
4250 break;
4251 case Sema::CXXMoveAssignment:
4252 IsAssignment = true;
4253 IsMove = true;
4254 break;
4255 case Sema::CXXDestructor:
4256 break;
4257 case Sema::CXXInvalid:
4258 llvm_unreachable("invalid special member kind");
4259 }
4260
4261 if (MD->getNumParams()) {
4262 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4263 VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4264 }
4265 }
4266
4267 bool inUnion() const { return MD->getParent()->isUnion(); }
4268
4269 /// Look up the corresponding special member in the given class.
Richard Smith517bb842012-07-18 03:51:16 +00004270 Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4271 unsigned Quals) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004272 unsigned TQ = MD->getTypeQualifiers();
Richard Smith517bb842012-07-18 03:51:16 +00004273 // cv-qualifiers on class members don't affect default ctor / dtor calls.
4274 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4275 Quals = 0;
4276 return S.LookupSpecialMember(Class, CSM,
4277 ConstArg || (Quals & Qualifiers::Const),
4278 VolatileArg || (Quals & Qualifiers::Volatile),
Richard Smith7d5088a2012-02-18 02:02:13 +00004279 MD->getRefQualifier() == RQ_RValue,
4280 TQ & Qualifiers::Const,
4281 TQ & Qualifiers::Volatile);
4282 }
4283
Richard Smith6c4c36c2012-03-30 20:53:28 +00004284 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
Richard Smith9a561d52012-02-26 09:11:52 +00004285
Richard Smith6c4c36c2012-03-30 20:53:28 +00004286 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
Richard Smith7d5088a2012-02-18 02:02:13 +00004287 bool shouldDeleteForField(FieldDecl *FD);
4288 bool shouldDeleteForAllConstMembers();
Richard Smith6c4c36c2012-03-30 20:53:28 +00004289
Richard Smith517bb842012-07-18 03:51:16 +00004290 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4291 unsigned Quals);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004292 bool shouldDeleteForSubobjectCall(Subobject Subobj,
4293 Sema::SpecialMemberOverloadResult *SMOR,
4294 bool IsDtorCallInCtor);
John McCall12d8d802012-04-09 20:53:23 +00004295
4296 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
Richard Smith7d5088a2012-02-18 02:02:13 +00004297};
4298}
4299
John McCall12d8d802012-04-09 20:53:23 +00004300/// Is the given special member inaccessible when used on the given
4301/// sub-object.
4302bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4303 CXXMethodDecl *target) {
4304 /// If we're operating on a base class, the object type is the
4305 /// type of this special member.
4306 QualType objectTy;
4307 AccessSpecifier access = target->getAccess();;
4308 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4309 objectTy = S.Context.getTypeDeclType(MD->getParent());
4310 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4311
4312 // If we're operating on a field, the object type is the type of the field.
4313 } else {
4314 objectTy = S.Context.getTypeDeclType(target->getParent());
4315 }
4316
4317 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4318}
4319
Richard Smith6c4c36c2012-03-30 20:53:28 +00004320/// Check whether we should delete a special member due to the implicit
4321/// definition containing a call to a special member of a subobject.
4322bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4323 Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4324 bool IsDtorCallInCtor) {
4325 CXXMethodDecl *Decl = SMOR->getMethod();
4326 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4327
4328 int DiagKind = -1;
4329
4330 if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4331 DiagKind = !Decl ? 0 : 1;
4332 else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4333 DiagKind = 2;
John McCall12d8d802012-04-09 20:53:23 +00004334 else if (!isAccessible(Subobj, Decl))
Richard Smith6c4c36c2012-03-30 20:53:28 +00004335 DiagKind = 3;
4336 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4337 !Decl->isTrivial()) {
4338 // A member of a union must have a trivial corresponding special member.
4339 // As a weird special case, a destructor call from a union's constructor
4340 // must be accessible and non-deleted, but need not be trivial. Such a
4341 // destructor is never actually called, but is semantically checked as
4342 // if it were.
4343 DiagKind = 4;
4344 }
4345
4346 if (DiagKind == -1)
4347 return false;
4348
4349 if (Diagnose) {
4350 if (Field) {
4351 S.Diag(Field->getLocation(),
4352 diag::note_deleted_special_member_class_subobject)
4353 << CSM << MD->getParent() << /*IsField*/true
4354 << Field << DiagKind << IsDtorCallInCtor;
4355 } else {
4356 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4357 S.Diag(Base->getLocStart(),
4358 diag::note_deleted_special_member_class_subobject)
4359 << CSM << MD->getParent() << /*IsField*/false
4360 << Base->getType() << DiagKind << IsDtorCallInCtor;
4361 }
4362
4363 if (DiagKind == 1)
4364 S.NoteDeletedFunction(Decl);
4365 // FIXME: Explain inaccessibility if DiagKind == 3.
4366 }
4367
4368 return true;
4369}
4370
Richard Smith9a561d52012-02-26 09:11:52 +00004371/// Check whether we should delete a special member function due to having a
Richard Smith517bb842012-07-18 03:51:16 +00004372/// direct or virtual base class or non-static data member of class type M.
Richard Smith9a561d52012-02-26 09:11:52 +00004373bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
Richard Smith517bb842012-07-18 03:51:16 +00004374 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
Richard Smith6c4c36c2012-03-30 20:53:28 +00004375 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
Richard Smith7d5088a2012-02-18 02:02:13 +00004376
4377 // C++11 [class.ctor]p5:
Richard Smithdf8dc862012-03-29 19:00:10 +00004378 // -- any direct or virtual base class, or non-static data member with no
4379 // brace-or-equal-initializer, has class type M (or array thereof) and
Richard Smith7d5088a2012-02-18 02:02:13 +00004380 // either M has no default constructor or overload resolution as applied
4381 // to M's default constructor results in an ambiguity or in a function
4382 // that is deleted or inaccessible
4383 // C++11 [class.copy]p11, C++11 [class.copy]p23:
4384 // -- a direct or virtual base class B that cannot be copied/moved because
4385 // overload resolution, as applied to B's corresponding special member,
4386 // results in an ambiguity or a function that is deleted or inaccessible
4387 // from the defaulted special member
Richard Smith6c4c36c2012-03-30 20:53:28 +00004388 // C++11 [class.dtor]p5:
4389 // -- any direct or virtual base class [...] has a type with a destructor
4390 // that is deleted or inaccessible
4391 if (!(CSM == Sema::CXXDefaultConstructor &&
Richard Smith1c931be2012-04-02 18:40:40 +00004392 Field && Field->hasInClassInitializer()) &&
Richard Smith517bb842012-07-18 03:51:16 +00004393 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
Richard Smith1c931be2012-04-02 18:40:40 +00004394 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004395
Richard Smith6c4c36c2012-03-30 20:53:28 +00004396 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4397 // -- any direct or virtual base class or non-static data member has a
4398 // type with a destructor that is deleted or inaccessible
4399 if (IsConstructor) {
4400 Sema::SpecialMemberOverloadResult *SMOR =
4401 S.LookupSpecialMember(Class, Sema::CXXDestructor,
4402 false, false, false, false, false);
4403 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4404 return true;
4405 }
4406
Richard Smith9a561d52012-02-26 09:11:52 +00004407 return false;
4408}
4409
4410/// Check whether we should delete a special member function due to the class
4411/// having a particular direct or virtual base class.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004412bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
Richard Smith1c931be2012-04-02 18:40:40 +00004413 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
Richard Smith517bb842012-07-18 03:51:16 +00004414 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
Richard Smith7d5088a2012-02-18 02:02:13 +00004415}
4416
4417/// Check whether we should delete a special member function due to the class
4418/// having a particular non-static data member.
4419bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4420 QualType FieldType = S.Context.getBaseElementType(FD->getType());
4421 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4422
4423 if (CSM == Sema::CXXDefaultConstructor) {
4424 // For a default constructor, all references must be initialized in-class
4425 // and, if a union, it must have a non-const member.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004426 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4427 if (Diagnose)
4428 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4429 << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004430 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004431 }
Richard Smith79363f52012-02-27 06:07:25 +00004432 // C++11 [class.ctor]p5: any non-variant non-static data member of
4433 // const-qualified type (or array thereof) with no
4434 // brace-or-equal-initializer does not have a user-provided default
4435 // constructor.
4436 if (!inUnion() && FieldType.isConstQualified() &&
4437 !FD->hasInClassInitializer() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004438 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4439 if (Diagnose)
4440 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004441 << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith79363f52012-02-27 06:07:25 +00004442 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004443 }
4444
4445 if (inUnion() && !FieldType.isConstQualified())
4446 AllFieldsAreConst = false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004447 } else if (CSM == Sema::CXXCopyConstructor) {
4448 // For a copy constructor, data members must not be of rvalue reference
4449 // type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004450 if (FieldType->isRValueReferenceType()) {
4451 if (Diagnose)
4452 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4453 << MD->getParent() << FD << FieldType;
Richard Smith7d5088a2012-02-18 02:02:13 +00004454 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004455 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004456 } else if (IsAssignment) {
4457 // For an assignment operator, data members must not be of reference type.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004458 if (FieldType->isReferenceType()) {
4459 if (Diagnose)
4460 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4461 << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
Richard Smith7d5088a2012-02-18 02:02:13 +00004462 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004463 }
4464 if (!FieldRecord && FieldType.isConstQualified()) {
4465 // C++11 [class.copy]p23:
4466 // -- a non-static data member of const non-class type (or array thereof)
4467 if (Diagnose)
4468 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
Richard Smitha2e76f52012-04-29 06:32:34 +00004469 << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004470 return true;
4471 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004472 }
4473
4474 if (FieldRecord) {
Richard Smith7d5088a2012-02-18 02:02:13 +00004475 // Some additional restrictions exist on the variant members.
4476 if (!inUnion() && FieldRecord->isUnion() &&
4477 FieldRecord->isAnonymousStructOrUnion()) {
4478 bool AllVariantFieldsAreConst = true;
4479
Richard Smithdf8dc862012-03-29 19:00:10 +00004480 // FIXME: Handle anonymous unions declared within anonymous unions.
Richard Smith7d5088a2012-02-18 02:02:13 +00004481 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4482 UE = FieldRecord->field_end();
4483 UI != UE; ++UI) {
4484 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
Richard Smith7d5088a2012-02-18 02:02:13 +00004485
4486 if (!UnionFieldType.isConstQualified())
4487 AllVariantFieldsAreConst = false;
4488
Richard Smith9a561d52012-02-26 09:11:52 +00004489 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4490 if (UnionFieldRecord &&
Richard Smith517bb842012-07-18 03:51:16 +00004491 shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4492 UnionFieldType.getCVRQualifiers()))
Richard Smith9a561d52012-02-26 09:11:52 +00004493 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004494 }
4495
4496 // At least one member in each anonymous union must be non-const
Douglas Gregor221c27f2012-02-24 21:25:53 +00004497 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004498 FieldRecord->field_begin() != FieldRecord->field_end()) {
4499 if (Diagnose)
4500 S.Diag(FieldRecord->getLocation(),
4501 diag::note_deleted_default_ctor_all_const)
4502 << MD->getParent() << /*anonymous union*/1;
Richard Smith7d5088a2012-02-18 02:02:13 +00004503 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004504 }
Richard Smith7d5088a2012-02-18 02:02:13 +00004505
Richard Smithdf8dc862012-03-29 19:00:10 +00004506 // Don't check the implicit member of the anonymous union type.
Richard Smith7d5088a2012-02-18 02:02:13 +00004507 // This is technically non-conformant, but sanity demands it.
4508 return false;
4509 }
4510
Richard Smith517bb842012-07-18 03:51:16 +00004511 if (shouldDeleteForClassSubobject(FieldRecord, FD,
4512 FieldType.getCVRQualifiers()))
Richard Smithdf8dc862012-03-29 19:00:10 +00004513 return true;
Richard Smith7d5088a2012-02-18 02:02:13 +00004514 }
4515
4516 return false;
4517}
4518
4519/// C++11 [class.ctor] p5:
4520/// A defaulted default constructor for a class X is defined as deleted if
4521/// X is a union and all of its variant members are of const-qualified type.
4522bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
Douglas Gregor221c27f2012-02-24 21:25:53 +00004523 // This is a silly definition, because it gives an empty union a deleted
4524 // default constructor. Don't do that.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004525 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4526 (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4527 if (Diagnose)
4528 S.Diag(MD->getParent()->getLocation(),
4529 diag::note_deleted_default_ctor_all_const)
4530 << MD->getParent() << /*not anonymous union*/0;
4531 return true;
4532 }
4533 return false;
Richard Smith7d5088a2012-02-18 02:02:13 +00004534}
4535
4536/// Determine whether a defaulted special member function should be defined as
4537/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4538/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
Richard Smith6c4c36c2012-03-30 20:53:28 +00004539bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4540 bool Diagnose) {
Richard Smitheef00292012-08-06 02:25:10 +00004541 if (MD->isInvalidDecl())
4542 return false;
Sean Hunte16da072011-10-10 06:18:57 +00004543 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004544 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004545 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004546 return false;
4547
Richard Smith7d5088a2012-02-18 02:02:13 +00004548 // C++11 [expr.lambda.prim]p19:
4549 // The closure type associated with a lambda-expression has a
4550 // deleted (8.4.3) default constructor and a deleted copy
4551 // assignment operator.
4552 if (RD->isLambda() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004553 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4554 if (Diagnose)
4555 Diag(RD->getLocation(), diag::note_lambda_decl);
Richard Smith7d5088a2012-02-18 02:02:13 +00004556 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004557 }
4558
Richard Smith5bdaac52012-04-02 20:59:25 +00004559 // For an anonymous struct or union, the copy and assignment special members
4560 // will never be used, so skip the check. For an anonymous union declared at
4561 // namespace scope, the constructor and destructor are used.
4562 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4563 RD->isAnonymousStructOrUnion())
4564 return false;
4565
Richard Smith6c4c36c2012-03-30 20:53:28 +00004566 // C++11 [class.copy]p7, p18:
4567 // If the class definition declares a move constructor or move assignment
4568 // operator, an implicitly declared copy constructor or copy assignment
4569 // operator is defined as deleted.
4570 if (MD->isImplicit() &&
4571 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4572 CXXMethodDecl *UserDeclaredMove = 0;
4573
4574 // In Microsoft mode, a user-declared move only causes the deletion of the
4575 // corresponding copy operation, not both copy operations.
4576 if (RD->hasUserDeclaredMoveConstructor() &&
4577 (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4578 if (!Diagnose) return true;
4579 UserDeclaredMove = RD->getMoveConstructor();
Richard Smith1c931be2012-04-02 18:40:40 +00004580 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004581 } else if (RD->hasUserDeclaredMoveAssignment() &&
4582 (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4583 if (!Diagnose) return true;
4584 UserDeclaredMove = RD->getMoveAssignmentOperator();
Richard Smith1c931be2012-04-02 18:40:40 +00004585 assert(UserDeclaredMove);
Richard Smith6c4c36c2012-03-30 20:53:28 +00004586 }
4587
4588 if (UserDeclaredMove) {
4589 Diag(UserDeclaredMove->getLocation(),
4590 diag::note_deleted_copy_user_declared_move)
Richard Smithe6af6602012-04-02 21:07:48 +00004591 << (CSM == CXXCopyAssignment) << RD
Richard Smith6c4c36c2012-03-30 20:53:28 +00004592 << UserDeclaredMove->isMoveAssignmentOperator();
4593 return true;
4594 }
4595 }
Sean Hunte16da072011-10-10 06:18:57 +00004596
Richard Smith5bdaac52012-04-02 20:59:25 +00004597 // Do access control from the special member function
4598 ContextRAII MethodContext(*this, MD);
4599
Richard Smith9a561d52012-02-26 09:11:52 +00004600 // C++11 [class.dtor]p5:
4601 // -- for a virtual destructor, lookup of the non-array deallocation function
4602 // results in an ambiguity or in a function that is deleted or inaccessible
Richard Smith6c4c36c2012-03-30 20:53:28 +00004603 if (CSM == CXXDestructor && MD->isVirtual()) {
Richard Smith9a561d52012-02-26 09:11:52 +00004604 FunctionDecl *OperatorDelete = 0;
4605 DeclarationName Name =
4606 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4607 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
Richard Smith6c4c36c2012-03-30 20:53:28 +00004608 OperatorDelete, false)) {
4609 if (Diagnose)
4610 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
Richard Smith9a561d52012-02-26 09:11:52 +00004611 return true;
Richard Smith6c4c36c2012-03-30 20:53:28 +00004612 }
Richard Smith9a561d52012-02-26 09:11:52 +00004613 }
4614
Richard Smith6c4c36c2012-03-30 20:53:28 +00004615 SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004616
Sean Huntcdee3fe2011-05-11 22:34:38 +00004617 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004618 BE = RD->bases_end(); BI != BE; ++BI)
4619 if (!BI->isVirtual() &&
Richard Smith6c4c36c2012-03-30 20:53:28 +00004620 SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004621 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004622
4623 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004624 BE = RD->vbases_end(); BI != BE; ++BI)
Richard Smith6c4c36c2012-03-30 20:53:28 +00004625 if (SMI.shouldDeleteForBase(BI))
Richard Smith7d5088a2012-02-18 02:02:13 +00004626 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004627
4628 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
Richard Smith7d5088a2012-02-18 02:02:13 +00004629 FE = RD->field_end(); FI != FE; ++FI)
4630 if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
David Blaikie581deb32012-06-06 20:45:41 +00004631 SMI.shouldDeleteForField(*FI))
Sean Hunte3406822011-05-20 21:43:47 +00004632 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004633
Richard Smith7d5088a2012-02-18 02:02:13 +00004634 if (SMI.shouldDeleteForAllConstMembers())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004635 return true;
4636
4637 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004638}
4639
4640/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004641namespace {
4642 struct FindHiddenVirtualMethodData {
4643 Sema *S;
4644 CXXMethodDecl *Method;
4645 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004646 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004647 };
4648}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004649
4650/// \brief Member lookup function that determines whether a given C++
4651/// method overloads virtual methods in a base class without overriding any,
4652/// to be used with CXXRecordDecl::lookupInBases().
4653static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4654 CXXBasePath &Path,
4655 void *UserData) {
4656 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4657
4658 FindHiddenVirtualMethodData &Data
4659 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4660
4661 DeclarationName Name = Data.Method->getDeclName();
4662 assert(Name.getNameKind() == DeclarationName::Identifier);
4663
4664 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004665 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004666 for (Path.Decls = BaseRecord->lookup(Name);
4667 Path.Decls.first != Path.Decls.second;
4668 ++Path.Decls.first) {
4669 NamedDecl *D = *Path.Decls.first;
4670 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004671 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004672 foundSameNameMethod = true;
4673 // Interested only in hidden virtual methods.
4674 if (!MD->isVirtual())
4675 continue;
4676 // If the method we are checking overrides a method from its base
4677 // don't warn about the other overloaded methods.
4678 if (!Data.S->IsOverload(Data.Method, MD, false))
4679 return true;
4680 // Collect the overload only if its hidden.
4681 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4682 overloadedMethods.push_back(MD);
4683 }
4684 }
4685
4686 if (foundSameNameMethod)
4687 Data.OverloadedMethods.append(overloadedMethods.begin(),
4688 overloadedMethods.end());
4689 return foundSameNameMethod;
4690}
4691
4692/// \brief See if a method overloads virtual methods in a base class without
4693/// overriding any.
4694void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4695 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004696 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004697 return;
Benjamin Kramerc4704422012-05-19 16:03:58 +00004698 if (!MD->getDeclName().isIdentifier())
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004699 return;
4700
4701 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4702 /*bool RecordPaths=*/false,
4703 /*bool DetectVirtual=*/false);
4704 FindHiddenVirtualMethodData Data;
4705 Data.Method = MD;
4706 Data.S = this;
4707
4708 // Keep the base methods that were overriden or introduced in the subclass
4709 // by 'using' in a set. A base method not in this set is hidden.
4710 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4711 res.first != res.second; ++res.first) {
4712 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4713 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4714 E = MD->end_overridden_methods();
4715 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004716 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004717 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4718 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004719 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004720 }
4721
4722 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4723 !Data.OverloadedMethods.empty()) {
4724 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4725 << MD << (Data.OverloadedMethods.size() > 1);
4726
4727 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4728 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4729 Diag(overloadedMD->getLocation(),
4730 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4731 }
4732 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004733}
4734
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004735void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00004736 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004737 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00004738 SourceLocation RBrac,
4739 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004740 if (!TagDecl)
4741 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004742
Douglas Gregor42af25f2009-05-11 19:58:34 +00004743 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00004744
Rafael Espindolaf729ce02012-07-12 04:32:30 +00004745 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
4746 if (l->getKind() != AttributeList::AT_Visibility)
4747 continue;
4748 l->setInvalid();
4749 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
4750 l->getName();
4751 }
4752
David Blaikie77b6de02011-09-22 02:58:26 +00004753 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00004754 // strict aliasing violation!
4755 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00004756 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00004757
Douglas Gregor23c94db2010-07-02 17:43:08 +00004758 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00004759 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00004760}
4761
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004762/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4763/// special functions, such as the default constructor, copy
4764/// constructor, or destructor, to the given C++ class (C++
4765/// [special]p1). This routine can only be executed just before the
4766/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00004767void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00004768 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00004769 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004770
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00004771 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00004772 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004773
David Blaikie4e4d0842012-03-11 07:00:24 +00004774 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
Richard Smithb701d3d2011-12-24 21:56:24 +00004775 ++ASTContext::NumImplicitMoveConstructors;
4776
Douglas Gregora376d102010-07-02 21:50:04 +00004777 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4778 ++ASTContext::NumImplicitCopyAssignmentOperators;
4779
4780 // If we have a dynamic class, then the copy assignment operator may be
4781 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4782 // it shows up in the right place in the vtable and that we diagnose
4783 // problems with the implicit exception specification.
4784 if (ClassDecl->isDynamicClass())
4785 DeclareImplicitCopyAssignment(ClassDecl);
4786 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00004787
Richard Smith1c931be2012-04-02 18:40:40 +00004788 if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
Richard Smithb701d3d2011-12-24 21:56:24 +00004789 ++ASTContext::NumImplicitMoveAssignmentOperators;
4790
4791 // Likewise for the move assignment operator.
4792 if (ClassDecl->isDynamicClass())
4793 DeclareImplicitMoveAssignment(ClassDecl);
4794 }
4795
Douglas Gregor4923aa22010-07-02 20:37:36 +00004796 if (!ClassDecl->hasUserDeclaredDestructor()) {
4797 ++ASTContext::NumImplicitDestructors;
4798
4799 // If we have a dynamic class, then the destructor may be virtual, so we
4800 // have to declare the destructor immediately. This ensures that, e.g., it
4801 // shows up in the right place in the vtable and that we diagnose problems
4802 // with the implicit exception specification.
4803 if (ClassDecl->isDynamicClass())
4804 DeclareImplicitDestructor(ClassDecl);
4805 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00004806}
4807
Francois Pichet8387e2a2011-04-22 22:18:13 +00004808void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4809 if (!D)
4810 return;
4811
4812 int NumParamList = D->getNumTemplateParameterLists();
4813 for (int i = 0; i < NumParamList; i++) {
4814 TemplateParameterList* Params = D->getTemplateParameterList(i);
4815 for (TemplateParameterList::iterator Param = Params->begin(),
4816 ParamEnd = Params->end();
4817 Param != ParamEnd; ++Param) {
4818 NamedDecl *Named = cast<NamedDecl>(*Param);
4819 if (Named->getDeclName()) {
4820 S->AddDecl(Named);
4821 IdResolver.AddDecl(Named);
4822 }
4823 }
4824 }
4825}
4826
John McCalld226f652010-08-21 09:40:31 +00004827void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00004828 if (!D)
4829 return;
4830
4831 TemplateParameterList *Params = 0;
4832 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4833 Params = Template->getTemplateParameters();
4834 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4835 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4836 Params = PartialSpec->getTemplateParameters();
4837 else
Douglas Gregor6569d682009-05-27 23:11:45 +00004838 return;
4839
Douglas Gregor6569d682009-05-27 23:11:45 +00004840 for (TemplateParameterList::iterator Param = Params->begin(),
4841 ParamEnd = Params->end();
4842 Param != ParamEnd; ++Param) {
4843 NamedDecl *Named = cast<NamedDecl>(*Param);
4844 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00004845 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00004846 IdResolver.AddDecl(Named);
4847 }
4848 }
4849}
4850
John McCalld226f652010-08-21 09:40:31 +00004851void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004852 if (!RecordD) return;
4853 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00004854 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00004855 PushDeclContext(S, Record);
4856}
4857
John McCalld226f652010-08-21 09:40:31 +00004858void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00004859 if (!RecordD) return;
4860 PopDeclContext();
4861}
4862
Douglas Gregor72b505b2008-12-16 21:30:33 +00004863/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4864/// parsing a top-level (non-nested) C++ class, and we are now
4865/// parsing those parts of the given Method declaration that could
4866/// not be parsed earlier (C++ [class.mem]p2), such as default
4867/// arguments. This action should enter the scope of the given
4868/// Method declaration as if we had just parsed the qualified method
4869/// name. However, it should not bring the parameters into scope;
4870/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00004871void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00004872}
4873
4874/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4875/// C++ method declaration. We're (re-)introducing the given
4876/// function parameter into scope for use in parsing later parts of
4877/// the method declaration. For example, we could see an
4878/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00004879void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004880 if (!ParamD)
4881 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004882
John McCalld226f652010-08-21 09:40:31 +00004883 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00004884
4885 // If this parameter has an unparsed default argument, clear it out
4886 // to make way for the parsed default argument.
4887 if (Param->hasUnparsedDefaultArg())
4888 Param->setDefaultArg(0);
4889
John McCalld226f652010-08-21 09:40:31 +00004890 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004891 if (Param->getDeclName())
4892 IdResolver.AddDecl(Param);
4893}
4894
4895/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4896/// processing the delayed method declaration for Method. The method
4897/// declaration is now considered finished. There may be a separate
4898/// ActOnStartOfFunctionDef action later (not necessarily
4899/// immediately!) for this method, if it was also defined inside the
4900/// class body.
John McCalld226f652010-08-21 09:40:31 +00004901void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00004902 if (!MethodD)
4903 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004904
Douglas Gregorefd5bda2009-08-24 11:57:43 +00004905 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00004906
John McCalld226f652010-08-21 09:40:31 +00004907 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004908
4909 // Now that we have our default arguments, check the constructor
4910 // again. It could produce additional diagnostics or affect whether
4911 // the class has implicitly-declared destructors, among other
4912 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00004913 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4914 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00004915
4916 // Check the default arguments, which we may have added.
4917 if (!Method->isInvalidDecl())
4918 CheckCXXDefaultArguments(Method);
4919}
4920
Douglas Gregor42a552f2008-11-05 20:51:48 +00004921/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00004922/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00004923/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00004924/// emit diagnostics and set the invalid bit to true. In any case, the type
4925/// will be updated to reflect a well-formed type for the constructor and
4926/// returned.
4927QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00004928 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00004929 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004930
4931 // C++ [class.ctor]p3:
4932 // A constructor shall not be virtual (10.3) or static (9.4). A
4933 // constructor can be invoked for a const, volatile or const
4934 // volatile object. A constructor shall not be declared const,
4935 // volatile, or const volatile (9.3.2).
4936 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00004937 if (!D.isInvalidType())
4938 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4939 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4940 << SourceRange(D.getIdentifierLoc());
4941 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004942 }
John McCalld931b082010-08-26 03:08:43 +00004943 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00004944 if (!D.isInvalidType())
4945 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4946 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4947 << SourceRange(D.getIdentifierLoc());
4948 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00004949 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00004950 }
Mike Stump1eb44332009-09-09 15:08:12 +00004951
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004952 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00004953 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00004954 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004955 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4956 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004957 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004958 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4959 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00004960 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004961 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4962 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00004963 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00004964 }
Mike Stump1eb44332009-09-09 15:08:12 +00004965
Douglas Gregorc938c162011-01-26 05:01:58 +00004966 // C++0x [class.ctor]p4:
4967 // A constructor shall not be declared with a ref-qualifier.
4968 if (FTI.hasRefQualifier()) {
4969 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4970 << FTI.RefQualifierIsLValueRef
4971 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4972 D.setInvalidType();
4973 }
4974
Douglas Gregor42a552f2008-11-05 20:51:48 +00004975 // Rebuild the function type "R" without any type qualifiers (in
4976 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00004977 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00004978 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00004979 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4980 return R;
4981
4982 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4983 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00004984 EPI.RefQualifier = RQ_None;
4985
Chris Lattner65401802009-04-25 08:28:21 +00004986 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00004987 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00004988}
4989
Douglas Gregor72b505b2008-12-16 21:30:33 +00004990/// CheckConstructor - Checks a fully-formed constructor for
4991/// well-formedness, issuing any diagnostics required. Returns true if
4992/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00004993void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00004994 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00004995 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4996 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00004997 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00004998
4999 // C++ [class.copy]p3:
5000 // A declaration of a constructor for a class X is ill-formed if
5001 // its first parameter is of type (optionally cv-qualified) X and
5002 // either there are no other parameters or else all other
5003 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005004 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005005 ((Constructor->getNumParams() == 1) ||
5006 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005007 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5008 Constructor->getTemplateSpecializationKind()
5009 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005010 QualType ParamType = Constructor->getParamDecl(0)->getType();
5011 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5012 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005013 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005014 const char *ConstRef
5015 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5016 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005017 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005018 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005019
5020 // FIXME: Rather that making the constructor invalid, we should endeavor
5021 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005022 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005023 }
5024 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005025}
5026
John McCall15442822010-08-04 01:04:25 +00005027/// CheckDestructor - Checks a fully-formed destructor definition for
5028/// well-formedness, issuing any diagnostics required. Returns true
5029/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005030bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005031 CXXRecordDecl *RD = Destructor->getParent();
5032
5033 if (Destructor->isVirtual()) {
5034 SourceLocation Loc;
5035
5036 if (!Destructor->isImplicit())
5037 Loc = Destructor->getLocation();
5038 else
5039 Loc = RD->getLocation();
5040
5041 // If we have a virtual destructor, look up the deallocation function
5042 FunctionDecl *OperatorDelete = 0;
5043 DeclarationName Name =
5044 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005045 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005046 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005047
Eli Friedman5f2987c2012-02-02 03:46:19 +00005048 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005049
5050 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005051 }
Anders Carlsson37909802009-11-30 21:24:50 +00005052
5053 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005054}
5055
Mike Stump1eb44332009-09-09 15:08:12 +00005056static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005057FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5058 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5059 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005060 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005061}
5062
Douglas Gregor42a552f2008-11-05 20:51:48 +00005063/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5064/// the well-formednes of the destructor declarator @p D with type @p
5065/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005066/// emit diagnostics and set the declarator to invalid. Even if this happens,
5067/// will be updated to reflect a well-formed type for the destructor and
5068/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005069QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005070 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005071 // C++ [class.dtor]p1:
5072 // [...] A typedef-name that names a class is a class-name
5073 // (7.1.3); however, a typedef-name that names a class shall not
5074 // be used as the identifier in the declarator for a destructor
5075 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005076 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005077 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005078 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005079 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005080 else if (const TemplateSpecializationType *TST =
5081 DeclaratorType->getAs<TemplateSpecializationType>())
5082 if (TST->isTypeAlias())
5083 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5084 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005085
5086 // C++ [class.dtor]p2:
5087 // A destructor is used to destroy objects of its class type. A
5088 // destructor takes no parameters, and no return type can be
5089 // specified for it (not even void). The address of a destructor
5090 // shall not be taken. A destructor shall not be static. A
5091 // destructor can be invoked for a const, volatile or const
5092 // volatile object. A destructor shall not be declared const,
5093 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005094 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005095 if (!D.isInvalidType())
5096 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5097 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005098 << SourceRange(D.getIdentifierLoc())
5099 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5100
John McCalld931b082010-08-26 03:08:43 +00005101 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005102 }
Chris Lattner65401802009-04-25 08:28:21 +00005103 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005104 // Destructors don't have return types, but the parser will
5105 // happily parse something like:
5106 //
5107 // class X {
5108 // float ~X();
5109 // };
5110 //
5111 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005112 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5113 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5114 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005115 }
Mike Stump1eb44332009-09-09 15:08:12 +00005116
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005117 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005118 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005119 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005120 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5121 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005122 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005123 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5124 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005125 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005126 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5127 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005128 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005129 }
5130
Douglas Gregorc938c162011-01-26 05:01:58 +00005131 // C++0x [class.dtor]p2:
5132 // A destructor shall not be declared with a ref-qualifier.
5133 if (FTI.hasRefQualifier()) {
5134 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5135 << FTI.RefQualifierIsLValueRef
5136 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5137 D.setInvalidType();
5138 }
5139
Douglas Gregor42a552f2008-11-05 20:51:48 +00005140 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005141 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005142 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5143
5144 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005145 FTI.freeArgs();
5146 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005147 }
5148
Mike Stump1eb44332009-09-09 15:08:12 +00005149 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005150 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005151 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005152 D.setInvalidType();
5153 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005154
5155 // Rebuild the function type "R" without any type qualifiers or
5156 // parameters (in case any of the errors above fired) and with
5157 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005158 // types.
John McCalle23cf432010-12-14 08:05:40 +00005159 if (!D.isInvalidType())
5160 return R;
5161
Douglas Gregord92ec472010-07-01 05:10:53 +00005162 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005163 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5164 EPI.Variadic = false;
5165 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005166 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005167 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005168}
5169
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005170/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5171/// well-formednes of the conversion function declarator @p D with
5172/// type @p R. If there are any errors in the declarator, this routine
5173/// will emit diagnostics and return true. Otherwise, it will return
5174/// false. Either way, the type @p R will be updated to reflect a
5175/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005176void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005177 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005178 // C++ [class.conv.fct]p1:
5179 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005180 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005181 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005182 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005183 if (!D.isInvalidType())
5184 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5185 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5186 << SourceRange(D.getIdentifierLoc());
5187 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005188 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005189 }
John McCalla3f81372010-04-13 00:04:31 +00005190
5191 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5192
Chris Lattner6e475012009-04-25 08:35:12 +00005193 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005194 // Conversion functions don't have return types, but the parser will
5195 // happily parse something like:
5196 //
5197 // class X {
5198 // float operator bool();
5199 // };
5200 //
5201 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005202 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5203 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5204 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005205 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005206 }
5207
John McCalla3f81372010-04-13 00:04:31 +00005208 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5209
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005210 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005211 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005212 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5213
5214 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005215 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005216 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005217 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005218 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005219 D.setInvalidType();
5220 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005221
John McCalla3f81372010-04-13 00:04:31 +00005222 // Diagnose "&operator bool()" and other such nonsense. This
5223 // is actually a gcc extension which we don't support.
5224 if (Proto->getResultType() != ConvType) {
5225 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5226 << Proto->getResultType();
5227 D.setInvalidType();
5228 ConvType = Proto->getResultType();
5229 }
5230
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005231 // C++ [class.conv.fct]p4:
5232 // The conversion-type-id shall not represent a function type nor
5233 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005234 if (ConvType->isArrayType()) {
5235 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5236 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005237 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005238 } else if (ConvType->isFunctionType()) {
5239 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5240 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005241 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005242 }
5243
5244 // Rebuild the function type "R" without any parameters (in case any
5245 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005246 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005247 if (D.isInvalidType())
5248 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005249
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005250 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005251 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005252 Diag(D.getDeclSpec().getExplicitSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005253 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00005254 diag::warn_cxx98_compat_explicit_conversion_functions :
5255 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005256 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005257}
5258
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005259/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5260/// the declaration of the given C++ conversion function. This routine
5261/// is responsible for recording the conversion function in the C++
5262/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005263Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005264 assert(Conversion && "Expected to receive a conversion function declaration");
5265
Douglas Gregor9d350972008-12-12 08:25:50 +00005266 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005267
5268 // Make sure we aren't redeclaring the conversion function.
5269 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005270
5271 // C++ [class.conv.fct]p1:
5272 // [...] A conversion function is never used to convert a
5273 // (possibly cv-qualified) object to the (possibly cv-qualified)
5274 // same object type (or a reference to it), to a (possibly
5275 // cv-qualified) base class of that type (or a reference to it),
5276 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005277 // FIXME: Suppress this warning if the conversion function ends up being a
5278 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005279 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005280 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005281 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005282 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005283 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5284 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005285 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005286 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005287 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5288 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005289 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005290 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005291 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005292 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005293 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005294 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005295 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005296 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005297 }
5298
Douglas Gregore80622f2010-09-29 04:25:11 +00005299 if (FunctionTemplateDecl *ConversionTemplate
5300 = Conversion->getDescribedFunctionTemplate())
5301 return ConversionTemplate;
5302
John McCalld226f652010-08-21 09:40:31 +00005303 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005304}
5305
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005306//===----------------------------------------------------------------------===//
5307// Namespace Handling
5308//===----------------------------------------------------------------------===//
5309
John McCallea318642010-08-26 09:15:37 +00005310
5311
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005312/// ActOnStartNamespaceDef - This is called at the start of a namespace
5313/// definition.
John McCalld226f652010-08-21 09:40:31 +00005314Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005315 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005316 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005317 SourceLocation IdentLoc,
5318 IdentifierInfo *II,
5319 SourceLocation LBrace,
5320 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005321 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5322 // For anonymous namespace, take the location of the left brace.
5323 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005324 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005325 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005326 bool IsStd = false;
5327 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005328 Scope *DeclRegionScope = NamespcScope->getParent();
5329
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005330 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005331 if (II) {
5332 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005333 // The identifier in an original-namespace-definition shall not
5334 // have been previously defined in the declarative region in
5335 // which the original-namespace-definition appears. The
5336 // identifier in an original-namespace-definition is the name of
5337 // the namespace. Subsequently in that declarative region, it is
5338 // treated as an original-namespace-name.
5339 //
5340 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005341 // look through using directives, just look for any ordinary names.
5342
5343 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005344 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5345 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005346 NamedDecl *PrevDecl = 0;
5347 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005348 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005349 R.first != R.second; ++R.first) {
5350 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5351 PrevDecl = *R.first;
5352 break;
5353 }
5354 }
5355
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005356 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5357
5358 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005359 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005360 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005361 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005362 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005363 // The user probably just forgot the 'inline', so suggest that it
5364 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005365 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005366 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5367 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005368 Diag(Loc, diag::err_inline_namespace_mismatch)
5369 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005370 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005371 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5372
5373 IsInline = PrevNS->isInline();
5374 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005375 } else if (PrevDecl) {
5376 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005377 Diag(Loc, diag::err_redefinition_different_kind)
5378 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005379 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005380 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005381 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005382 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005383 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005384 // This is the first "real" definition of the namespace "std", so update
5385 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005386 PrevNS = getStdNamespace();
5387 IsStd = true;
5388 AddToKnown = !IsInline;
5389 } else {
5390 // We've seen this namespace for the first time.
5391 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005392 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005393 } else {
John McCall9aeed322009-10-01 00:25:31 +00005394 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005395
5396 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005397 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005398 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005399 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005400 } else {
5401 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005402 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005403 }
5404
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005405 if (PrevNS && IsInline != PrevNS->isInline()) {
5406 // inline-ness must match
5407 Diag(Loc, diag::err_inline_namespace_mismatch)
5408 << IsInline;
5409 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005410
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005411 // Recover by ignoring the new namespace's inline status.
5412 IsInline = PrevNS->isInline();
5413 }
5414 }
5415
5416 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5417 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005418 if (IsInvalid)
5419 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005420
5421 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005422
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005423 // FIXME: Should we be merging attributes?
5424 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005425 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005426
5427 if (IsStd)
5428 StdNamespace = Namespc;
5429 if (AddToKnown)
5430 KnownNamespaces[Namespc] = false;
5431
5432 if (II) {
5433 PushOnScopeChains(Namespc, DeclRegionScope);
5434 } else {
5435 // Link the anonymous namespace into its parent.
5436 DeclContext *Parent = CurContext->getRedeclContext();
5437 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5438 TU->setAnonymousNamespace(Namespc);
5439 } else {
5440 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005441 }
John McCall9aeed322009-10-01 00:25:31 +00005442
Douglas Gregora4181472010-03-24 00:46:35 +00005443 CurContext->addDecl(Namespc);
5444
John McCall9aeed322009-10-01 00:25:31 +00005445 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5446 // behaves as if it were replaced by
5447 // namespace unique { /* empty body */ }
5448 // using namespace unique;
5449 // namespace unique { namespace-body }
5450 // where all occurrences of 'unique' in a translation unit are
5451 // replaced by the same identifier and this identifier differs
5452 // from all other identifiers in the entire program.
5453
5454 // We just create the namespace with an empty name and then add an
5455 // implicit using declaration, just like the standard suggests.
5456 //
5457 // CodeGen enforces the "universally unique" aspect by giving all
5458 // declarations semantically contained within an anonymous
5459 // namespace internal linkage.
5460
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005461 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005462 UsingDirectiveDecl* UD
5463 = UsingDirectiveDecl::Create(Context, CurContext,
5464 /* 'using' */ LBrace,
5465 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005466 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005467 /* identifier */ SourceLocation(),
5468 Namespc,
5469 /* Ancestor */ CurContext);
5470 UD->setImplicit();
5471 CurContext->addDecl(UD);
5472 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005473 }
5474
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00005475 ActOnDocumentableDecl(Namespc);
5476
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005477 // Although we could have an invalid decl (i.e. the namespace name is a
5478 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005479 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5480 // for the namespace has the declarations that showed up in that particular
5481 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005482 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005483 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005484}
5485
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005486/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5487/// is a namespace alias, returns the namespace it points to.
5488static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5489 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5490 return AD->getNamespace();
5491 return dyn_cast_or_null<NamespaceDecl>(D);
5492}
5493
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005494/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5495/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005496void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005497 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5498 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005499 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005500 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005501 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005502 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005503}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005504
John McCall384aff82010-08-25 07:42:41 +00005505CXXRecordDecl *Sema::getStdBadAlloc() const {
5506 return cast_or_null<CXXRecordDecl>(
5507 StdBadAlloc.get(Context.getExternalSource()));
5508}
5509
5510NamespaceDecl *Sema::getStdNamespace() const {
5511 return cast_or_null<NamespaceDecl>(
5512 StdNamespace.get(Context.getExternalSource()));
5513}
5514
Douglas Gregor66992202010-06-29 17:53:46 +00005515/// \brief Retrieve the special "std" namespace, which may require us to
5516/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005517NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005518 if (!StdNamespace) {
5519 // The "std" namespace has not yet been defined, so build one implicitly.
5520 StdNamespace = NamespaceDecl::Create(Context,
5521 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005522 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005523 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005524 &PP.getIdentifierTable().get("std"),
5525 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005526 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005527 }
5528
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005529 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005530}
5531
Sebastian Redl395e04d2012-01-17 22:49:33 +00005532bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005533 assert(getLangOpts().CPlusPlus &&
Sebastian Redl395e04d2012-01-17 22:49:33 +00005534 "Looking for std::initializer_list outside of C++.");
5535
5536 // We're looking for implicit instantiations of
5537 // template <typename E> class std::initializer_list.
5538
5539 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5540 return false;
5541
Sebastian Redl84760e32012-01-17 22:49:58 +00005542 ClassTemplateDecl *Template = 0;
5543 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005544
Sebastian Redl84760e32012-01-17 22:49:58 +00005545 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005546
Sebastian Redl84760e32012-01-17 22:49:58 +00005547 ClassTemplateSpecializationDecl *Specialization =
5548 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5549 if (!Specialization)
5550 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005551
Sebastian Redl84760e32012-01-17 22:49:58 +00005552 Template = Specialization->getSpecializedTemplate();
5553 Arguments = Specialization->getTemplateArgs().data();
5554 } else if (const TemplateSpecializationType *TST =
5555 Ty->getAs<TemplateSpecializationType>()) {
5556 Template = dyn_cast_or_null<ClassTemplateDecl>(
5557 TST->getTemplateName().getAsTemplateDecl());
5558 Arguments = TST->getArgs();
5559 }
5560 if (!Template)
5561 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005562
5563 if (!StdInitializerList) {
5564 // Haven't recognized std::initializer_list yet, maybe this is it.
5565 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5566 if (TemplateClass->getIdentifier() !=
5567 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005568 !getStdNamespace()->InEnclosingNamespaceSetOf(
5569 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005570 return false;
5571 // This is a template called std::initializer_list, but is it the right
5572 // template?
5573 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005574 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005575 return false;
5576 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5577 return false;
5578
5579 // It's the right template.
5580 StdInitializerList = Template;
5581 }
5582
5583 if (Template != StdInitializerList)
5584 return false;
5585
5586 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005587 if (Element)
5588 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005589 return true;
5590}
5591
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005592static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5593 NamespaceDecl *Std = S.getStdNamespace();
5594 if (!Std) {
5595 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5596 return 0;
5597 }
5598
5599 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5600 Loc, Sema::LookupOrdinaryName);
5601 if (!S.LookupQualifiedName(Result, Std)) {
5602 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5603 return 0;
5604 }
5605 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5606 if (!Template) {
5607 Result.suppressDiagnostics();
5608 // We found something weird. Complain about the first thing we found.
5609 NamedDecl *Found = *Result.begin();
5610 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5611 return 0;
5612 }
5613
5614 // We found some template called std::initializer_list. Now verify that it's
5615 // correct.
5616 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005617 if (Params->getMinRequiredArguments() != 1 ||
5618 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005619 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5620 return 0;
5621 }
5622
5623 return Template;
5624}
5625
5626QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5627 if (!StdInitializerList) {
5628 StdInitializerList = LookupStdInitializerList(*this, Loc);
5629 if (!StdInitializerList)
5630 return QualType();
5631 }
5632
5633 TemplateArgumentListInfo Args(Loc, Loc);
5634 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5635 Context.getTrivialTypeSourceInfo(Element,
5636 Loc)));
5637 return Context.getCanonicalType(
5638 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5639}
5640
Sebastian Redl98d36062012-01-17 22:50:14 +00005641bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5642 // C++ [dcl.init.list]p2:
5643 // A constructor is an initializer-list constructor if its first parameter
5644 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5645 // std::initializer_list<E> for some type E, and either there are no other
5646 // parameters or else all other parameters have default arguments.
5647 if (Ctor->getNumParams() < 1 ||
5648 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5649 return false;
5650
5651 QualType ArgType = Ctor->getParamDecl(0)->getType();
5652 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5653 ArgType = RT->getPointeeType().getUnqualifiedType();
5654
5655 return isStdInitializerList(ArgType, 0);
5656}
5657
Douglas Gregor9172aa62011-03-26 22:25:30 +00005658/// \brief Determine whether a using statement is in a context where it will be
5659/// apply in all contexts.
5660static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5661 switch (CurContext->getDeclKind()) {
5662 case Decl::TranslationUnit:
5663 return true;
5664 case Decl::LinkageSpec:
5665 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5666 default:
5667 return false;
5668 }
5669}
5670
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005671namespace {
5672
5673// Callback to only accept typo corrections that are namespaces.
5674class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5675 public:
5676 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5677 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5678 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5679 }
5680 return false;
5681 }
5682};
5683
5684}
5685
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005686static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5687 CXXScopeSpec &SS,
5688 SourceLocation IdentLoc,
5689 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005690 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005691 R.clear();
5692 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005693 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005694 Validator)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00005695 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5696 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005697 if (DeclContext *DC = S.computeDeclContext(SS, false))
5698 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5699 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5700 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5701 else
5702 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5703 << Ident << CorrectedQuotedStr
5704 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005705
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005706 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5707 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005708
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005709 R.addDecl(Corrected.getCorrectionDecl());
5710 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005711 }
5712 return false;
5713}
5714
John McCalld226f652010-08-21 09:40:31 +00005715Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005716 SourceLocation UsingLoc,
5717 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005718 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005719 SourceLocation IdentLoc,
5720 IdentifierInfo *NamespcName,
5721 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005722 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5723 assert(NamespcName && "Invalid NamespcName.");
5724 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005725
5726 // This can only happen along a recovery path.
5727 while (S->getFlags() & Scope::TemplateParamScope)
5728 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005729 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00005730
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005731 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00005732 NestedNameSpecifier *Qualifier = 0;
5733 if (SS.isSet())
5734 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5735
Douglas Gregoreb11cd02009-01-14 22:20:51 +00005736 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00005737 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5738 LookupParsedName(R, S, &SS);
5739 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00005740 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005741
Douglas Gregor66992202010-06-29 17:53:46 +00005742 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005743 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00005744 // Allow "using namespace std;" or "using namespace ::std;" even if
5745 // "std" hasn't been defined yet, for GCC compatibility.
5746 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5747 NamespcName->isStr("std")) {
5748 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005749 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00005750 R.resolveKind();
5751 }
5752 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005753 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00005754 }
5755
John McCallf36e02d2009-10-09 21:13:30 +00005756 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005757 NamedDecl *Named = R.getFoundDecl();
5758 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5759 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005760 // C++ [namespace.udir]p1:
5761 // A using-directive specifies that the names in the nominated
5762 // namespace can be used in the scope in which the
5763 // using-directive appears after the using-directive. During
5764 // unqualified name lookup (3.4.1), the names appear as if they
5765 // were declared in the nearest enclosing namespace which
5766 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00005767 // namespace. [Note: in this context, "contains" means "contains
5768 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005769
5770 // Find enclosing context containing both using-directive and
5771 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005772 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005773 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5774 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5775 CommonAncestor = CommonAncestor->getParent();
5776
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005777 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00005778 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005779 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005780
Douglas Gregor9172aa62011-03-26 22:25:30 +00005781 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00005782 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00005783 Diag(IdentLoc, diag::warn_using_directive_in_header);
5784 }
5785
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005786 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005787 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00005788 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00005789 }
5790
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005791 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00005792 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005793}
5794
5795void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005796 // If the scope has an associated entity and the using directive is at
5797 // namespace or translation unit scope, add the UsingDirectiveDecl into
5798 // its lookup structure so qualified name lookup can find it.
5799 DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5800 if (Ctx && !Ctx->isFunctionOrMethod())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00005801 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00005802 else
Richard Smith1b7f9cb2012-03-13 03:12:56 +00005803 // Otherwise, it is at block sope. The using-directives will affect lookup
5804 // only to the end of the scope.
John McCalld226f652010-08-21 09:40:31 +00005805 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00005806}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005807
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005808
John McCalld226f652010-08-21 09:40:31 +00005809Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00005810 AccessSpecifier AS,
5811 bool HasUsingKeyword,
5812 SourceLocation UsingLoc,
5813 CXXScopeSpec &SS,
5814 UnqualifiedId &Name,
5815 AttributeList *AttrList,
5816 bool IsTypeName,
5817 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00005818 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00005819
Douglas Gregor12c118a2009-11-04 16:30:06 +00005820 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00005821 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005822 case UnqualifiedId::IK_Identifier:
5823 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00005824 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00005825 case UnqualifiedId::IK_ConversionFunctionId:
5826 break;
5827
5828 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00005829 case UnqualifiedId::IK_ConstructorTemplateId:
Richard Smitha1366cb2012-04-27 19:33:05 +00005830 // C++11 inheriting constructors.
Daniel Dunbar96a00142012-03-09 18:35:03 +00005831 Diag(Name.getLocStart(),
David Blaikie4e4d0842012-03-11 07:00:24 +00005832 getLangOpts().CPlusPlus0x ?
Richard Smitha1366cb2012-04-27 19:33:05 +00005833 // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5834 // instead once inheriting constructors work.
5835 diag::err_using_decl_constructor_unsupported :
Richard Smithebaf0e62011-10-18 20:49:44 +00005836 diag::err_using_decl_constructor)
5837 << SS.getRange();
5838
David Blaikie4e4d0842012-03-11 07:00:24 +00005839 if (getLangOpts().CPlusPlus0x) break;
John McCall604e7f12009-12-08 07:46:18 +00005840
John McCalld226f652010-08-21 09:40:31 +00005841 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005842
5843 case UnqualifiedId::IK_DestructorName:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005844 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005845 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00005846 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005847
5848 case UnqualifiedId::IK_TemplateId:
Daniel Dunbar96a00142012-03-09 18:35:03 +00005849 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
Douglas Gregor12c118a2009-11-04 16:30:06 +00005850 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00005851 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00005852 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005853
5854 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5855 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00005856 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00005857 return 0;
John McCall604e7f12009-12-08 07:46:18 +00005858
John McCall60fa3cf2009-12-11 02:10:03 +00005859 // Warn about using declarations.
5860 // TODO: store that the declaration was written without 'using' and
5861 // talk about access decls instead of using decls in the
5862 // diagnostics.
5863 if (!HasUsingKeyword) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005864 UsingLoc = Name.getLocStart();
John McCall60fa3cf2009-12-11 02:10:03 +00005865
5866 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00005867 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00005868 }
5869
Douglas Gregor56c04582010-12-16 00:46:58 +00005870 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5871 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5872 return 0;
5873
John McCall9488ea12009-11-17 05:59:44 +00005874 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00005875 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00005876 /* IsInstantiation */ false,
5877 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00005878 if (UD)
5879 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00005880
John McCalld226f652010-08-21 09:40:31 +00005881 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00005882}
5883
Douglas Gregor09acc982010-07-07 23:08:52 +00005884/// \brief Determine whether a using declaration considers the given
5885/// declarations as "equivalent", e.g., if they are redeclarations of
5886/// the same entity or are both typedefs of the same type.
5887static bool
5888IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5889 bool &SuppressRedeclaration) {
5890 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5891 SuppressRedeclaration = false;
5892 return true;
5893 }
5894
Richard Smith162e1c12011-04-15 14:24:37 +00005895 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5896 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00005897 SuppressRedeclaration = true;
5898 return Context.hasSameType(TD1->getUnderlyingType(),
5899 TD2->getUnderlyingType());
5900 }
5901
5902 return false;
5903}
5904
5905
John McCall9f54ad42009-12-10 09:41:52 +00005906/// Determines whether to create a using shadow decl for a particular
5907/// decl, given the set of decls existing prior to this using lookup.
5908bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5909 const LookupResult &Previous) {
5910 // Diagnose finding a decl which is not from a base class of the
5911 // current class. We do this now because there are cases where this
5912 // function will silently decide not to build a shadow decl, which
5913 // will pre-empt further diagnostics.
5914 //
5915 // We don't need to do this in C++0x because we do the check once on
5916 // the qualifier.
5917 //
5918 // FIXME: diagnose the following if we care enough:
5919 // struct A { int foo; };
5920 // struct B : A { using A::foo; };
5921 // template <class T> struct C : A {};
5922 // template <class T> struct D : C<T> { using B::foo; } // <---
5923 // This is invalid (during instantiation) in C++03 because B::foo
5924 // resolves to the using decl in B, which is not a base class of D<T>.
5925 // We can't diagnose it immediately because C<T> is an unknown
5926 // specialization. The UsingShadowDecl in D<T> then points directly
5927 // to A::foo, which will look well-formed when we instantiate.
5928 // The right solution is to not collapse the shadow-decl chain.
David Blaikie4e4d0842012-03-11 07:00:24 +00005929 if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
John McCall9f54ad42009-12-10 09:41:52 +00005930 DeclContext *OrigDC = Orig->getDeclContext();
5931
5932 // Handle enums and anonymous structs.
5933 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5934 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5935 while (OrigRec->isAnonymousStructOrUnion())
5936 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5937
5938 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5939 if (OrigDC == CurContext) {
5940 Diag(Using->getLocation(),
5941 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005942 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005943 Diag(Orig->getLocation(), diag::note_using_decl_target);
5944 return true;
5945 }
5946
Douglas Gregordc355712011-02-25 00:36:19 +00005947 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00005948 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00005949 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00005950 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00005951 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00005952 Diag(Orig->getLocation(), diag::note_using_decl_target);
5953 return true;
5954 }
5955 }
5956
5957 if (Previous.empty()) return false;
5958
5959 NamedDecl *Target = Orig;
5960 if (isa<UsingShadowDecl>(Target))
5961 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5962
John McCalld7533ec2009-12-11 02:33:26 +00005963 // If the target happens to be one of the previous declarations, we
5964 // don't have a conflict.
5965 //
5966 // FIXME: but we might be increasing its access, in which case we
5967 // should redeclare it.
5968 NamedDecl *NonTag = 0, *Tag = 0;
5969 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5970 I != E; ++I) {
5971 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00005972 bool Result;
5973 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5974 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00005975
5976 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5977 }
5978
John McCall9f54ad42009-12-10 09:41:52 +00005979 if (Target->isFunctionOrFunctionTemplate()) {
5980 FunctionDecl *FD;
5981 if (isa<FunctionTemplateDecl>(Target))
5982 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5983 else
5984 FD = cast<FunctionDecl>(Target);
5985
5986 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00005987 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00005988 case Ovl_Overload:
5989 return false;
5990
5991 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00005992 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00005993 break;
5994
5995 // We found a decl with the exact signature.
5996 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00005997 // If we're in a record, we want to hide the target, so we
5998 // return true (without a diagnostic) to tell the caller not to
5999 // build a shadow decl.
6000 if (CurContext->isRecord())
6001 return true;
6002
6003 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006004 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006005 break;
6006 }
6007
6008 Diag(Target->getLocation(), diag::note_using_decl_target);
6009 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6010 return true;
6011 }
6012
6013 // Target is not a function.
6014
John McCall9f54ad42009-12-10 09:41:52 +00006015 if (isa<TagDecl>(Target)) {
6016 // No conflict between a tag and a non-tag.
6017 if (!Tag) return false;
6018
John McCall41ce66f2009-12-10 19:51:03 +00006019 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006020 Diag(Target->getLocation(), diag::note_using_decl_target);
6021 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6022 return true;
6023 }
6024
6025 // No conflict between a tag and a non-tag.
6026 if (!NonTag) return false;
6027
John McCall41ce66f2009-12-10 19:51:03 +00006028 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006029 Diag(Target->getLocation(), diag::note_using_decl_target);
6030 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6031 return true;
6032}
6033
John McCall9488ea12009-11-17 05:59:44 +00006034/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006035UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006036 UsingDecl *UD,
6037 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006038
6039 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006040 NamedDecl *Target = Orig;
6041 if (isa<UsingShadowDecl>(Target)) {
6042 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6043 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006044 }
6045
6046 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006047 = UsingShadowDecl::Create(Context, CurContext,
6048 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006049 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006050
6051 Shadow->setAccess(UD->getAccess());
6052 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6053 Shadow->setInvalidDecl();
6054
John McCall9488ea12009-11-17 05:59:44 +00006055 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006056 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006057 else
John McCall604e7f12009-12-08 07:46:18 +00006058 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006059
John McCall604e7f12009-12-08 07:46:18 +00006060
John McCall9f54ad42009-12-10 09:41:52 +00006061 return Shadow;
6062}
John McCall604e7f12009-12-08 07:46:18 +00006063
John McCall9f54ad42009-12-10 09:41:52 +00006064/// Hides a using shadow declaration. This is required by the current
6065/// using-decl implementation when a resolvable using declaration in a
6066/// class is followed by a declaration which would hide or override
6067/// one or more of the using decl's targets; for example:
6068///
6069/// struct Base { void foo(int); };
6070/// struct Derived : Base {
6071/// using Base::foo;
6072/// void foo(int);
6073/// };
6074///
6075/// The governing language is C++03 [namespace.udecl]p12:
6076///
6077/// When a using-declaration brings names from a base class into a
6078/// derived class scope, member functions in the derived class
6079/// override and/or hide member functions with the same name and
6080/// parameter types in a base class (rather than conflicting).
6081///
6082/// There are two ways to implement this:
6083/// (1) optimistically create shadow decls when they're not hidden
6084/// by existing declarations, or
6085/// (2) don't create any shadow decls (or at least don't make them
6086/// visible) until we've fully parsed/instantiated the class.
6087/// The problem with (1) is that we might have to retroactively remove
6088/// a shadow decl, which requires several O(n) operations because the
6089/// decl structures are (very reasonably) not designed for removal.
6090/// (2) avoids this but is very fiddly and phase-dependent.
6091void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006092 if (Shadow->getDeclName().getNameKind() ==
6093 DeclarationName::CXXConversionFunctionName)
6094 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6095
John McCall9f54ad42009-12-10 09:41:52 +00006096 // Remove it from the DeclContext...
6097 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006098
John McCall9f54ad42009-12-10 09:41:52 +00006099 // ...and the scope, if applicable...
6100 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006101 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006102 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006103 }
6104
John McCall9f54ad42009-12-10 09:41:52 +00006105 // ...and the using decl.
6106 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6107
6108 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006109 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006110}
6111
John McCall7ba107a2009-11-18 02:36:19 +00006112/// Builds a using declaration.
6113///
6114/// \param IsInstantiation - Whether this call arises from an
6115/// instantiation of an unresolved using declaration. We treat
6116/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006117NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6118 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006119 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006120 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006121 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006122 bool IsInstantiation,
6123 bool IsTypeName,
6124 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006125 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006126 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006127 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006128
Anders Carlsson550b14b2009-08-28 05:49:21 +00006129 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006130
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006131 if (SS.isEmpty()) {
6132 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006133 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006134 }
Mike Stump1eb44332009-09-09 15:08:12 +00006135
John McCall9f54ad42009-12-10 09:41:52 +00006136 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006137 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006138 ForRedeclaration);
6139 Previous.setHideTags(false);
6140 if (S) {
6141 LookupName(Previous, S);
6142
6143 // It is really dumb that we have to do this.
6144 LookupResult::Filter F = Previous.makeFilter();
6145 while (F.hasNext()) {
6146 NamedDecl *D = F.next();
6147 if (!isDeclInScope(D, CurContext, S))
6148 F.erase();
6149 }
6150 F.done();
6151 } else {
6152 assert(IsInstantiation && "no scope in non-instantiation");
6153 assert(CurContext->isRecord() && "scope not record in instantiation");
6154 LookupQualifiedName(Previous, CurContext);
6155 }
6156
John McCall9f54ad42009-12-10 09:41:52 +00006157 // Check for invalid redeclarations.
6158 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6159 return 0;
6160
6161 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006162 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6163 return 0;
6164
John McCallaf8e6ed2009-11-12 03:15:40 +00006165 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006166 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006167 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006168 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006169 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006170 // FIXME: not all declaration name kinds are legal here
6171 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6172 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006173 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006174 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006175 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006176 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6177 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006178 }
John McCalled976492009-12-04 22:46:56 +00006179 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006180 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6181 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006182 }
John McCalled976492009-12-04 22:46:56 +00006183 D->setAccess(AS);
6184 CurContext->addDecl(D);
6185
6186 if (!LookupContext) return D;
6187 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006188
John McCall77bb1aa2010-05-01 00:40:08 +00006189 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006190 UD->setInvalidDecl();
6191 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006192 }
6193
Richard Smithc5a89a12012-04-02 01:30:27 +00006194 // The normal rules do not apply to inheriting constructor declarations.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006195 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smithc5a89a12012-04-02 01:30:27 +00006196 if (CheckInheritingConstructorUsingDecl(UD))
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006197 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006198 return UD;
6199 }
6200
6201 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006202
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006203 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006204
John McCall604e7f12009-12-08 07:46:18 +00006205 // Unlike most lookups, we don't always want to hide tag
6206 // declarations: tag names are visible through the using declaration
6207 // even if hidden by ordinary names, *except* in a dependent context
6208 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006209 if (!IsInstantiation)
6210 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006211
John McCallb9abd8722012-04-07 03:04:20 +00006212 // For the purposes of this lookup, we have a base object type
6213 // equal to that of the current context.
6214 if (CurContext->isRecord()) {
6215 R.setBaseObjectType(
6216 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6217 }
6218
John McCalla24dc2e2009-11-17 02:14:36 +00006219 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006220
John McCallf36e02d2009-10-09 21:13:30 +00006221 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006222 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006223 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006224 UD->setInvalidDecl();
6225 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006226 }
6227
John McCalled976492009-12-04 22:46:56 +00006228 if (R.isAmbiguous()) {
6229 UD->setInvalidDecl();
6230 return UD;
6231 }
Mike Stump1eb44332009-09-09 15:08:12 +00006232
John McCall7ba107a2009-11-18 02:36:19 +00006233 if (IsTypeName) {
6234 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006235 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006236 Diag(IdentLoc, diag::err_using_typename_non_type);
6237 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6238 Diag((*I)->getUnderlyingDecl()->getLocation(),
6239 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006240 UD->setInvalidDecl();
6241 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006242 }
6243 } else {
6244 // If we asked for a non-typename and we got a type, error out,
6245 // but only if this is an instantiation of an unresolved using
6246 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006247 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006248 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6249 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006250 UD->setInvalidDecl();
6251 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006252 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006253 }
6254
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006255 // C++0x N2914 [namespace.udecl]p6:
6256 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006257 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006258 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6259 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006260 UD->setInvalidDecl();
6261 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006262 }
Mike Stump1eb44332009-09-09 15:08:12 +00006263
John McCall9f54ad42009-12-10 09:41:52 +00006264 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6265 if (!CheckUsingShadowDecl(UD, *I, Previous))
6266 BuildUsingShadowDecl(S, UD, *I);
6267 }
John McCall9488ea12009-11-17 05:59:44 +00006268
6269 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006270}
6271
Sebastian Redlf677ea32011-02-05 19:23:19 +00006272/// Additional checks for a using declaration referring to a constructor name.
Richard Smithc5a89a12012-04-02 01:30:27 +00006273bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6274 assert(!UD->isTypeName() && "expecting a constructor name");
Sebastian Redlf677ea32011-02-05 19:23:19 +00006275
Douglas Gregordc355712011-02-25 00:36:19 +00006276 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006277 assert(SourceType &&
6278 "Using decl naming constructor doesn't have type in scope spec.");
6279 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6280
6281 // Check whether the named type is a direct base class.
6282 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6283 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6284 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6285 BaseIt != BaseE; ++BaseIt) {
6286 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6287 if (CanonicalSourceType == BaseType)
6288 break;
Richard Smithc5a89a12012-04-02 01:30:27 +00006289 if (BaseIt->getType()->isDependentType())
6290 break;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006291 }
6292
6293 if (BaseIt == BaseE) {
6294 // Did not find SourceType in the bases.
6295 Diag(UD->getUsingLocation(),
6296 diag::err_using_decl_constructor_not_in_direct_base)
6297 << UD->getNameInfo().getSourceRange()
6298 << QualType(SourceType, 0) << TargetClass;
6299 return true;
6300 }
6301
Richard Smithc5a89a12012-04-02 01:30:27 +00006302 if (!CurContext->isDependentContext())
6303 BaseIt->setInheritConstructors();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006304
6305 return false;
6306}
6307
John McCall9f54ad42009-12-10 09:41:52 +00006308/// Checks that the given using declaration is not an invalid
6309/// redeclaration. Note that this is checking only for the using decl
6310/// itself, not for any ill-formedness among the UsingShadowDecls.
6311bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6312 bool isTypeName,
6313 const CXXScopeSpec &SS,
6314 SourceLocation NameLoc,
6315 const LookupResult &Prev) {
6316 // C++03 [namespace.udecl]p8:
6317 // C++0x [namespace.udecl]p10:
6318 // A using-declaration is a declaration and can therefore be used
6319 // repeatedly where (and only where) multiple declarations are
6320 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006321 //
John McCall8a726212010-11-29 18:01:58 +00006322 // That's in non-member contexts.
6323 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006324 return false;
6325
6326 NestedNameSpecifier *Qual
6327 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6328
6329 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6330 NamedDecl *D = *I;
6331
6332 bool DTypename;
6333 NestedNameSpecifier *DQual;
6334 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6335 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006336 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006337 } else if (UnresolvedUsingValueDecl *UD
6338 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6339 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006340 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006341 } else if (UnresolvedUsingTypenameDecl *UD
6342 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6343 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006344 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006345 } else continue;
6346
6347 // using decls differ if one says 'typename' and the other doesn't.
6348 // FIXME: non-dependent using decls?
6349 if (isTypeName != DTypename) continue;
6350
6351 // using decls differ if they name different scopes (but note that
6352 // template instantiation can cause this check to trigger when it
6353 // didn't before instantiation).
6354 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6355 Context.getCanonicalNestedNameSpecifier(DQual))
6356 continue;
6357
6358 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006359 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006360 return true;
6361 }
6362
6363 return false;
6364}
6365
John McCall604e7f12009-12-08 07:46:18 +00006366
John McCalled976492009-12-04 22:46:56 +00006367/// Checks that the given nested-name qualifier used in a using decl
6368/// in the current context is appropriately related to the current
6369/// scope. If an error is found, diagnoses it and returns true.
6370bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6371 const CXXScopeSpec &SS,
6372 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006373 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006374
John McCall604e7f12009-12-08 07:46:18 +00006375 if (!CurContext->isRecord()) {
6376 // C++03 [namespace.udecl]p3:
6377 // C++0x [namespace.udecl]p8:
6378 // A using-declaration for a class member shall be a member-declaration.
6379
6380 // If we weren't able to compute a valid scope, it must be a
6381 // dependent class scope.
6382 if (!NamedContext || NamedContext->isRecord()) {
6383 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6384 << SS.getRange();
6385 return true;
6386 }
6387
6388 // Otherwise, everything is known to be fine.
6389 return false;
6390 }
6391
6392 // The current scope is a record.
6393
6394 // If the named context is dependent, we can't decide much.
6395 if (!NamedContext) {
6396 // FIXME: in C++0x, we can diagnose if we can prove that the
6397 // nested-name-specifier does not refer to a base class, which is
6398 // still possible in some cases.
6399
6400 // Otherwise we have to conservatively report that things might be
6401 // okay.
6402 return false;
6403 }
6404
6405 if (!NamedContext->isRecord()) {
6406 // Ideally this would point at the last name in the specifier,
6407 // but we don't have that level of source info.
6408 Diag(SS.getRange().getBegin(),
6409 diag::err_using_decl_nested_name_specifier_is_not_class)
6410 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6411 return true;
6412 }
6413
Douglas Gregor6fb07292010-12-21 07:41:49 +00006414 if (!NamedContext->isDependentContext() &&
6415 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6416 return true;
6417
David Blaikie4e4d0842012-03-11 07:00:24 +00006418 if (getLangOpts().CPlusPlus0x) {
John McCall604e7f12009-12-08 07:46:18 +00006419 // C++0x [namespace.udecl]p3:
6420 // In a using-declaration used as a member-declaration, the
6421 // nested-name-specifier shall name a base class of the class
6422 // being defined.
6423
6424 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6425 cast<CXXRecordDecl>(NamedContext))) {
6426 if (CurContext == NamedContext) {
6427 Diag(NameLoc,
6428 diag::err_using_decl_nested_name_specifier_is_current_class)
6429 << SS.getRange();
6430 return true;
6431 }
6432
6433 Diag(SS.getRange().getBegin(),
6434 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6435 << (NestedNameSpecifier*) SS.getScopeRep()
6436 << cast<CXXRecordDecl>(CurContext)
6437 << SS.getRange();
6438 return true;
6439 }
6440
6441 return false;
6442 }
6443
6444 // C++03 [namespace.udecl]p4:
6445 // A using-declaration used as a member-declaration shall refer
6446 // to a member of a base class of the class being defined [etc.].
6447
6448 // Salient point: SS doesn't have to name a base class as long as
6449 // lookup only finds members from base classes. Therefore we can
6450 // diagnose here only if we can prove that that can't happen,
6451 // i.e. if the class hierarchies provably don't intersect.
6452
6453 // TODO: it would be nice if "definitely valid" results were cached
6454 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6455 // need to be repeated.
6456
6457 struct UserData {
Benjamin Kramer8c43dcc2012-02-23 16:06:01 +00006458 llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
John McCall604e7f12009-12-08 07:46:18 +00006459
6460 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6461 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6462 Data->Bases.insert(Base);
6463 return true;
6464 }
6465
6466 bool hasDependentBases(const CXXRecordDecl *Class) {
6467 return !Class->forallBases(collect, this);
6468 }
6469
6470 /// Returns true if the base is dependent or is one of the
6471 /// accumulated base classes.
6472 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6473 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6474 return !Data->Bases.count(Base);
6475 }
6476
6477 bool mightShareBases(const CXXRecordDecl *Class) {
6478 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6479 }
6480 };
6481
6482 UserData Data;
6483
6484 // Returns false if we find a dependent base.
6485 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6486 return false;
6487
6488 // Returns false if the class has a dependent base or if it or one
6489 // of its bases is present in the base set of the current context.
6490 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6491 return false;
6492
6493 Diag(SS.getRange().getBegin(),
6494 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6495 << (NestedNameSpecifier*) SS.getScopeRep()
6496 << cast<CXXRecordDecl>(CurContext)
6497 << SS.getRange();
6498
6499 return true;
John McCalled976492009-12-04 22:46:56 +00006500}
6501
Richard Smith162e1c12011-04-15 14:24:37 +00006502Decl *Sema::ActOnAliasDeclaration(Scope *S,
6503 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006504 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006505 SourceLocation UsingLoc,
6506 UnqualifiedId &Name,
6507 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006508 // Skip up to the relevant declaration scope.
6509 while (S->getFlags() & Scope::TemplateParamScope)
6510 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006511 assert((S->getFlags() & Scope::DeclScope) &&
6512 "got alias-declaration outside of declaration scope");
6513
6514 if (Type.isInvalid())
6515 return 0;
6516
6517 bool Invalid = false;
6518 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6519 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006520 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006521
6522 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6523 return 0;
6524
6525 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006526 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006527 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006528 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6529 TInfo->getTypeLoc().getBeginLoc());
6530 }
Richard Smith162e1c12011-04-15 14:24:37 +00006531
6532 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6533 LookupName(Previous, S);
6534
6535 // Warn about shadowing the name of a template parameter.
6536 if (Previous.isSingleResult() &&
6537 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006538 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006539 Previous.clear();
6540 }
6541
6542 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6543 "name in alias declaration must be an identifier");
6544 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6545 Name.StartLocation,
6546 Name.Identifier, TInfo);
6547
6548 NewTD->setAccess(AS);
6549
6550 if (Invalid)
6551 NewTD->setInvalidDecl();
6552
Richard Smith3e4c6c42011-05-05 21:57:07 +00006553 CheckTypedefForVariablyModifiedType(S, NewTD);
6554 Invalid |= NewTD->isInvalidDecl();
6555
Richard Smith162e1c12011-04-15 14:24:37 +00006556 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006557
6558 NamedDecl *NewND;
6559 if (TemplateParamLists.size()) {
6560 TypeAliasTemplateDecl *OldDecl = 0;
6561 TemplateParameterList *OldTemplateParams = 0;
6562
6563 if (TemplateParamLists.size() != 1) {
6564 Diag(UsingLoc, diag::err_alias_template_extra_headers)
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006565 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
6566 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
Richard Smith3e4c6c42011-05-05 21:57:07 +00006567 }
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00006568 TemplateParameterList *TemplateParams = TemplateParamLists[0];
Richard Smith3e4c6c42011-05-05 21:57:07 +00006569
6570 // Only consider previous declarations in the same scope.
6571 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6572 /*ExplicitInstantiationOrSpecialization*/false);
6573 if (!Previous.empty()) {
6574 Redeclaration = true;
6575
6576 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6577 if (!OldDecl && !Invalid) {
6578 Diag(UsingLoc, diag::err_redefinition_different_kind)
6579 << Name.Identifier;
6580
6581 NamedDecl *OldD = Previous.getRepresentativeDecl();
6582 if (OldD->getLocation().isValid())
6583 Diag(OldD->getLocation(), diag::note_previous_definition);
6584
6585 Invalid = true;
6586 }
6587
6588 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6589 if (TemplateParameterListsAreEqual(TemplateParams,
6590 OldDecl->getTemplateParameters(),
6591 /*Complain=*/true,
6592 TPL_TemplateMatch))
6593 OldTemplateParams = OldDecl->getTemplateParameters();
6594 else
6595 Invalid = true;
6596
6597 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6598 if (!Invalid &&
6599 !Context.hasSameType(OldTD->getUnderlyingType(),
6600 NewTD->getUnderlyingType())) {
6601 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6602 // but we can't reasonably accept it.
6603 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6604 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6605 if (OldTD->getLocation().isValid())
6606 Diag(OldTD->getLocation(), diag::note_previous_definition);
6607 Invalid = true;
6608 }
6609 }
6610 }
6611
6612 // Merge any previous default template arguments into our parameters,
6613 // and check the parameter list.
6614 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6615 TPC_TypeAliasTemplate))
6616 return 0;
6617
6618 TypeAliasTemplateDecl *NewDecl =
6619 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6620 Name.Identifier, TemplateParams,
6621 NewTD);
6622
6623 NewDecl->setAccess(AS);
6624
6625 if (Invalid)
6626 NewDecl->setInvalidDecl();
6627 else if (OldDecl)
6628 NewDecl->setPreviousDeclaration(OldDecl);
6629
6630 NewND = NewDecl;
6631 } else {
6632 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6633 NewND = NewTD;
6634 }
Richard Smith162e1c12011-04-15 14:24:37 +00006635
6636 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006637 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006638
Dmitri Gribenkoc27bc802012-08-02 20:49:51 +00006639 ActOnDocumentableDecl(NewND);
Richard Smith3e4c6c42011-05-05 21:57:07 +00006640 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006641}
6642
John McCalld226f652010-08-21 09:40:31 +00006643Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006644 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006645 SourceLocation AliasLoc,
6646 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006647 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006648 SourceLocation IdentLoc,
6649 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006650
Anders Carlsson81c85c42009-03-28 23:53:49 +00006651 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006652 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6653 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006654
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006655 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006656 NamedDecl *PrevDecl
6657 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6658 ForRedeclaration);
6659 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6660 PrevDecl = 0;
6661
6662 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006663 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006664 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006665 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006666 // FIXME: At some point, we'll want to create the (redundant)
6667 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006668 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006669 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006670 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006671 }
Mike Stump1eb44332009-09-09 15:08:12 +00006672
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006673 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6674 diag::err_redefinition_different_kind;
6675 Diag(AliasLoc, DiagID) << Alias;
6676 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006677 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006678 }
6679
John McCalla24dc2e2009-11-17 02:14:36 +00006680 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006681 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006682
John McCallf36e02d2009-10-09 21:13:30 +00006683 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006684 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Richard Smithbf9658c2012-04-05 23:13:23 +00006685 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006686 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006687 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006688 }
Mike Stump1eb44332009-09-09 15:08:12 +00006689
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006690 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006691 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006692 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006693 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006694
John McCall3dbd3d52010-02-16 06:53:13 +00006695 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006696 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006697}
6698
Douglas Gregor39957dc2010-05-01 15:04:51 +00006699namespace {
6700 /// \brief Scoped object used to handle the state changes required in Sema
6701 /// to implicitly define the body of a C++ member function;
6702 class ImplicitlyDefinedFunctionScope {
6703 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006704 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006705
6706 public:
6707 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006708 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006709 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006710 S.PushFunctionScope();
6711 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6712 }
6713
6714 ~ImplicitlyDefinedFunctionScope() {
6715 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006716 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006717 }
6718 };
6719}
6720
Sean Hunt001cad92011-05-10 00:49:42 +00006721Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00006722Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
6723 CXXMethodDecl *MD) {
6724 CXXRecordDecl *ClassDecl = MD->getParent();
6725
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006726 // C++ [except.spec]p14:
6727 // An implicitly declared special member function (Clause 12) shall have an
6728 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00006729 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006730 if (ClassDecl->isInvalidDecl())
6731 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006732
Sebastian Redl60618fa2011-03-12 11:50:43 +00006733 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006734 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6735 BEnd = ClassDecl->bases_end();
6736 B != BEnd; ++B) {
6737 if (B->isVirtual()) // Handled below.
6738 continue;
6739
Douglas Gregor18274032010-07-03 00:47:00 +00006740 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6741 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006742 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6743 // If this is a deleted function, add it anyway. This might be conformant
6744 // with the standard. This might not. I'm not sure. It might not matter.
6745 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006746 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006747 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006748 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006749
6750 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006751 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6752 BEnd = ClassDecl->vbases_end();
6753 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00006754 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6755 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00006756 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6757 // If this is a deleted function, add it anyway. This might be conformant
6758 // with the standard. This might not. I'm not sure. It might not matter.
6759 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006760 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006761 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006762 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00006763
6764 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006765 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6766 FEnd = ClassDecl->field_end();
6767 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00006768 if (F->hasInClassInitializer()) {
6769 if (Expr *E = F->getInClassInitializer())
6770 ExceptSpec.CalledExpr(E);
6771 else if (!F->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00006772 // DR1351:
6773 // If the brace-or-equal-initializer of a non-static data member
6774 // invokes a defaulted default constructor of its class or of an
6775 // enclosing class in a potentially evaluated subexpression, the
6776 // program is ill-formed.
6777 //
6778 // This resolution is unworkable: the exception specification of the
6779 // default constructor can be needed in an unevaluated context, in
6780 // particular, in the operand of a noexcept-expression, and we can be
6781 // unable to compute an exception specification for an enclosed class.
6782 //
6783 // We do not allow an in-class initializer to require the evaluation
6784 // of the exception specification for any in-class initializer whose
6785 // definition is not lexically complete.
6786 Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
Richard Smith7a614d82011-06-11 17:19:42 +00006787 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00006788 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00006789 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6790 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6791 // If this is a deleted function, add it anyway. This might be conformant
6792 // with the standard. This might not. I'm not sure. It might not matter.
6793 // In particular, the problem is that this function never gets called. It
6794 // might just be ill-formed because this function attempts to refer to
6795 // a deleted function here.
6796 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00006797 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00006798 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006799 }
John McCalle23cf432010-12-14 08:05:40 +00006800
Sean Hunt001cad92011-05-10 00:49:42 +00006801 return ExceptSpec;
6802}
6803
6804CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6805 CXXRecordDecl *ClassDecl) {
6806 // C++ [class.ctor]p5:
6807 // A default constructor for a class X is a constructor of class X
6808 // that can be called without an argument. If there is no
6809 // user-declared constructor for class X, a default constructor is
6810 // implicitly declared. An implicitly-declared default constructor
6811 // is an inline public member of its class.
6812 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6813 "Should not build implicit default constructor!");
6814
Richard Smith7756afa2012-06-10 05:43:50 +00006815 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
6816 CXXDefaultConstructor,
6817 false);
6818
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006819 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00006820 CanQualType ClassType
6821 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006822 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006823 DeclarationName Name
6824 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00006825 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00006826 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00006827 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00006828 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00006829 Constexpr);
Douglas Gregor32df23e2010-07-01 22:02:46 +00006830 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00006831 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00006832 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00006833 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Richard Smithb9d0b762012-07-27 04:22:15 +00006834
6835 // Build an exception specification pointing back at this constructor.
6836 FunctionProtoType::ExtProtoInfo EPI;
6837 EPI.ExceptionSpecType = EST_Unevaluated;
6838 EPI.ExceptionSpecDecl = DefaultCon;
6839 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6840
Douglas Gregor18274032010-07-03 00:47:00 +00006841 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00006842 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6843
Douglas Gregor23c94db2010-07-02 17:43:08 +00006844 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00006845 PushOnScopeChains(DefaultCon, S, false);
6846 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00006847
Sean Hunte16da072011-10-10 06:18:57 +00006848 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00006849 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00006850
Douglas Gregor32df23e2010-07-01 22:02:46 +00006851 return DefaultCon;
6852}
6853
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006854void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6855 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00006856 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00006857 !Constructor->doesThisDeclarationHaveABody() &&
6858 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006859 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00006860
Anders Carlssonf6513ed2010-04-23 16:04:08 +00006861 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00006862 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00006863
Douglas Gregor39957dc2010-05-01 15:04:51 +00006864 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00006865 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00006866 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00006867 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00006868 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00006869 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00006870 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006871 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00006872 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006873
6874 SourceLocation Loc = Constructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00006875 Constructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor4ada9d32010-09-20 16:48:21 +00006876
6877 Constructor->setUsed();
6878 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00006879
6880 if (ASTMutationListener *L = getASTMutationListener()) {
6881 L->CompletedImplicitDefinition(Constructor);
6882 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006883}
6884
Richard Smith7a614d82011-06-11 17:19:42 +00006885void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6886 if (!D) return;
6887 AdjustDeclIfTemplate(D);
6888
6889 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
Richard Smith7a614d82011-06-11 17:19:42 +00006890
Richard Smithb9d0b762012-07-27 04:22:15 +00006891 if (!ClassDecl->isDependentType())
6892 CheckExplicitlyDefaultedMethods(ClassDecl);
Richard Smith7a614d82011-06-11 17:19:42 +00006893}
6894
Sebastian Redlf677ea32011-02-05 19:23:19 +00006895void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6896 // We start with an initial pass over the base classes to collect those that
6897 // inherit constructors from. If there are none, we can forgo all further
6898 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00006899 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006900 BasesVector BasesToInheritFrom;
6901 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6902 BaseE = ClassDecl->bases_end();
6903 BaseIt != BaseE; ++BaseIt) {
6904 if (BaseIt->getInheritConstructors()) {
6905 QualType Base = BaseIt->getType();
6906 if (Base->isDependentType()) {
6907 // If we inherit constructors from anything that is dependent, just
6908 // abort processing altogether. We'll get another chance for the
6909 // instantiations.
6910 return;
6911 }
6912 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6913 }
6914 }
6915 if (BasesToInheritFrom.empty())
6916 return;
6917
6918 // Now collect the constructors that we already have in the current class.
6919 // Those take precedence over inherited constructors.
6920 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6921 // unless there is a user-declared constructor with the same signature in
6922 // the class where the using-declaration appears.
6923 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6924 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6925 CtorE = ClassDecl->ctor_end();
6926 CtorIt != CtorE; ++CtorIt) {
6927 ExistingConstructors.insert(
6928 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6929 }
6930
Sebastian Redlf677ea32011-02-05 19:23:19 +00006931 DeclarationName CreatedCtorName =
6932 Context.DeclarationNames.getCXXConstructorName(
6933 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6934
6935 // Now comes the true work.
6936 // First, we keep a map from constructor types to the base that introduced
6937 // them. Needed for finding conflicting constructors. We also keep the
6938 // actually inserted declarations in there, for pretty diagnostics.
6939 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6940 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6941 ConstructorToSourceMap InheritedConstructors;
6942 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6943 BaseE = BasesToInheritFrom.end();
6944 BaseIt != BaseE; ++BaseIt) {
6945 const RecordType *Base = *BaseIt;
6946 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6947 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6948 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6949 CtorE = BaseDecl->ctor_end();
6950 CtorIt != CtorE; ++CtorIt) {
6951 // Find the using declaration for inheriting this base's constructors.
Richard Smithc5a89a12012-04-02 01:30:27 +00006952 // FIXME: Don't perform name lookup just to obtain a source location!
Sebastian Redlf677ea32011-02-05 19:23:19 +00006953 DeclarationName Name =
6954 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
Richard Smithc5a89a12012-04-02 01:30:27 +00006955 LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6956 LookupQualifiedName(Result, CurContext);
6957 UsingDecl *UD = Result.getAsSingle<UsingDecl>();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006958 SourceLocation UsingLoc = UD ? UD->getLocation() :
6959 ClassDecl->getLocation();
6960
6961 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6962 // from the class X named in the using-declaration consists of actual
6963 // constructors and notional constructors that result from the
6964 // transformation of defaulted parameters as follows:
6965 // - all non-template default constructors of X, and
6966 // - for each non-template constructor of X that has at least one
6967 // parameter with a default argument, the set of constructors that
6968 // results from omitting any ellipsis parameter specification and
6969 // successively omitting parameters with a default argument from the
6970 // end of the parameter-type-list.
David Blaikie581deb32012-06-06 20:45:41 +00006971 CXXConstructorDecl *BaseCtor = *CtorIt;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006972 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6973 const FunctionProtoType *BaseCtorType =
6974 BaseCtor->getType()->getAs<FunctionProtoType>();
6975
6976 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6977 maxParams = BaseCtor->getNumParams();
6978 params <= maxParams; ++params) {
6979 // Skip default constructors. They're never inherited.
6980 if (params == 0)
6981 continue;
6982 // Skip copy and move constructors for the same reason.
6983 if (CanBeCopyOrMove && params == 1)
6984 continue;
6985
6986 // Build up a function type for this particular constructor.
6987 // FIXME: The working paper does not consider that the exception spec
6988 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00006989 // source. This code doesn't yet, either. When it does, this code will
6990 // need to be delayed until after exception specifications and in-class
6991 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00006992 const Type *NewCtorType;
6993 if (params == maxParams)
6994 NewCtorType = BaseCtorType;
6995 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00006996 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00006997 for (unsigned i = 0; i < params; ++i) {
6998 Args.push_back(BaseCtorType->getArgType(i));
6999 }
7000 FunctionProtoType::ExtProtoInfo ExtInfo =
7001 BaseCtorType->getExtProtoInfo();
7002 ExtInfo.Variadic = false;
7003 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7004 Args.data(), params, ExtInfo)
7005 .getTypePtr();
7006 }
7007 const Type *CanonicalNewCtorType =
7008 Context.getCanonicalType(NewCtorType);
7009
7010 // Now that we have the type, first check if the class already has a
7011 // constructor with this signature.
7012 if (ExistingConstructors.count(CanonicalNewCtorType))
7013 continue;
7014
7015 // Then we check if we have already declared an inherited constructor
7016 // with this signature.
7017 std::pair<ConstructorToSourceMap::iterator, bool> result =
7018 InheritedConstructors.insert(std::make_pair(
7019 CanonicalNewCtorType,
7020 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7021 if (!result.second) {
7022 // Already in the map. If it came from a different class, that's an
7023 // error. Not if it's from the same.
7024 CanQualType PreviousBase = result.first->second.first;
7025 if (CanonicalBase != PreviousBase) {
7026 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7027 const CXXConstructorDecl *PrevBaseCtor =
7028 PrevCtor->getInheritedConstructor();
7029 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7030
7031 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7032 Diag(BaseCtor->getLocation(),
7033 diag::note_using_decl_constructor_conflict_current_ctor);
7034 Diag(PrevBaseCtor->getLocation(),
7035 diag::note_using_decl_constructor_conflict_previous_ctor);
7036 Diag(PrevCtor->getLocation(),
7037 diag::note_using_decl_constructor_conflict_previous_using);
7038 }
7039 continue;
7040 }
7041
7042 // OK, we're there, now add the constructor.
7043 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007044 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007045 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7046 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007047 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7048 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007049 /*ImplicitlyDeclared=*/true,
7050 // FIXME: Due to a defect in the standard, we treat inherited
7051 // constructors as constexpr even if that makes them ill-formed.
7052 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007053 NewCtor->setAccess(BaseCtor->getAccess());
7054
7055 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007056 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007057 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007058 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7059 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007060 /*IdentifierInfo=*/0,
7061 BaseCtorType->getArgType(i),
7062 /*TInfo=*/0, SC_None,
7063 SC_None, /*DefaultArg=*/0));
7064 }
David Blaikie4278c652011-09-21 18:16:56 +00007065 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007066 NewCtor->setInheritedConstructor(BaseCtor);
7067
Sebastian Redlf677ea32011-02-05 19:23:19 +00007068 ClassDecl->addDecl(NewCtor);
7069 result.first->second.second = NewCtor;
7070 }
7071 }
7072 }
7073}
7074
Sean Huntcb45a0f2011-05-12 22:46:25 +00007075Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007076Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
7077 CXXRecordDecl *ClassDecl = MD->getParent();
7078
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007079 // C++ [except.spec]p14:
7080 // An implicitly declared special member function (Clause 12) shall have
7081 // an exception-specification.
Richard Smithe6975e92012-04-17 00:58:00 +00007082 ImplicitExceptionSpecification ExceptSpec(*this);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007083 if (ClassDecl->isInvalidDecl())
7084 return ExceptSpec;
7085
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007086 // Direct base-class destructors.
7087 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7088 BEnd = ClassDecl->bases_end();
7089 B != BEnd; ++B) {
7090 if (B->isVirtual()) // Handled below.
7091 continue;
7092
7093 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007094 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007095 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007096 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007097
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007098 // Virtual base-class destructors.
7099 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7100 BEnd = ClassDecl->vbases_end();
7101 B != BEnd; ++B) {
7102 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007103 ExceptSpec.CalledDecl(B->getLocStart(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007104 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007105 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007106
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007107 // Field destructors.
7108 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7109 FEnd = ClassDecl->field_end();
7110 F != FEnd; ++F) {
7111 if (const RecordType *RecordTy
7112 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
Richard Smithe6975e92012-04-17 00:58:00 +00007113 ExceptSpec.CalledDecl(F->getLocation(),
Sebastian Redl0ee33912011-05-19 05:13:44 +00007114 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007115 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007116
Sean Huntcb45a0f2011-05-12 22:46:25 +00007117 return ExceptSpec;
7118}
7119
7120CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7121 // C++ [class.dtor]p2:
7122 // If a class has no user-declared destructor, a destructor is
7123 // declared implicitly. An implicitly-declared destructor is an
7124 // inline public member of its class.
Sean Huntcb45a0f2011-05-12 22:46:25 +00007125
Douglas Gregor4923aa22010-07-02 20:37:36 +00007126 // Create the actual destructor declaration.
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007127 CanQualType ClassType
7128 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007129 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007130 DeclarationName Name
7131 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007132 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007133 CXXDestructorDecl *Destructor
Richard Smithb9d0b762012-07-27 04:22:15 +00007134 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7135 QualType(), 0, /*isInline=*/true,
Sebastian Redl60618fa2011-03-12 11:50:43 +00007136 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007137 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007138 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007139 Destructor->setImplicit();
7140 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Richard Smithb9d0b762012-07-27 04:22:15 +00007141
7142 // Build an exception specification pointing back at this destructor.
7143 FunctionProtoType::ExtProtoInfo EPI;
7144 EPI.ExceptionSpecType = EST_Unevaluated;
7145 EPI.ExceptionSpecDecl = Destructor;
7146 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7147
Douglas Gregor4923aa22010-07-02 20:37:36 +00007148 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007149 ++ASTContext::NumImplicitDestructorsDeclared;
Richard Smithb9d0b762012-07-27 04:22:15 +00007150
Douglas Gregor4923aa22010-07-02 20:37:36 +00007151 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007152 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007153 PushOnScopeChains(Destructor, S, false);
7154 ClassDecl->addDecl(Destructor);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007155
Richard Smith9a561d52012-02-26 09:11:52 +00007156 AddOverriddenMethods(ClassDecl, Destructor);
7157
Richard Smith7d5088a2012-02-18 02:02:13 +00007158 if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
Sean Huntcb45a0f2011-05-12 22:46:25 +00007159 Destructor->setDeletedAsWritten();
Richard Smith9a561d52012-02-26 09:11:52 +00007160
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007161 return Destructor;
7162}
7163
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007164void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007165 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007166 assert((Destructor->isDefaulted() &&
Richard Smith03f68782012-02-26 07:51:39 +00007167 !Destructor->doesThisDeclarationHaveABody() &&
7168 !Destructor->isDeleted()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007169 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007170 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007171 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007172
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007173 if (Destructor->isInvalidDecl())
7174 return;
7175
Douglas Gregor39957dc2010-05-01 15:04:51 +00007176 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007177
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007178 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007179 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7180 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007181
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007182 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007183 Diag(CurrentLocation, diag::note_member_synthesized_at)
7184 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7185
7186 Destructor->setInvalidDecl();
7187 return;
7188 }
7189
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007190 SourceLocation Loc = Destructor->getLocation();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00007191 Destructor->setBody(new (Context) CompoundStmt(Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007192 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007193 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007194 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007195
7196 if (ASTMutationListener *L = getASTMutationListener()) {
7197 L->CompletedImplicitDefinition(Destructor);
7198 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007199}
7200
Richard Smitha4156b82012-04-21 18:42:51 +00007201/// \brief Perform any semantic analysis which needs to be delayed until all
7202/// pending class member declarations have been parsed.
7203void Sema::ActOnFinishCXXMemberDecls() {
Richard Smitha4156b82012-04-21 18:42:51 +00007204 // Perform any deferred checking of exception specifications for virtual
7205 // destructors.
7206 for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7207 i != e; ++i) {
7208 const CXXDestructorDecl *Dtor =
7209 DelayedDestructorExceptionSpecChecks[i].first;
7210 assert(!Dtor->getParent()->isDependentType() &&
7211 "Should not ever add destructors of templates into the list.");
7212 CheckOverridingFunctionExceptionSpec(Dtor,
7213 DelayedDestructorExceptionSpecChecks[i].second);
7214 }
7215 DelayedDestructorExceptionSpecChecks.clear();
7216}
7217
Richard Smithb9d0b762012-07-27 04:22:15 +00007218void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
7219 CXXDestructorDecl *Destructor) {
7220 assert(getLangOpts().CPlusPlus0x &&
7221 "adjusting dtor exception specs was introduced in c++11");
7222
Sebastian Redl0ee33912011-05-19 05:13:44 +00007223 // C++11 [class.dtor]p3:
7224 // A declaration of a destructor that does not have an exception-
7225 // specification is implicitly considered to have the same exception-
7226 // specification as an implicit declaration.
Richard Smithb9d0b762012-07-27 04:22:15 +00007227 const FunctionProtoType *DtorType = Destructor->getType()->
Sebastian Redl0ee33912011-05-19 05:13:44 +00007228 getAs<FunctionProtoType>();
Richard Smithb9d0b762012-07-27 04:22:15 +00007229 if (DtorType->hasExceptionSpec())
Sebastian Redl0ee33912011-05-19 05:13:44 +00007230 return;
7231
Chandler Carruth3f224b22011-09-20 04:55:26 +00007232 // Replace the destructor's type, building off the existing one. Fortunately,
7233 // the only thing of interest in the destructor type is its extended info.
7234 // The return and arguments are fixed.
Richard Smithb9d0b762012-07-27 04:22:15 +00007235 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
7236 EPI.ExceptionSpecType = EST_Unevaluated;
7237 EPI.ExceptionSpecDecl = Destructor;
7238 Destructor->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
Richard Smitha4156b82012-04-21 18:42:51 +00007239
Sebastian Redl0ee33912011-05-19 05:13:44 +00007240 // FIXME: If the destructor has a body that could throw, and the newly created
7241 // spec doesn't allow exceptions, we should emit a warning, because this
7242 // change in behavior can break conforming C++03 programs at runtime.
Richard Smithb9d0b762012-07-27 04:22:15 +00007243 // However, we don't have a body or an exception specification yet, so it
7244 // needs to be done somewhere else.
Sebastian Redl0ee33912011-05-19 05:13:44 +00007245}
7246
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007247/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007248/// \c To.
7249///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007250/// This routine is used to copy/move the members of a class with an
7251/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007252/// copied are arrays, this routine builds for loops to copy them.
7253///
7254/// \param S The Sema object used for type-checking.
7255///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007256/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007257///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007258/// \param T The type of the expressions being copied/moved. Both expressions
7259/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007260///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007261/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007262///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007263/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007264///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007265/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007266/// Otherwise, it's a non-static member subobject.
7267///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007268/// \param Copying Whether we're copying or moving.
7269///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007270/// \param Depth Internal parameter recording the depth of the recursion.
7271///
7272/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007273static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007274BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007275 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007276 bool CopyingBaseSubobject, bool Copying,
7277 unsigned Depth = 0) {
7278 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007279 // Each subobject is assigned in the manner appropriate to its type:
7280 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007281 // - if the subobject is of class type, as if by a call to operator= with
7282 // the subobject as the object expression and the corresponding
7283 // subobject of x as a single function argument (as if by explicit
7284 // qualification; that is, ignoring any possible virtual overriding
7285 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007286 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7287 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7288
7289 // Look for operator=.
7290 DeclarationName Name
7291 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7292 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7293 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7294
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007295 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007296 LookupResult::Filter F = OpLookup.makeFilter();
7297 while (F.hasNext()) {
7298 NamedDecl *D = F.next();
7299 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Richard Smith1c931be2012-04-02 18:40:40 +00007300 if (Method->isCopyAssignmentOperator() ||
7301 (!Copying && Method->isMoveAssignmentOperator()))
Douglas Gregor06a9f362010-05-01 20:49:11 +00007302 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007303
Douglas Gregor06a9f362010-05-01 20:49:11 +00007304 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007305 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007306 F.done();
7307
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007308 // Suppress the protected check (C++ [class.protected]) for each of the
7309 // assignment operators we found. This strange dance is required when
7310 // we're assigning via a base classes's copy-assignment operator. To
7311 // ensure that we're getting the right base class subobject (without
7312 // ambiguities), we need to cast "this" to that subobject type; to
7313 // ensure that we don't go through the virtual call mechanism, we need
7314 // to qualify the operator= name with the base class (see below). However,
7315 // this means that if the base class has a protected copy assignment
7316 // operator, the protected member access check will fail. So, we
7317 // rewrite "protected" access to "public" access in this case, since we
7318 // know by construction that we're calling from a derived class.
7319 if (CopyingBaseSubobject) {
7320 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7321 L != LEnd; ++L) {
7322 if (L.getAccess() == AS_protected)
7323 L.setAccess(AS_public);
7324 }
7325 }
7326
Douglas Gregor06a9f362010-05-01 20:49:11 +00007327 // Create the nested-name-specifier that will be used to qualify the
7328 // reference to operator=; this is required to suppress the virtual
7329 // call mechanism.
7330 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007331 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007332 SS.MakeTrivial(S.Context,
7333 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007334 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007335 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007336
7337 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007338 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007339 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007340 /*TemplateKWLoc=*/SourceLocation(),
7341 /*FirstQualifierInScope=*/0,
7342 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007343 /*TemplateArgs=*/0,
7344 /*SuppressQualifierCheck=*/true);
7345 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007346 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007347
7348 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007349
John McCall60d7b3a2010-08-24 06:29:42 +00007350 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007351 OpEqualRef.takeAs<Expr>(),
7352 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007353 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007354 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007355
7356 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007357 }
John McCallb0207482010-03-16 06:11:48 +00007358
Douglas Gregor06a9f362010-05-01 20:49:11 +00007359 // - if the subobject is of scalar type, the built-in assignment
7360 // operator is used.
7361 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7362 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007363 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007364 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007365 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007366
7367 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007368 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007369
7370 // - if the subobject is an array, each element is assigned, in the
7371 // manner appropriate to the element type;
7372
7373 // Construct a loop over the array bounds, e.g.,
7374 //
7375 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7376 //
7377 // that will copy each of the array elements.
7378 QualType SizeType = S.Context.getSizeType();
7379
7380 // Create the iteration variable.
7381 IdentifierInfo *IterationVarName = 0;
7382 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007383 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007384 llvm::raw_svector_ostream OS(Str);
7385 OS << "__i" << Depth;
7386 IterationVarName = &S.Context.Idents.get(OS.str());
7387 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007388 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007389 IterationVarName, SizeType,
7390 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007391 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007392
7393 // Initialize the iteration variable to zero.
7394 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007395 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007396
7397 // Create a reference to the iteration variable; we'll use this several
7398 // times throughout.
7399 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007400 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007401 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007402 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7403 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7404
Douglas Gregor06a9f362010-05-01 20:49:11 +00007405 // Create the DeclStmt that holds the iteration variable.
7406 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7407
7408 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007409 llvm::APInt Upper
7410 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007411 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007412 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007413 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7414 BO_NE, S.Context.BoolTy,
7415 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007416
7417 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007418 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007419 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7420 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007421
7422 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007423 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007424 IterationVarRefRVal,
7425 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007426 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007427 IterationVarRefRVal,
7428 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007429 if (!Copying) // Cast to rvalue
7430 From = CastForMoving(S, From);
7431
7432 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007433 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7434 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007435 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007436 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007437 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007438
7439 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007440 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007441 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007442 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007443 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007444}
7445
Richard Smithb9d0b762012-07-27 04:22:15 +00007446/// Determine whether an implicit copy assignment operator for ClassDecl has a
7447/// const argument.
7448/// FIXME: It ought to be possible to store this on the record.
7449static bool isImplicitCopyAssignmentArgConst(Sema &S,
7450 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007451 if (ClassDecl->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00007452 return true;
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007453
Douglas Gregord3c35902010-07-01 16:36:15 +00007454 // C++ [class.copy]p10:
7455 // If the class definition does not explicitly declare a copy
7456 // assignment operator, one is declared implicitly.
7457 // The implicitly-defined copy assignment operator for a class X
7458 // will have the form
7459 //
7460 // X& X::operator=(const X&)
7461 //
7462 // if
Douglas Gregord3c35902010-07-01 16:36:15 +00007463 // -- each direct base class B of X has a copy assignment operator
7464 // whose parameter is of type const B&, const volatile B& or B,
7465 // and
7466 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7467 BaseEnd = ClassDecl->bases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007468 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007469 // We'll handle this below
Richard Smithb9d0b762012-07-27 04:22:15 +00007470 if (S.getLangOpts().CPlusPlus0x && Base->isVirtual())
Sean Hunt661c67a2011-06-21 23:42:56 +00007471 continue;
7472
Douglas Gregord3c35902010-07-01 16:36:15 +00007473 assert(!Base->getType()->isDependentType() &&
7474 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007475 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smithb9d0b762012-07-27 04:22:15 +00007476 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0))
7477 return false;
Sean Hunt661c67a2011-06-21 23:42:56 +00007478 }
7479
Richard Smithebaf0e62011-10-18 20:49:44 +00007480 // In C++11, the above citation has "or virtual" added
Richard Smithb9d0b762012-07-27 04:22:15 +00007481 if (S.getLangOpts().CPlusPlus0x) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007482 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7483 BaseEnd = ClassDecl->vbases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007484 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007485 assert(!Base->getType()->isDependentType() &&
7486 "Cannot generate implicit members for class with dependent bases.");
7487 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
Richard Smithb9d0b762012-07-27 04:22:15 +00007488 if (!S.LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7489 false, 0))
7490 return false;
Sean Hunt661c67a2011-06-21 23:42:56 +00007491 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007492 }
7493
7494 // -- for all the nonstatic data members of X that are of a class
7495 // type M (or array thereof), each such class type has a copy
7496 // assignment operator whose parameter is of type const M&,
7497 // const volatile M& or M.
7498 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7499 FieldEnd = ClassDecl->field_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00007500 Field != FieldEnd; ++Field) {
7501 QualType FieldType = S.Context.getBaseElementType(Field->getType());
7502 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl())
7503 if (!S.LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7504 false, 0))
7505 return false;
Douglas Gregord3c35902010-07-01 16:36:15 +00007506 }
7507
7508 // Otherwise, the implicitly declared copy assignment operator will
7509 // have the form
7510 //
7511 // X& X::operator=(X&)
Richard Smithb9d0b762012-07-27 04:22:15 +00007512
7513 return true;
7514}
7515
7516Sema::ImplicitExceptionSpecification
7517Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
7518 CXXRecordDecl *ClassDecl = MD->getParent();
7519
7520 ImplicitExceptionSpecification ExceptSpec(*this);
7521 if (ClassDecl->isInvalidDecl())
7522 return ExceptSpec;
7523
7524 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
7525 assert(T->getNumArgs() == 1 && "not a copy assignment op");
7526 unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
7527
Douglas Gregorb87786f2010-07-01 17:48:08 +00007528 // C++ [except.spec]p14:
Richard Smithb9d0b762012-07-27 04:22:15 +00007529 // An implicitly declared special member function (Clause 12) shall have an
Douglas Gregorb87786f2010-07-01 17:48:08 +00007530 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007531
7532 // It is unspecified whether or not an implicit copy assignment operator
7533 // attempts to deduplicate calls to assignment operators of virtual bases are
7534 // made. As such, this exception specification is effectively unspecified.
7535 // Based on a similar decision made for constness in C++0x, we're erring on
7536 // the side of assuming such calls to be made regardless of whether they
7537 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007538 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7539 BaseEnd = ClassDecl->bases_end();
7540 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007541 if (Base->isVirtual())
7542 continue;
7543
Douglas Gregora376d102010-07-02 21:50:04 +00007544 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007545 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007546 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7547 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007548 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Douglas Gregorb87786f2010-07-01 17:48:08 +00007549 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007550
7551 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7552 BaseEnd = ClassDecl->vbases_end();
7553 Base != BaseEnd; ++Base) {
7554 CXXRecordDecl *BaseClassDecl
7555 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7556 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7557 ArgQuals, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007558 ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
Sean Hunt661c67a2011-06-21 23:42:56 +00007559 }
7560
Douglas Gregorb87786f2010-07-01 17:48:08 +00007561 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7562 FieldEnd = ClassDecl->field_end();
7563 Field != FieldEnd;
7564 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007565 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007566 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7567 if (CXXMethodDecl *CopyAssign =
Richard Smith6a06e5f2012-07-18 03:36:00 +00007568 LookupCopyingAssignment(FieldClassDecl,
7569 ArgQuals | FieldType.getCVRQualifiers(),
7570 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007571 ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007572 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007573 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007574
Richard Smithb9d0b762012-07-27 04:22:15 +00007575 return ExceptSpec;
Sean Hunt30de05c2011-05-14 05:23:20 +00007576}
7577
7578CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7579 // Note: The following rules are largely analoguous to the copy
7580 // constructor rules. Note that virtual bases are not taken into account
7581 // for determining the argument type of the operator. Note also that
7582 // operators taking an object instead of a reference are allowed.
7583
Sean Hunt30de05c2011-05-14 05:23:20 +00007584 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7585 QualType RetType = Context.getLValueReferenceType(ArgType);
Richard Smithb9d0b762012-07-27 04:22:15 +00007586 if (isImplicitCopyAssignmentArgConst(*this, ClassDecl))
Sean Hunt30de05c2011-05-14 05:23:20 +00007587 ArgType = ArgType.withConst();
7588 ArgType = Context.getLValueReferenceType(ArgType);
7589
Douglas Gregord3c35902010-07-01 16:36:15 +00007590 // An implicitly-declared copy assignment operator is an inline public
7591 // member of its class.
7592 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007593 SourceLocation ClassLoc = ClassDecl->getLocation();
7594 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007595 CXXMethodDecl *CopyAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00007596 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Douglas Gregord3c35902010-07-01 16:36:15 +00007597 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007598 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007599 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007600 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007601 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007602 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007603 CopyAssignment->setImplicit();
7604 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Richard Smithb9d0b762012-07-27 04:22:15 +00007605
7606 // Build an exception specification pointing back at this member.
7607 FunctionProtoType::ExtProtoInfo EPI;
7608 EPI.ExceptionSpecType = EST_Unevaluated;
7609 EPI.ExceptionSpecDecl = CopyAssignment;
7610 CopyAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
7611
Douglas Gregord3c35902010-07-01 16:36:15 +00007612 // Add the parameter to the operator.
7613 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007614 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007615 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007616 SC_None,
7617 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007618 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007619
Douglas Gregora376d102010-07-02 21:50:04 +00007620 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007621 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007622
Douglas Gregor23c94db2010-07-02 17:43:08 +00007623 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007624 PushOnScopeChains(CopyAssignment, S, false);
7625 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007626
Nico Weberafcc96a2012-01-23 03:19:29 +00007627 // C++0x [class.copy]p19:
7628 // .... If the class definition does not explicitly declare a copy
7629 // assignment operator, there is no user-declared move constructor, and
7630 // there is no user-declared move assignment operator, a copy assignment
7631 // operator is implicitly declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00007632 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007633 CopyAssignment->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00007634
Douglas Gregord3c35902010-07-01 16:36:15 +00007635 AddOverriddenMethods(ClassDecl, CopyAssignment);
7636 return CopyAssignment;
7637}
7638
Douglas Gregor06a9f362010-05-01 20:49:11 +00007639void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7640 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007641 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007642 CopyAssignOperator->isOverloadedOperator() &&
7643 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00007644 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7645 !CopyAssignOperator->isDeleted()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007646 "DefineImplicitCopyAssignment called for wrong function");
7647
7648 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7649
7650 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7651 CopyAssignOperator->setInvalidDecl();
7652 return;
7653 }
7654
7655 CopyAssignOperator->setUsed();
7656
7657 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007658 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007659
7660 // C++0x [class.copy]p30:
7661 // The implicitly-defined or explicitly-defaulted copy assignment operator
7662 // for a non-union class X performs memberwise copy assignment of its
7663 // subobjects. The direct base classes of X are assigned first, in the
7664 // order of their declaration in the base-specifier-list, and then the
7665 // immediate non-static data members of X are assigned, in the order in
7666 // which they were declared in the class definition.
7667
7668 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00007669 SmallVector<Stmt*, 8> Statements;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007670
7671 // The parameter for the "other" object, which we are copying from.
7672 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7673 Qualifiers OtherQuals = Other->getType().getQualifiers();
7674 QualType OtherRefType = Other->getType();
7675 if (const LValueReferenceType *OtherRef
7676 = OtherRefType->getAs<LValueReferenceType>()) {
7677 OtherRefType = OtherRef->getPointeeType();
7678 OtherQuals = OtherRefType.getQualifiers();
7679 }
7680
7681 // Our location for everything implicitly-generated.
7682 SourceLocation Loc = CopyAssignOperator->getLocation();
7683
7684 // Construct a reference to the "other" object. We'll be using this
7685 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007686 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007687 assert(OtherRef && "Reference to parameter cannot fail!");
7688
7689 // Construct the "this" pointer. We'll be using this throughout the generated
7690 // ASTs.
7691 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7692 assert(This && "Reference to this cannot fail!");
7693
7694 // Assign base classes.
7695 bool Invalid = false;
7696 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7697 E = ClassDecl->bases_end(); Base != E; ++Base) {
7698 // Form the assignment:
7699 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7700 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007701 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007702 Invalid = true;
7703 continue;
7704 }
7705
John McCallf871d0c2010-08-07 06:22:56 +00007706 CXXCastPath BasePath;
7707 BasePath.push_back(Base);
7708
Douglas Gregor06a9f362010-05-01 20:49:11 +00007709 // Construct the "from" expression, which is an implicit cast to the
7710 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007711 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007712 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7713 CK_UncheckedDerivedToBase,
7714 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007715
7716 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007717 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007718
7719 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007720 To = ImpCastExprToType(To.take(),
7721 Context.getCVRQualifiedType(BaseType,
7722 CopyAssignOperator->getTypeQualifiers()),
7723 CK_UncheckedDerivedToBase,
7724 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007725
7726 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007727 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007728 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007729 /*CopyingBaseSubobject=*/true,
7730 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007731 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007732 Diag(CurrentLocation, diag::note_member_synthesized_at)
7733 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7734 CopyAssignOperator->setInvalidDecl();
7735 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007736 }
7737
7738 // Success! Record the copy.
7739 Statements.push_back(Copy.takeAs<Expr>());
7740 }
7741
7742 // \brief Reference to the __builtin_memcpy function.
7743 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007744 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007745 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007746
7747 // Assign non-static members.
7748 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7749 FieldEnd = ClassDecl->field_end();
7750 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00007751 if (Field->isUnnamedBitfield())
7752 continue;
7753
Douglas Gregor06a9f362010-05-01 20:49:11 +00007754 // Check for members of reference type; we can't copy those.
7755 if (Field->getType()->isReferenceType()) {
7756 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7757 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7758 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007759 Diag(CurrentLocation, diag::note_member_synthesized_at)
7760 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007761 Invalid = true;
7762 continue;
7763 }
7764
7765 // Check for members of const-qualified, non-class type.
7766 QualType BaseType = Context.getBaseElementType(Field->getType());
7767 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7768 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7769 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7770 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007771 Diag(CurrentLocation, diag::note_member_synthesized_at)
7772 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007773 Invalid = true;
7774 continue;
7775 }
John McCallb77115d2011-06-17 00:18:42 +00007776
7777 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00007778 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7779 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007780
7781 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00007782 if (FieldType->isIncompleteArrayType()) {
7783 assert(ClassDecl->hasFlexibleArrayMember() &&
7784 "Incomplete array type is not valid");
7785 continue;
7786 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007787
7788 // Build references to the field in the object we're copying from and to.
7789 CXXScopeSpec SS; // Intentionally empty
7790 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7791 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00007792 MemberLookup.addDecl(*Field);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007793 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00007794 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00007795 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007796 SS, SourceLocation(), 0,
7797 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00007798 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00007799 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007800 SS, SourceLocation(), 0,
7801 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007802 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7803 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7804
7805 // If the field should be copied with __builtin_memcpy rather than via
7806 // explicit assignments, do so. This optimization only applies for arrays
7807 // of scalars and arrays of class type with trivial copy-assignment
7808 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00007809 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007810 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007811 // Compute the size of the memory buffer to be copied.
7812 QualType SizeType = Context.getSizeType();
7813 llvm::APInt Size(Context.getTypeSize(SizeType),
7814 Context.getTypeSizeInChars(BaseType).getQuantity());
7815 for (const ConstantArrayType *Array
7816 = Context.getAsConstantArrayType(FieldType);
7817 Array;
7818 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00007819 llvm::APInt ArraySize
7820 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007821 Size *= ArraySize;
7822 }
7823
7824 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00007825 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7826 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007827
7828 bool NeedsCollectableMemCpy =
7829 (BaseType->isRecordType() &&
7830 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7831
7832 if (NeedsCollectableMemCpy) {
7833 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00007834 // Create a reference to the __builtin_objc_memmove_collectable function.
7835 LookupResult R(*this,
7836 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007837 Loc, LookupOrdinaryName);
7838 LookupName(R, TUScope, true);
7839
7840 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7841 if (!CollectableMemCpy) {
7842 // Something went horribly wrong earlier, and we will have
7843 // complained about it.
7844 Invalid = true;
7845 continue;
7846 }
7847
7848 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7849 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007850 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007851 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7852 }
7853 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007854 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00007855 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007856 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7857 LookupOrdinaryName);
7858 LookupName(R, TUScope, true);
7859
7860 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7861 if (!BuiltinMemCpy) {
7862 // Something went horribly wrong earlier, and we will have complained
7863 // about it.
7864 Invalid = true;
7865 continue;
7866 }
7867
7868 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7869 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00007870 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007871 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7872 }
7873
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00007874 SmallVector<Expr*, 8> CallArgs;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007875 CallArgs.push_back(To.takeAs<Expr>());
7876 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007877 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00007878 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007879 if (NeedsCollectableMemCpy)
7880 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007881 CollectableMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007882 Loc, CallArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007883 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007884 else
7885 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00007886 BuiltinMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007887 Loc, CallArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007888 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00007889
Douglas Gregor06a9f362010-05-01 20:49:11 +00007890 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7891 Statements.push_back(Call.takeAs<Expr>());
7892 continue;
7893 }
7894
7895 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00007896 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007897 To.get(), From.get(),
7898 /*CopyingBaseSubobject=*/false,
7899 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007900 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007901 Diag(CurrentLocation, diag::note_member_synthesized_at)
7902 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7903 CopyAssignOperator->setInvalidDecl();
7904 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007905 }
7906
7907 // Success! Record the copy.
7908 Statements.push_back(Copy.takeAs<Stmt>());
7909 }
7910
7911 if (!Invalid) {
7912 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00007913 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007914
John McCall60d7b3a2010-08-24 06:29:42 +00007915 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00007916 if (Return.isInvalid())
7917 Invalid = true;
7918 else {
7919 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007920
7921 if (Trap.hasErrorOccurred()) {
7922 Diag(CurrentLocation, diag::note_member_synthesized_at)
7923 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7924 Invalid = true;
7925 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007926 }
7927 }
7928
7929 if (Invalid) {
7930 CopyAssignOperator->setInvalidDecl();
7931 return;
7932 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007933
7934 StmtResult Body;
7935 {
7936 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00007937 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007938 /*isStmtExpr=*/false);
7939 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7940 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007941 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007942
7943 if (ASTMutationListener *L = getASTMutationListener()) {
7944 L->CompletedImplicitDefinition(CopyAssignOperator);
7945 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007946}
7947
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007948Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00007949Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
7950 CXXRecordDecl *ClassDecl = MD->getParent();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007951
Richard Smithb9d0b762012-07-27 04:22:15 +00007952 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007953 if (ClassDecl->isInvalidDecl())
7954 return ExceptSpec;
7955
7956 // C++0x [except.spec]p14:
7957 // An implicitly declared special member function (Clause 12) shall have an
7958 // exception-specification. [...]
7959
7960 // It is unspecified whether or not an implicit move assignment operator
7961 // attempts to deduplicate calls to assignment operators of virtual bases are
7962 // made. As such, this exception specification is effectively unspecified.
7963 // Based on a similar decision made for constness in C++0x, we're erring on
7964 // the side of assuming such calls to be made regardless of whether they
7965 // actually happen.
7966 // Note that a move constructor is not implicitly declared when there are
7967 // virtual bases, but it can still be user-declared and explicitly defaulted.
7968 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7969 BaseEnd = ClassDecl->bases_end();
7970 Base != BaseEnd; ++Base) {
7971 if (Base->isVirtual())
7972 continue;
7973
7974 CXXRecordDecl *BaseClassDecl
7975 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7976 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00007977 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007978 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007979 }
7980
7981 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7982 BaseEnd = ClassDecl->vbases_end();
7983 Base != BaseEnd; ++Base) {
7984 CXXRecordDecl *BaseClassDecl
7985 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7986 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
Richard Smith6a06e5f2012-07-18 03:36:00 +00007987 0, false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00007988 ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007989 }
7990
7991 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7992 FieldEnd = ClassDecl->field_end();
7993 Field != FieldEnd;
7994 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00007995 QualType FieldType = Context.getBaseElementType(Field->getType());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007996 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00007997 if (CXXMethodDecl *MoveAssign =
7998 LookupMovingAssignment(FieldClassDecl,
7999 FieldType.getCVRQualifiers(),
8000 false, 0))
Richard Smithe6975e92012-04-17 00:58:00 +00008001 ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008002 }
8003 }
8004
8005 return ExceptSpec;
8006}
8007
Richard Smith1c931be2012-04-02 18:40:40 +00008008/// Determine whether the class type has any direct or indirect virtual base
8009/// classes which have a non-trivial move assignment operator.
8010static bool
8011hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8012 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8013 BaseEnd = ClassDecl->vbases_end();
8014 Base != BaseEnd; ++Base) {
8015 CXXRecordDecl *BaseClass =
8016 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8017
8018 // Try to declare the move assignment. If it would be deleted, then the
8019 // class does not have a non-trivial move assignment.
8020 if (BaseClass->needsImplicitMoveAssignment())
8021 S.DeclareImplicitMoveAssignment(BaseClass);
8022
8023 // If the class has both a trivial move assignment and a non-trivial move
8024 // assignment, hasTrivialMoveAssignment() is false.
8025 if (BaseClass->hasDeclaredMoveAssignment() &&
8026 !BaseClass->hasTrivialMoveAssignment())
8027 return true;
8028 }
8029
8030 return false;
8031}
8032
8033/// Determine whether the given type either has a move constructor or is
8034/// trivially copyable.
8035static bool
8036hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8037 Type = S.Context.getBaseElementType(Type);
8038
8039 // FIXME: Technically, non-trivially-copyable non-class types, such as
8040 // reference types, are supposed to return false here, but that appears
8041 // to be a standard defect.
8042 CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
Richard Smith5d59b792012-04-25 18:28:49 +00008043 if (!ClassDecl || !ClassDecl->getDefinition())
Richard Smith1c931be2012-04-02 18:40:40 +00008044 return true;
8045
8046 if (Type.isTriviallyCopyableType(S.Context))
8047 return true;
8048
8049 if (IsConstructor) {
8050 if (ClassDecl->needsImplicitMoveConstructor())
8051 S.DeclareImplicitMoveConstructor(ClassDecl);
8052 return ClassDecl->hasDeclaredMoveConstructor();
8053 }
8054
8055 if (ClassDecl->needsImplicitMoveAssignment())
8056 S.DeclareImplicitMoveAssignment(ClassDecl);
8057 return ClassDecl->hasDeclaredMoveAssignment();
8058}
8059
8060/// Determine whether all non-static data members and direct or virtual bases
8061/// of class \p ClassDecl have either a move operation, or are trivially
8062/// copyable.
8063static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8064 bool IsConstructor) {
8065 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8066 BaseEnd = ClassDecl->bases_end();
8067 Base != BaseEnd; ++Base) {
8068 if (Base->isVirtual())
8069 continue;
8070
8071 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8072 return false;
8073 }
8074
8075 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8076 BaseEnd = ClassDecl->vbases_end();
8077 Base != BaseEnd; ++Base) {
8078 if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8079 return false;
8080 }
8081
8082 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8083 FieldEnd = ClassDecl->field_end();
8084 Field != FieldEnd; ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008085 if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
Richard Smith1c931be2012-04-02 18:40:40 +00008086 return false;
8087 }
8088
8089 return true;
8090}
8091
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008092CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008093 // C++11 [class.copy]p20:
8094 // If the definition of a class X does not explicitly declare a move
8095 // assignment operator, one will be implicitly declared as defaulted
8096 // if and only if:
8097 //
8098 // - [first 4 bullets]
8099 assert(ClassDecl->needsImplicitMoveAssignment());
8100
8101 // [Checked after we build the declaration]
8102 // - the move assignment operator would not be implicitly defined as
8103 // deleted,
8104
8105 // [DR1402]:
8106 // - X has no direct or indirect virtual base class with a non-trivial
8107 // move assignment operator, and
8108 // - each of X's non-static data members and direct or virtual base classes
8109 // has a type that either has a move assignment operator or is trivially
8110 // copyable.
8111 if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8112 !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8113 ClassDecl->setFailedImplicitMoveAssignment();
8114 return 0;
8115 }
8116
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008117 // Note: The following rules are largely analoguous to the move
8118 // constructor rules.
8119
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008120 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8121 QualType RetType = Context.getLValueReferenceType(ArgType);
8122 ArgType = Context.getRValueReferenceType(ArgType);
8123
8124 // An implicitly-declared move assignment operator is an inline public
8125 // member of its class.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008126 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8127 SourceLocation ClassLoc = ClassDecl->getLocation();
8128 DeclarationNameInfo NameInfo(Name, ClassLoc);
8129 CXXMethodDecl *MoveAssignment
Richard Smithb9d0b762012-07-27 04:22:15 +00008130 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008131 /*TInfo=*/0, /*isStatic=*/false,
8132 /*StorageClassAsWritten=*/SC_None,
8133 /*isInline=*/true,
8134 /*isConstexpr=*/false,
8135 SourceLocation());
8136 MoveAssignment->setAccess(AS_public);
8137 MoveAssignment->setDefaulted();
8138 MoveAssignment->setImplicit();
8139 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8140
Richard Smithb9d0b762012-07-27 04:22:15 +00008141 // Build an exception specification pointing back at this member.
8142 FunctionProtoType::ExtProtoInfo EPI;
8143 EPI.ExceptionSpecType = EST_Unevaluated;
8144 EPI.ExceptionSpecDecl = MoveAssignment;
8145 MoveAssignment->setType(Context.getFunctionType(RetType, &ArgType, 1, EPI));
8146
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008147 // Add the parameter to the operator.
8148 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8149 ClassLoc, ClassLoc, /*Id=*/0,
8150 ArgType, /*TInfo=*/0,
8151 SC_None,
8152 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008153 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008154
8155 // Note that we have added this copy-assignment operator.
8156 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8157
8158 // C++0x [class.copy]p9:
8159 // If the definition of a class X does not explicitly declare a move
8160 // assignment operator, one will be implicitly declared as defaulted if and
8161 // only if:
8162 // [...]
8163 // - the move assignment operator would not be implicitly defined as
8164 // deleted.
Richard Smith7d5088a2012-02-18 02:02:13 +00008165 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008166 // Cache this result so that we don't try to generate this over and over
8167 // on every lookup, leaking memory and wasting time.
8168 ClassDecl->setFailedImplicitMoveAssignment();
8169 return 0;
8170 }
8171
8172 if (Scope *S = getScopeForContext(ClassDecl))
8173 PushOnScopeChains(MoveAssignment, S, false);
8174 ClassDecl->addDecl(MoveAssignment);
8175
8176 AddOverriddenMethods(ClassDecl, MoveAssignment);
8177 return MoveAssignment;
8178}
8179
8180void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8181 CXXMethodDecl *MoveAssignOperator) {
8182 assert((MoveAssignOperator->isDefaulted() &&
8183 MoveAssignOperator->isOverloadedOperator() &&
8184 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
Richard Smith03f68782012-02-26 07:51:39 +00008185 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8186 !MoveAssignOperator->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008187 "DefineImplicitMoveAssignment called for wrong function");
8188
8189 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8190
8191 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8192 MoveAssignOperator->setInvalidDecl();
8193 return;
8194 }
8195
8196 MoveAssignOperator->setUsed();
8197
8198 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8199 DiagnosticErrorTrap Trap(Diags);
8200
8201 // C++0x [class.copy]p28:
8202 // The implicitly-defined or move assignment operator for a non-union class
8203 // X performs memberwise move assignment of its subobjects. The direct base
8204 // classes of X are assigned first, in the order of their declaration in the
8205 // base-specifier-list, and then the immediate non-static data members of X
8206 // are assigned, in the order in which they were declared in the class
8207 // definition.
8208
8209 // The statements that form the synthesized function body.
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008210 SmallVector<Stmt*, 8> Statements;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008211
8212 // The parameter for the "other" object, which we are move from.
8213 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8214 QualType OtherRefType = Other->getType()->
8215 getAs<RValueReferenceType>()->getPointeeType();
8216 assert(OtherRefType.getQualifiers() == 0 &&
8217 "Bad argument type of defaulted move assignment");
8218
8219 // Our location for everything implicitly-generated.
8220 SourceLocation Loc = MoveAssignOperator->getLocation();
8221
8222 // Construct a reference to the "other" object. We'll be using this
8223 // throughout the generated ASTs.
8224 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8225 assert(OtherRef && "Reference to parameter cannot fail!");
8226 // Cast to rvalue.
8227 OtherRef = CastForMoving(*this, OtherRef);
8228
8229 // Construct the "this" pointer. We'll be using this throughout the generated
8230 // ASTs.
8231 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8232 assert(This && "Reference to this cannot fail!");
Richard Smith1c931be2012-04-02 18:40:40 +00008233
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008234 // Assign base classes.
8235 bool Invalid = false;
8236 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8237 E = ClassDecl->bases_end(); Base != E; ++Base) {
8238 // Form the assignment:
8239 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8240 QualType BaseType = Base->getType().getUnqualifiedType();
8241 if (!BaseType->isRecordType()) {
8242 Invalid = true;
8243 continue;
8244 }
8245
8246 CXXCastPath BasePath;
8247 BasePath.push_back(Base);
8248
8249 // Construct the "from" expression, which is an implicit cast to the
8250 // appropriately-qualified base type.
8251 Expr *From = OtherRef;
8252 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008253 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008254
8255 // Dereference "this".
8256 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8257
8258 // Implicitly cast "this" to the appropriately-qualified base type.
8259 To = ImpCastExprToType(To.take(),
8260 Context.getCVRQualifiedType(BaseType,
8261 MoveAssignOperator->getTypeQualifiers()),
8262 CK_UncheckedDerivedToBase,
8263 VK_LValue, &BasePath);
8264
8265 // Build the move.
8266 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8267 To.get(), From,
8268 /*CopyingBaseSubobject=*/true,
8269 /*Copying=*/false);
8270 if (Move.isInvalid()) {
8271 Diag(CurrentLocation, diag::note_member_synthesized_at)
8272 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8273 MoveAssignOperator->setInvalidDecl();
8274 return;
8275 }
8276
8277 // Success! Record the move.
8278 Statements.push_back(Move.takeAs<Expr>());
8279 }
8280
8281 // \brief Reference to the __builtin_memcpy function.
8282 Expr *BuiltinMemCpyRef = 0;
8283 // \brief Reference to the __builtin_objc_memmove_collectable function.
8284 Expr *CollectableMemCpyRef = 0;
8285
8286 // Assign non-static members.
8287 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8288 FieldEnd = ClassDecl->field_end();
8289 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008290 if (Field->isUnnamedBitfield())
8291 continue;
8292
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008293 // Check for members of reference type; we can't move those.
8294 if (Field->getType()->isReferenceType()) {
8295 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8296 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8297 Diag(Field->getLocation(), diag::note_declared_at);
8298 Diag(CurrentLocation, diag::note_member_synthesized_at)
8299 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8300 Invalid = true;
8301 continue;
8302 }
8303
8304 // Check for members of const-qualified, non-class type.
8305 QualType BaseType = Context.getBaseElementType(Field->getType());
8306 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8307 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8308 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8309 Diag(Field->getLocation(), diag::note_declared_at);
8310 Diag(CurrentLocation, diag::note_member_synthesized_at)
8311 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8312 Invalid = true;
8313 continue;
8314 }
8315
8316 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008317 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8318 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008319
8320 QualType FieldType = Field->getType().getNonReferenceType();
8321 if (FieldType->isIncompleteArrayType()) {
8322 assert(ClassDecl->hasFlexibleArrayMember() &&
8323 "Incomplete array type is not valid");
8324 continue;
8325 }
8326
8327 // Build references to the field in the object we're copying from and to.
8328 CXXScopeSpec SS; // Intentionally empty
8329 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8330 LookupMemberName);
David Blaikie581deb32012-06-06 20:45:41 +00008331 MemberLookup.addDecl(*Field);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008332 MemberLookup.resolveKind();
8333 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8334 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008335 SS, SourceLocation(), 0,
8336 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008337 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8338 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008339 SS, SourceLocation(), 0,
8340 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008341 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8342 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8343
8344 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8345 "Member reference with rvalue base must be rvalue except for reference "
8346 "members, which aren't allowed for move assignment.");
8347
8348 // If the field should be copied with __builtin_memcpy rather than via
8349 // explicit assignments, do so. This optimization only applies for arrays
8350 // of scalars and arrays of class type with trivial move-assignment
8351 // operators.
8352 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8353 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8354 // Compute the size of the memory buffer to be copied.
8355 QualType SizeType = Context.getSizeType();
8356 llvm::APInt Size(Context.getTypeSize(SizeType),
8357 Context.getTypeSizeInChars(BaseType).getQuantity());
8358 for (const ConstantArrayType *Array
8359 = Context.getAsConstantArrayType(FieldType);
8360 Array;
8361 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8362 llvm::APInt ArraySize
8363 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8364 Size *= ArraySize;
8365 }
8366
Douglas Gregor45d3d712011-09-01 02:09:07 +00008367 // Take the address of the field references for "from" and "to". We
8368 // directly construct UnaryOperators here because semantic analysis
8369 // does not permit us to take the address of an xvalue.
8370 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8371 Context.getPointerType(From.get()->getType()),
8372 VK_RValue, OK_Ordinary, Loc);
8373 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8374 Context.getPointerType(To.get()->getType()),
8375 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008376
8377 bool NeedsCollectableMemCpy =
8378 (BaseType->isRecordType() &&
8379 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8380
8381 if (NeedsCollectableMemCpy) {
8382 if (!CollectableMemCpyRef) {
8383 // Create a reference to the __builtin_objc_memmove_collectable function.
8384 LookupResult R(*this,
8385 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8386 Loc, LookupOrdinaryName);
8387 LookupName(R, TUScope, true);
8388
8389 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8390 if (!CollectableMemCpy) {
8391 // Something went horribly wrong earlier, and we will have
8392 // complained about it.
8393 Invalid = true;
8394 continue;
8395 }
8396
8397 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8398 CollectableMemCpy->getType(),
8399 VK_LValue, Loc, 0).take();
8400 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8401 }
8402 }
8403 // Create a reference to the __builtin_memcpy builtin function.
8404 else if (!BuiltinMemCpyRef) {
8405 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8406 LookupOrdinaryName);
8407 LookupName(R, TUScope, true);
8408
8409 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8410 if (!BuiltinMemCpy) {
8411 // Something went horribly wrong earlier, and we will have complained
8412 // about it.
8413 Invalid = true;
8414 continue;
8415 }
8416
8417 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8418 BuiltinMemCpy->getType(),
8419 VK_LValue, Loc, 0).take();
8420 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8421 }
8422
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00008423 SmallVector<Expr*, 8> CallArgs;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008424 CallArgs.push_back(To.takeAs<Expr>());
8425 CallArgs.push_back(From.takeAs<Expr>());
8426 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8427 ExprResult Call = ExprError();
8428 if (NeedsCollectableMemCpy)
8429 Call = ActOnCallExpr(/*Scope=*/0,
8430 CollectableMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008431 Loc, CallArgs,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008432 Loc);
8433 else
8434 Call = ActOnCallExpr(/*Scope=*/0,
8435 BuiltinMemCpyRef,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008436 Loc, CallArgs,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008437 Loc);
8438
8439 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8440 Statements.push_back(Call.takeAs<Expr>());
8441 continue;
8442 }
8443
8444 // Build the move of this field.
8445 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8446 To.get(), From.get(),
8447 /*CopyingBaseSubobject=*/false,
8448 /*Copying=*/false);
8449 if (Move.isInvalid()) {
8450 Diag(CurrentLocation, diag::note_member_synthesized_at)
8451 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8452 MoveAssignOperator->setInvalidDecl();
8453 return;
8454 }
8455
8456 // Success! Record the copy.
8457 Statements.push_back(Move.takeAs<Stmt>());
8458 }
8459
8460 if (!Invalid) {
8461 // Add a "return *this;"
8462 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8463
8464 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8465 if (Return.isInvalid())
8466 Invalid = true;
8467 else {
8468 Statements.push_back(Return.takeAs<Stmt>());
8469
8470 if (Trap.hasErrorOccurred()) {
8471 Diag(CurrentLocation, diag::note_member_synthesized_at)
8472 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8473 Invalid = true;
8474 }
8475 }
8476 }
8477
8478 if (Invalid) {
8479 MoveAssignOperator->setInvalidDecl();
8480 return;
8481 }
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008482
8483 StmtResult Body;
8484 {
8485 CompoundScopeRAII CompoundScope(*this);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00008486 Body = ActOnCompoundStmt(Loc, Loc, Statements,
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008487 /*isStmtExpr=*/false);
8488 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8489 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008490 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8491
8492 if (ASTMutationListener *L = getASTMutationListener()) {
8493 L->CompletedImplicitDefinition(MoveAssignOperator);
8494 }
8495}
8496
Richard Smithb9d0b762012-07-27 04:22:15 +00008497/// Determine whether an implicit copy constructor for ClassDecl has a const
8498/// argument.
8499/// FIXME: It ought to be possible to store this on the record.
8500static bool isImplicitCopyCtorArgConst(Sema &S, CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008501 if (ClassDecl->isInvalidDecl())
Richard Smithb9d0b762012-07-27 04:22:15 +00008502 return true;
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008503
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008504 // C++ [class.copy]p5:
8505 // The implicitly-declared copy constructor for a class X will
8506 // have the form
8507 //
8508 // X::X(const X&)
8509 //
8510 // if
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008511 // -- each direct or virtual base class B of X has a copy
8512 // constructor whose first parameter is of type const B& or
8513 // const volatile B&, and
8514 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8515 BaseEnd = ClassDecl->bases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008516 Base != BaseEnd; ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008517 // Virtual bases are handled below.
8518 if (Base->isVirtual())
8519 continue;
Richard Smithb9d0b762012-07-27 04:22:15 +00008520
Douglas Gregor22584312010-07-02 23:41:54 +00008521 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008522 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smithb9d0b762012-07-27 04:22:15 +00008523 // FIXME: This lookup is wrong. If the copy ctor for a member or base is
8524 // ambiguous, we should still produce a constructor with a const-qualified
8525 // parameter.
8526 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8527 return false;
Douglas Gregor598a8542010-07-01 18:27:03 +00008528 }
8529
8530 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8531 BaseEnd = ClassDecl->vbases_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008532 Base != BaseEnd; ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008533 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008534 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Richard Smithb9d0b762012-07-27 04:22:15 +00008535 if (!S.LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const))
8536 return false;
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008537 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008538
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008539 // -- for all the nonstatic data members of X that are of a
8540 // class type M (or array thereof), each such class type
8541 // has a copy constructor whose first parameter is of type
8542 // const M& or const volatile M&.
8543 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8544 FieldEnd = ClassDecl->field_end();
Richard Smithb9d0b762012-07-27 04:22:15 +00008545 Field != FieldEnd; ++Field) {
8546 QualType FieldType = S.Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008547 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Richard Smithb9d0b762012-07-27 04:22:15 +00008548 if (!S.LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const))
8549 return false;
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008550 }
8551 }
Richard Smithb9d0b762012-07-27 04:22:15 +00008552
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008553 // Otherwise, the implicitly declared copy constructor will have
8554 // the form
8555 //
8556 // X::X(X&)
Richard Smithb9d0b762012-07-27 04:22:15 +00008557
8558 return true;
8559}
8560
8561Sema::ImplicitExceptionSpecification
8562Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
8563 CXXRecordDecl *ClassDecl = MD->getParent();
8564
8565 ImplicitExceptionSpecification ExceptSpec(*this);
8566 if (ClassDecl->isInvalidDecl())
8567 return ExceptSpec;
8568
8569 const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8570 assert(T->getNumArgs() >= 1 && "not a copy ctor");
8571 unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8572
Douglas Gregor0d405db2010-07-01 20:59:04 +00008573 // C++ [except.spec]p14:
8574 // An implicitly declared special member function (Clause 12) shall have an
8575 // exception-specification. [...]
Douglas Gregor0d405db2010-07-01 20:59:04 +00008576 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8577 BaseEnd = ClassDecl->bases_end();
8578 Base != BaseEnd;
8579 ++Base) {
8580 // Virtual bases are handled below.
8581 if (Base->isVirtual())
8582 continue;
8583
Douglas Gregor22584312010-07-02 23:41:54 +00008584 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008585 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008586 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008587 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008588 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008589 }
8590 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8591 BaseEnd = ClassDecl->vbases_end();
8592 Base != BaseEnd;
8593 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008594 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008595 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008596 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008597 LookupCopyingConstructor(BaseClassDecl, Quals))
Richard Smithe6975e92012-04-17 00:58:00 +00008598 ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008599 }
8600 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8601 FieldEnd = ClassDecl->field_end();
8602 Field != FieldEnd;
8603 ++Field) {
David Blaikie262bc182012-04-30 02:36:29 +00008604 QualType FieldType = Context.getBaseElementType(Field->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008605 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8606 if (CXXConstructorDecl *CopyConstructor =
Richard Smith6a06e5f2012-07-18 03:36:00 +00008607 LookupCopyingConstructor(FieldClassDecl,
8608 Quals | FieldType.getCVRQualifiers()))
Richard Smithe6975e92012-04-17 00:58:00 +00008609 ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008610 }
8611 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008612
Richard Smithb9d0b762012-07-27 04:22:15 +00008613 return ExceptSpec;
Sean Hunt49634cf2011-05-13 06:10:58 +00008614}
8615
8616CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8617 CXXRecordDecl *ClassDecl) {
8618 // C++ [class.copy]p4:
8619 // If the class definition does not explicitly declare a copy
8620 // constructor, one is declared implicitly.
8621
Sean Hunt49634cf2011-05-13 06:10:58 +00008622 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8623 QualType ArgType = ClassType;
Richard Smithb9d0b762012-07-27 04:22:15 +00008624 bool Const = isImplicitCopyCtorArgConst(*this, ClassDecl);
Sean Hunt49634cf2011-05-13 06:10:58 +00008625 if (Const)
8626 ArgType = ArgType.withConst();
8627 ArgType = Context.getLValueReferenceType(ArgType);
Sean Hunt49634cf2011-05-13 06:10:58 +00008628
Richard Smith7756afa2012-06-10 05:43:50 +00008629 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8630 CXXCopyConstructor,
8631 Const);
8632
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008633 DeclarationName Name
8634 = Context.DeclarationNames.getCXXConstructorName(
8635 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008636 SourceLocation ClassLoc = ClassDecl->getLocation();
8637 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008638
8639 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008640 // member of its class.
8641 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008642 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008643 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008644 Constexpr);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008645 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008646 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008647 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008648
Richard Smithb9d0b762012-07-27 04:22:15 +00008649 // Build an exception specification pointing back at this member.
8650 FunctionProtoType::ExtProtoInfo EPI;
8651 EPI.ExceptionSpecType = EST_Unevaluated;
8652 EPI.ExceptionSpecDecl = CopyConstructor;
8653 CopyConstructor->setType(
8654 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8655
Douglas Gregor22584312010-07-02 23:41:54 +00008656 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008657 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8658
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008659 // Add the parameter to the constructor.
8660 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008661 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008662 /*IdentifierInfo=*/0,
8663 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008664 SC_None,
8665 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008666 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008667
Douglas Gregor23c94db2010-07-02 17:43:08 +00008668 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008669 PushOnScopeChains(CopyConstructor, S, false);
8670 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008671
Nico Weberafcc96a2012-01-23 03:19:29 +00008672 // C++11 [class.copy]p8:
8673 // ... If the class definition does not explicitly declare a copy
8674 // constructor, there is no user-declared move constructor, and there is no
8675 // user-declared move assignment operator, a copy constructor is implicitly
8676 // declared as defaulted.
Richard Smith6c4c36c2012-03-30 20:53:28 +00008677 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008678 CopyConstructor->setDeletedAsWritten();
Richard Smith6c4c36c2012-03-30 20:53:28 +00008679
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008680 return CopyConstructor;
8681}
8682
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008683void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008684 CXXConstructorDecl *CopyConstructor) {
8685 assert((CopyConstructor->isDefaulted() &&
8686 CopyConstructor->isCopyConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008687 !CopyConstructor->doesThisDeclarationHaveABody() &&
8688 !CopyConstructor->isDeleted()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008689 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008690
Anders Carlsson63010a72010-04-23 16:24:12 +00008691 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008692 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008693
Douglas Gregor39957dc2010-05-01 15:04:51 +00008694 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008695 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008696
Sean Huntcbb67482011-01-08 20:30:50 +00008697 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008698 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008699 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008700 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008701 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008702 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008703 Sema::CompoundScopeRAII CompoundScope(*this);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008704 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8705 CopyConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00008706 MultiStmtArg(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008707 /*isStmtExpr=*/false)
8708 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008709 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008710 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008711
8712 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008713 if (ASTMutationListener *L = getASTMutationListener()) {
8714 L->CompletedImplicitDefinition(CopyConstructor);
8715 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008716}
8717
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008718Sema::ImplicitExceptionSpecification
Richard Smithb9d0b762012-07-27 04:22:15 +00008719Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
8720 CXXRecordDecl *ClassDecl = MD->getParent();
8721
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008722 // C++ [except.spec]p14:
8723 // An implicitly declared special member function (Clause 12) shall have an
8724 // exception-specification. [...]
Richard Smithe6975e92012-04-17 00:58:00 +00008725 ImplicitExceptionSpecification ExceptSpec(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008726 if (ClassDecl->isInvalidDecl())
8727 return ExceptSpec;
8728
8729 // Direct base-class constructors.
8730 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8731 BEnd = ClassDecl->bases_end();
8732 B != BEnd; ++B) {
8733 if (B->isVirtual()) // Handled below.
8734 continue;
8735
8736 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8737 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00008738 CXXConstructorDecl *Constructor =
8739 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008740 // If this is a deleted function, add it anyway. This might be conformant
8741 // with the standard. This might not. I'm not sure. It might not matter.
8742 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008743 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008744 }
8745 }
8746
8747 // Virtual base-class constructors.
8748 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8749 BEnd = ClassDecl->vbases_end();
8750 B != BEnd; ++B) {
8751 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8752 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Richard Smith6a06e5f2012-07-18 03:36:00 +00008753 CXXConstructorDecl *Constructor =
8754 LookupMovingConstructor(BaseClassDecl, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008755 // If this is a deleted function, add it anyway. This might be conformant
8756 // with the standard. This might not. I'm not sure. It might not matter.
8757 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008758 ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008759 }
8760 }
8761
8762 // Field constructors.
8763 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8764 FEnd = ClassDecl->field_end();
8765 F != FEnd; ++F) {
Richard Smith6a06e5f2012-07-18 03:36:00 +00008766 QualType FieldType = Context.getBaseElementType(F->getType());
8767 if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
8768 CXXConstructorDecl *Constructor =
8769 LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008770 // If this is a deleted function, add it anyway. This might be conformant
8771 // with the standard. This might not. I'm not sure. It might not matter.
8772 // In particular, the problem is that this function never gets called. It
8773 // might just be ill-formed because this function attempts to refer to
8774 // a deleted function here.
8775 if (Constructor)
Richard Smithe6975e92012-04-17 00:58:00 +00008776 ExceptSpec.CalledDecl(F->getLocation(), Constructor);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008777 }
8778 }
8779
8780 return ExceptSpec;
8781}
8782
8783CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8784 CXXRecordDecl *ClassDecl) {
Richard Smith1c931be2012-04-02 18:40:40 +00008785 // C++11 [class.copy]p9:
8786 // If the definition of a class X does not explicitly declare a move
8787 // constructor, one will be implicitly declared as defaulted if and only if:
8788 //
8789 // - [first 4 bullets]
8790 assert(ClassDecl->needsImplicitMoveConstructor());
8791
8792 // [Checked after we build the declaration]
8793 // - the move assignment operator would not be implicitly defined as
8794 // deleted,
8795
8796 // [DR1402]:
8797 // - each of X's non-static data members and direct or virtual base classes
8798 // has a type that either has a move constructor or is trivially copyable.
8799 if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8800 ClassDecl->setFailedImplicitMoveConstructor();
8801 return 0;
8802 }
8803
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008804 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8805 QualType ArgType = Context.getRValueReferenceType(ClassType);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008806
Richard Smith7756afa2012-06-10 05:43:50 +00008807 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8808 CXXMoveConstructor,
8809 false);
8810
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008811 DeclarationName Name
8812 = Context.DeclarationNames.getCXXConstructorName(
8813 Context.getCanonicalType(ClassType));
8814 SourceLocation ClassLoc = ClassDecl->getLocation();
8815 DeclarationNameInfo NameInfo(Name, ClassLoc);
8816
8817 // C++0x [class.copy]p11:
8818 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008819 // member of its class.
8820 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
Richard Smithb9d0b762012-07-27 04:22:15 +00008821 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
Richard Smith61802452011-12-22 02:22:31 +00008822 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
Richard Smith7756afa2012-06-10 05:43:50 +00008823 Constexpr);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008824 MoveConstructor->setAccess(AS_public);
8825 MoveConstructor->setDefaulted();
8826 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008827
Richard Smithb9d0b762012-07-27 04:22:15 +00008828 // Build an exception specification pointing back at this member.
8829 FunctionProtoType::ExtProtoInfo EPI;
8830 EPI.ExceptionSpecType = EST_Unevaluated;
8831 EPI.ExceptionSpecDecl = MoveConstructor;
8832 MoveConstructor->setType(
8833 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
8834
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008835 // Add the parameter to the constructor.
8836 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8837 ClassLoc, ClassLoc,
8838 /*IdentifierInfo=*/0,
8839 ArgType, /*TInfo=*/0,
8840 SC_None,
8841 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008842 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008843
8844 // C++0x [class.copy]p9:
8845 // If the definition of a class X does not explicitly declare a move
8846 // constructor, one will be implicitly declared as defaulted if and only if:
8847 // [...]
8848 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008849 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008850 // Cache this result so that we don't try to generate this over and over
8851 // on every lookup, leaking memory and wasting time.
8852 ClassDecl->setFailedImplicitMoveConstructor();
8853 return 0;
8854 }
8855
8856 // Note that we have declared this constructor.
8857 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8858
8859 if (Scope *S = getScopeForContext(ClassDecl))
8860 PushOnScopeChains(MoveConstructor, S, false);
8861 ClassDecl->addDecl(MoveConstructor);
8862
8863 return MoveConstructor;
8864}
8865
8866void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8867 CXXConstructorDecl *MoveConstructor) {
8868 assert((MoveConstructor->isDefaulted() &&
8869 MoveConstructor->isMoveConstructor() &&
Richard Smith03f68782012-02-26 07:51:39 +00008870 !MoveConstructor->doesThisDeclarationHaveABody() &&
8871 !MoveConstructor->isDeleted()) &&
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008872 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8873
8874 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8875 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8876
8877 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8878 DiagnosticErrorTrap Trap(Diags);
8879
8880 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8881 Trap.hasErrorOccurred()) {
8882 Diag(CurrentLocation, diag::note_member_synthesized_at)
8883 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8884 MoveConstructor->setInvalidDecl();
8885 } else {
Dmitri Gribenko625bb562012-02-14 22:14:32 +00008886 Sema::CompoundScopeRAII CompoundScope(*this);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008887 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8888 MoveConstructor->getLocation(),
Benjamin Kramer5354e772012-08-23 23:38:35 +00008889 MultiStmtArg(),
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008890 /*isStmtExpr=*/false)
8891 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008892 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008893 }
8894
8895 MoveConstructor->setUsed();
8896
8897 if (ASTMutationListener *L = getASTMutationListener()) {
8898 L->CompletedImplicitDefinition(MoveConstructor);
8899 }
8900}
8901
Douglas Gregore4e68d42012-02-15 19:33:52 +00008902bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8903 return FD->isDeleted() &&
8904 (FD->isDefaulted() || FD->isImplicit()) &&
8905 isa<CXXMethodDecl>(FD);
8906}
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008907
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008908/// \brief Mark the call operator of the given lambda closure type as "used".
8909static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8910 CXXMethodDecl *CallOperator
Douglas Gregorac1303e2012-02-22 05:02:47 +00008911 = cast<CXXMethodDecl>(
8912 *Lambda->lookup(
8913 S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008914 CallOperator->setReferenced();
8915 CallOperator->setUsed();
8916}
8917
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008918void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8919 SourceLocation CurrentLocation,
8920 CXXConversionDecl *Conv)
8921{
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008922 CXXRecordDecl *Lambda = Conv->getParent();
8923
8924 // Make sure that the lambda call operator is marked used.
8925 markLambdaCallOperatorUsed(*this, Lambda);
8926
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008927 Conv->setUsed();
8928
8929 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8930 DiagnosticErrorTrap Trap(Diags);
8931
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008932 // Return the address of the __invoke function.
8933 DeclarationName InvokeName = &Context.Idents.get("__invoke");
8934 CXXMethodDecl *Invoke
8935 = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8936 Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8937 VK_LValue, Conv->getLocation()).take();
8938 assert(FunctionRef && "Can't refer to __invoke function?");
8939 Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8940 Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8941 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008942 Conv->getLocation()));
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008943
8944 // Fill in the __invoke function with a dummy implementation. IR generation
8945 // will fill in the actual details.
8946 Invoke->setUsed();
8947 Invoke->setReferenced();
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00008948 Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008949
8950 if (ASTMutationListener *L = getASTMutationListener()) {
8951 L->CompletedImplicitDefinition(Conv);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00008952 L->CompletedImplicitDefinition(Invoke);
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008953 }
8954}
8955
8956void Sema::DefineImplicitLambdaToBlockPointerConversion(
8957 SourceLocation CurrentLocation,
8958 CXXConversionDecl *Conv)
8959{
8960 Conv->setUsed();
8961
8962 ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8963 DiagnosticErrorTrap Trap(Diags);
8964
Douglas Gregorac1303e2012-02-22 05:02:47 +00008965 // Copy-initialize the lambda object as needed to capture it.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008966 Expr *This = ActOnCXXThis(CurrentLocation).take();
8967 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008968
Eli Friedman23f02672012-03-01 04:01:32 +00008969 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8970 Conv->getLocation(),
8971 Conv, DerefThis);
8972
8973 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8974 // behavior. Note that only the general conversion function does this
8975 // (since it's unusable otherwise); in the case where we inline the
8976 // block literal, it has block literal lifetime semantics.
David Blaikie4e4d0842012-03-11 07:00:24 +00008977 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
Eli Friedman23f02672012-03-01 04:01:32 +00008978 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8979 CK_CopyAndAutoreleaseBlockObject,
8980 BuildBlock.get(), 0, VK_RValue);
8981
8982 if (BuildBlock.isInvalid()) {
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008983 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
Douglas Gregorac1303e2012-02-22 05:02:47 +00008984 Conv->setInvalidDecl();
8985 return;
Douglas Gregorf6e2e022012-02-16 01:06:16 +00008986 }
Douglas Gregorac1303e2012-02-22 05:02:47 +00008987
Douglas Gregorac1303e2012-02-22 05:02:47 +00008988 // Create the return statement that returns the block from the conversion
8989 // function.
Eli Friedman23f02672012-03-01 04:01:32 +00008990 StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
Douglas Gregorac1303e2012-02-22 05:02:47 +00008991 if (Return.isInvalid()) {
8992 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8993 Conv->setInvalidDecl();
8994 return;
8995 }
8996
8997 // Set the body of the conversion function.
8998 Stmt *ReturnS = Return.take();
8999 Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9000 Conv->getLocation(),
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009001 Conv->getLocation()));
9002
Douglas Gregorac1303e2012-02-22 05:02:47 +00009003 // We're done; notify the mutation listener, if any.
Douglas Gregorf6e2e022012-02-16 01:06:16 +00009004 if (ASTMutationListener *L = getASTMutationListener()) {
9005 L->CompletedImplicitDefinition(Conv);
9006 }
9007}
9008
Douglas Gregorf52757d2012-03-10 06:53:13 +00009009/// \brief Determine whether the given list arguments contains exactly one
9010/// "real" (non-default) argument.
9011static bool hasOneRealArgument(MultiExprArg Args) {
9012 switch (Args.size()) {
9013 case 0:
9014 return false;
9015
9016 default:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009017 if (!Args[1]->isDefaultArgument())
Douglas Gregorf52757d2012-03-10 06:53:13 +00009018 return false;
9019
9020 // fall through
9021 case 1:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009022 return !Args[0]->isDefaultArgument();
Douglas Gregorf52757d2012-03-10 06:53:13 +00009023 }
9024
9025 return false;
9026}
9027
John McCall60d7b3a2010-08-24 06:29:42 +00009028ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009029Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00009030 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00009031 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009032 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009033 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009034 unsigned ConstructKind,
9035 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009036 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009037
Douglas Gregor2f599792010-04-02 18:24:57 +00009038 // C++0x [class.copy]p34:
9039 // When certain criteria are met, an implementation is allowed to
9040 // omit the copy/move construction of a class object, even if the
9041 // copy/move constructor and/or destructor for the object have
9042 // side effects. [...]
9043 // - when a temporary class object that has not been bound to a
9044 // reference (12.2) would be copied/moved to a class object
9045 // with the same cv-unqualified type, the copy/move operation
9046 // can be omitted by constructing the temporary object
9047 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009048 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregorf52757d2012-03-10 06:53:13 +00009049 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
Benjamin Kramer5354e772012-08-23 23:38:35 +00009050 Expr *SubExpr = ExprArgs[0];
John McCall558d2ab2010-09-15 10:14:12 +00009051 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009052 }
Mike Stump1eb44332009-09-09 15:08:12 +00009053
9054 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009055 Elidable, ExprArgs, HadMultipleCandidates,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009056 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009057}
9058
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009059/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9060/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009061ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009062Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9063 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009064 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009065 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009066 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009067 unsigned ConstructKind,
9068 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009069 unsigned NumExprs = ExprArgs.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009070 Expr **Exprs = ExprArgs.data();
Mike Stump1eb44332009-09-09 15:08:12 +00009071
Eli Friedman5f2987c2012-02-02 03:46:19 +00009072 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009073 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009074 Constructor, Elidable, Exprs, NumExprs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00009075 HadMultipleCandidates, /*FIXME*/false,
9076 RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009077 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9078 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009079}
9080
Mike Stump1eb44332009-09-09 15:08:12 +00009081bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009082 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009083 MultiExprArg Exprs,
9084 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009085 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009086 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009087 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009088 Exprs, HadMultipleCandidates, false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009089 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009090 if (TempResult.isInvalid())
9091 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009092
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009093 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009094 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009095 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009096 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009097 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009098
Anders Carlssonfe2de492009-08-25 05:18:00 +00009099 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009100}
9101
John McCall68c6c9a2010-02-02 09:10:11 +00009102void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009103 if (VD->isInvalidDecl()) return;
9104
John McCall68c6c9a2010-02-02 09:10:11 +00009105 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009106 if (ClassDecl->isInvalidDecl()) return;
Richard Smith213d70b2012-02-18 04:13:32 +00009107 if (ClassDecl->hasIrrelevantDestructor()) return;
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009108 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009109
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009110 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009111 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009112 CheckDestructorAccess(VD->getLocation(), Destructor,
9113 PDiag(diag::err_access_dtor_var)
9114 << VD->getDeclName()
9115 << VD->getType());
Richard Smith213d70b2012-02-18 04:13:32 +00009116 DiagnoseUseOfDecl(Destructor, VD->getLocation());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009117
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009118 if (!VD->hasGlobalStorage()) return;
9119
9120 // Emit warning for non-trivial dtor in global scope (a real global,
9121 // class-static, function-static).
9122 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9123
9124 // TODO: this should be re-enabled for static locals by !CXAAtExit
9125 if (!VD->isStaticLocal())
9126 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009127}
9128
Douglas Gregor39da0b82009-09-09 23:08:42 +00009129/// \brief Given a constructor and the set of arguments provided for the
9130/// constructor, convert the arguments and add any required default arguments
9131/// to form a proper call to this constructor.
9132///
9133/// \returns true if an error occurred, false otherwise.
9134bool
9135Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9136 MultiExprArg ArgsPtr,
Richard Smith831421f2012-06-25 20:30:08 +00009137 SourceLocation Loc,
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00009138 SmallVectorImpl<Expr*> &ConvertedArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009139 bool AllowExplicit) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009140 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9141 unsigned NumArgs = ArgsPtr.size();
Benjamin Kramer5354e772012-08-23 23:38:35 +00009142 Expr **Args = ArgsPtr.data();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009143
9144 const FunctionProtoType *Proto
9145 = Constructor->getType()->getAs<FunctionProtoType>();
9146 assert(Proto && "Constructor without a prototype?");
9147 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009148
9149 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009150 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009151 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009152 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009153 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009154
9155 VariadicCallType CallType =
9156 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009157 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009158 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9159 Proto, 0, Args, NumArgs, AllArgs,
Douglas Gregored878af2012-02-24 23:56:31 +00009160 CallType, AllowExplicit);
Benjamin Kramer14c59822012-02-14 12:06:21 +00009161 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
Eli Friedmane61eb042012-02-18 04:48:30 +00009162
9163 DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9164
Richard Smith831421f2012-06-25 20:30:08 +00009165 CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9166 Proto, Loc);
Eli Friedmane61eb042012-02-18 04:48:30 +00009167
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009168 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009169}
9170
Anders Carlsson20d45d22009-12-12 00:32:00 +00009171static inline bool
9172CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9173 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009174 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009175 if (isa<NamespaceDecl>(DC)) {
9176 return SemaRef.Diag(FnDecl->getLocation(),
9177 diag::err_operator_new_delete_declared_in_namespace)
9178 << FnDecl->getDeclName();
9179 }
9180
9181 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009182 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009183 return SemaRef.Diag(FnDecl->getLocation(),
9184 diag::err_operator_new_delete_declared_static)
9185 << FnDecl->getDeclName();
9186 }
9187
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009188 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009189}
9190
Anders Carlsson156c78e2009-12-13 17:53:43 +00009191static inline bool
9192CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9193 CanQualType ExpectedResultType,
9194 CanQualType ExpectedFirstParamType,
9195 unsigned DependentParamTypeDiag,
9196 unsigned InvalidParamTypeDiag) {
9197 QualType ResultType =
9198 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9199
9200 // Check that the result type is not dependent.
9201 if (ResultType->isDependentType())
9202 return SemaRef.Diag(FnDecl->getLocation(),
9203 diag::err_operator_new_delete_dependent_result_type)
9204 << FnDecl->getDeclName() << ExpectedResultType;
9205
9206 // Check that the result type is what we expect.
9207 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9208 return SemaRef.Diag(FnDecl->getLocation(),
9209 diag::err_operator_new_delete_invalid_result_type)
9210 << FnDecl->getDeclName() << ExpectedResultType;
9211
9212 // A function template must have at least 2 parameters.
9213 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9214 return SemaRef.Diag(FnDecl->getLocation(),
9215 diag::err_operator_new_delete_template_too_few_parameters)
9216 << FnDecl->getDeclName();
9217
9218 // The function decl must have at least 1 parameter.
9219 if (FnDecl->getNumParams() == 0)
9220 return SemaRef.Diag(FnDecl->getLocation(),
9221 diag::err_operator_new_delete_too_few_parameters)
9222 << FnDecl->getDeclName();
9223
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00009224 // Check the first parameter type is not dependent.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009225 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9226 if (FirstParamType->isDependentType())
9227 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9228 << FnDecl->getDeclName() << ExpectedFirstParamType;
9229
9230 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009231 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009232 ExpectedFirstParamType)
9233 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9234 << FnDecl->getDeclName() << ExpectedFirstParamType;
9235
9236 return false;
9237}
9238
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009239static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009240CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009241 // C++ [basic.stc.dynamic.allocation]p1:
9242 // A program is ill-formed if an allocation function is declared in a
9243 // namespace scope other than global scope or declared static in global
9244 // scope.
9245 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9246 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009247
9248 CanQualType SizeTy =
9249 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9250
9251 // C++ [basic.stc.dynamic.allocation]p1:
9252 // The return type shall be void*. The first parameter shall have type
9253 // std::size_t.
9254 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9255 SizeTy,
9256 diag::err_operator_new_dependent_param_type,
9257 diag::err_operator_new_param_type))
9258 return true;
9259
9260 // C++ [basic.stc.dynamic.allocation]p1:
9261 // The first parameter shall not have an associated default argument.
9262 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009263 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009264 diag::err_operator_new_default_arg)
9265 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9266
9267 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009268}
9269
9270static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009271CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9272 // C++ [basic.stc.dynamic.deallocation]p1:
9273 // A program is ill-formed if deallocation functions are declared in a
9274 // namespace scope other than global scope or declared static in global
9275 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009276 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9277 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009278
9279 // C++ [basic.stc.dynamic.deallocation]p2:
9280 // Each deallocation function shall return void and its first parameter
9281 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009282 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9283 SemaRef.Context.VoidPtrTy,
9284 diag::err_operator_delete_dependent_param_type,
9285 diag::err_operator_delete_param_type))
9286 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009287
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009288 return false;
9289}
9290
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009291/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9292/// of this overloaded operator is well-formed. If so, returns false;
9293/// otherwise, emits appropriate diagnostics and returns true.
9294bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009295 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009296 "Expected an overloaded operator declaration");
9297
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009298 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9299
Mike Stump1eb44332009-09-09 15:08:12 +00009300 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009301 // The allocation and deallocation functions, operator new,
9302 // operator new[], operator delete and operator delete[], are
9303 // described completely in 3.7.3. The attributes and restrictions
9304 // found in the rest of this subclause do not apply to them unless
9305 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009306 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009307 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009308
Anders Carlssona3ccda52009-12-12 00:26:23 +00009309 if (Op == OO_New || Op == OO_Array_New)
9310 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009311
9312 // C++ [over.oper]p6:
9313 // An operator function shall either be a non-static member
9314 // function or be a non-member function and have at least one
9315 // parameter whose type is a class, a reference to a class, an
9316 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009317 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9318 if (MethodDecl->isStatic())
9319 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009320 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009321 } else {
9322 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009323 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9324 ParamEnd = FnDecl->param_end();
9325 Param != ParamEnd; ++Param) {
9326 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009327 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9328 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009329 ClassOrEnumParam = true;
9330 break;
9331 }
9332 }
9333
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009334 if (!ClassOrEnumParam)
9335 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009336 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009337 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009338 }
9339
9340 // C++ [over.oper]p8:
9341 // An operator function cannot have default arguments (8.3.6),
9342 // except where explicitly stated below.
9343 //
Mike Stump1eb44332009-09-09 15:08:12 +00009344 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009345 // (C++ [over.call]p1).
9346 if (Op != OO_Call) {
9347 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9348 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009349 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009350 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009351 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009352 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009353 }
9354 }
9355
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009356 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9357 { false, false, false }
9358#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9359 , { Unary, Binary, MemberOnly }
9360#include "clang/Basic/OperatorKinds.def"
9361 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009362
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009363 bool CanBeUnaryOperator = OperatorUses[Op][0];
9364 bool CanBeBinaryOperator = OperatorUses[Op][1];
9365 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009366
9367 // C++ [over.oper]p8:
9368 // [...] Operator functions cannot have more or fewer parameters
9369 // than the number required for the corresponding operator, as
9370 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009371 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009372 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009373 if (Op != OO_Call &&
9374 ((NumParams == 1 && !CanBeUnaryOperator) ||
9375 (NumParams == 2 && !CanBeBinaryOperator) ||
9376 (NumParams < 1) || (NumParams > 2))) {
9377 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009378 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009379 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009380 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009381 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009382 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009383 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009384 assert(CanBeBinaryOperator &&
9385 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009386 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009387 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009388
Chris Lattner416e46f2008-11-21 07:57:12 +00009389 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009390 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009391 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009392
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009393 // Overloaded operators other than operator() cannot be variadic.
9394 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009395 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009396 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009397 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009398 }
9399
9400 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009401 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9402 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009403 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009404 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009405 }
9406
9407 // C++ [over.inc]p1:
9408 // The user-defined function called operator++ implements the
9409 // prefix and postfix ++ operator. If this function is a member
9410 // function with no parameters, or a non-member function with one
9411 // parameter of class or enumeration type, it defines the prefix
9412 // increment operator ++ for objects of that type. If the function
9413 // is a member function with one parameter (which shall be of type
9414 // int) or a non-member function with two parameters (the second
9415 // of which shall be of type int), it defines the postfix
9416 // increment operator ++ for objects of that type.
9417 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9418 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9419 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009420 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009421 ParamIsInt = BT->getKind() == BuiltinType::Int;
9422
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009423 if (!ParamIsInt)
9424 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009425 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009426 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009427 }
9428
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009429 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009430}
Chris Lattner5a003a42008-12-17 07:09:26 +00009431
Sean Hunta6c058d2010-01-13 09:01:02 +00009432/// CheckLiteralOperatorDeclaration - Check whether the declaration
9433/// of this literal operator function is well-formed. If so, returns
9434/// false; otherwise, emits appropriate diagnostics and returns true.
9435bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
Richard Smithe5658f02012-03-10 22:18:57 +00009436 if (isa<CXXMethodDecl>(FnDecl)) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009437 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9438 << FnDecl->getDeclName();
9439 return true;
9440 }
9441
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009442 if (FnDecl->isExternC()) {
9443 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9444 return true;
9445 }
9446
Sean Hunta6c058d2010-01-13 09:01:02 +00009447 bool Valid = false;
9448
Richard Smith36f5cfe2012-03-09 08:00:36 +00009449 // This might be the definition of a literal operator template.
9450 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9451 // This might be a specialization of a literal operator template.
9452 if (!TpDecl)
9453 TpDecl = FnDecl->getPrimaryTemplate();
9454
Sean Hunt216c2782010-04-07 23:11:06 +00009455 // template <char...> type operator "" name() is the only valid template
9456 // signature, and the only valid signature with no parameters.
Richard Smith36f5cfe2012-03-09 08:00:36 +00009457 if (TpDecl) {
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009458 if (FnDecl->param_size() == 0) {
Sean Hunt216c2782010-04-07 23:11:06 +00009459 // Must have only one template parameter
9460 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9461 if (Params->size() == 1) {
9462 NonTypeTemplateParmDecl *PmDecl =
Richard Smith5295b972012-08-03 21:14:57 +00009463 dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009464
Sean Hunt216c2782010-04-07 23:11:06 +00009465 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009466 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9467 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9468 Valid = true;
9469 }
9470 }
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009471 } else if (FnDecl->param_size()) {
Sean Hunta6c058d2010-01-13 09:01:02 +00009472 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009473 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9474
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009475 QualType T = (*Param)->getType().getUnqualifiedType();
Sean Hunta6c058d2010-01-13 09:01:02 +00009476
Sean Hunt30019c02010-04-07 22:57:35 +00009477 // unsigned long long int, long double, and any character type are allowed
9478 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009479 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9480 Context.hasSameType(T, Context.LongDoubleTy) ||
9481 Context.hasSameType(T, Context.CharTy) ||
9482 Context.hasSameType(T, Context.WCharTy) ||
9483 Context.hasSameType(T, Context.Char16Ty) ||
9484 Context.hasSameType(T, Context.Char32Ty)) {
9485 if (++Param == FnDecl->param_end())
9486 Valid = true;
9487 goto FinishedParams;
9488 }
9489
Sean Hunt30019c02010-04-07 22:57:35 +00009490 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009491 const PointerType *PT = T->getAs<PointerType>();
9492 if (!PT)
9493 goto FinishedParams;
9494 T = PT->getPointeeType();
Richard Smithb4a7b1e2012-03-04 09:41:16 +00009495 if (!T.isConstQualified() || T.isVolatileQualified())
Sean Hunta6c058d2010-01-13 09:01:02 +00009496 goto FinishedParams;
9497 T = T.getUnqualifiedType();
9498
9499 // Move on to the second parameter;
9500 ++Param;
9501
9502 // If there is no second parameter, the first must be a const char *
9503 if (Param == FnDecl->param_end()) {
9504 if (Context.hasSameType(T, Context.CharTy))
9505 Valid = true;
9506 goto FinishedParams;
9507 }
9508
9509 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9510 // are allowed as the first parameter to a two-parameter function
9511 if (!(Context.hasSameType(T, Context.CharTy) ||
9512 Context.hasSameType(T, Context.WCharTy) ||
9513 Context.hasSameType(T, Context.Char16Ty) ||
9514 Context.hasSameType(T, Context.Char32Ty)))
9515 goto FinishedParams;
9516
9517 // The second and final parameter must be an std::size_t
9518 T = (*Param)->getType().getUnqualifiedType();
9519 if (Context.hasSameType(T, Context.getSizeType()) &&
9520 ++Param == FnDecl->param_end())
9521 Valid = true;
9522 }
9523
9524 // FIXME: This diagnostic is absolutely terrible.
9525FinishedParams:
9526 if (!Valid) {
9527 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9528 << FnDecl->getDeclName();
9529 return true;
9530 }
9531
Richard Smitha9e88b22012-03-09 08:16:22 +00009532 // A parameter-declaration-clause containing a default argument is not
9533 // equivalent to any of the permitted forms.
9534 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9535 ParamEnd = FnDecl->param_end();
9536 Param != ParamEnd; ++Param) {
9537 if ((*Param)->hasDefaultArg()) {
9538 Diag((*Param)->getDefaultArgRange().getBegin(),
9539 diag::err_literal_operator_default_argument)
9540 << (*Param)->getDefaultArgRange();
9541 break;
9542 }
9543 }
9544
Richard Smith2fb4ae32012-03-08 02:39:21 +00009545 StringRef LiteralName
Douglas Gregor1155c422011-08-30 22:40:35 +00009546 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9547 if (LiteralName[0] != '_') {
Richard Smith2fb4ae32012-03-08 02:39:21 +00009548 // C++11 [usrlit.suffix]p1:
9549 // Literal suffix identifiers that do not start with an underscore
9550 // are reserved for future standardization.
9551 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
Douglas Gregor1155c422011-08-30 22:40:35 +00009552 }
Richard Smith2fb4ae32012-03-08 02:39:21 +00009553
Sean Hunta6c058d2010-01-13 09:01:02 +00009554 return false;
9555}
9556
Douglas Gregor074149e2009-01-05 19:45:36 +00009557/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9558/// linkage specification, including the language and (if present)
9559/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9560/// the location of the language string literal, which is provided
9561/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9562/// the '{' brace. Otherwise, this linkage specification does not
9563/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009564Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9565 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009566 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009567 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009568 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009569 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009570 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009571 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009572 Language = LinkageSpecDecl::lang_cxx;
9573 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009574 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009575 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009576 }
Mike Stump1eb44332009-09-09 15:08:12 +00009577
Chris Lattnercc98eac2008-12-17 07:13:27 +00009578 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009579
Douglas Gregor074149e2009-01-05 19:45:36 +00009580 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009581 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009582 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009583 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009584 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009585}
9586
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009587/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009588/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9589/// valid, it's the position of the closing '}' brace in a linkage
9590/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009591Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009592 Decl *LinkageSpec,
9593 SourceLocation RBraceLoc) {
9594 if (LinkageSpec) {
9595 if (RBraceLoc.isValid()) {
9596 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9597 LSDecl->setRBraceLoc(RBraceLoc);
9598 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009599 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009600 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009601 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009602}
9603
Douglas Gregord308e622009-05-18 20:51:54 +00009604/// \brief Perform semantic analysis for the variable declaration that
9605/// occurs within a C++ catch clause, returning the newly-created
9606/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009607VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009608 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009609 SourceLocation StartLoc,
9610 SourceLocation Loc,
9611 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009612 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009613 QualType ExDeclType = TInfo->getType();
9614
Sebastian Redl4b07b292008-12-22 19:15:10 +00009615 // Arrays and functions decay.
9616 if (ExDeclType->isArrayType())
9617 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9618 else if (ExDeclType->isFunctionType())
9619 ExDeclType = Context.getPointerType(ExDeclType);
9620
9621 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9622 // The exception-declaration shall not denote a pointer or reference to an
9623 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009624 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009625 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009626 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009627 Invalid = true;
9628 }
Douglas Gregord308e622009-05-18 20:51:54 +00009629
Sebastian Redl4b07b292008-12-22 19:15:10 +00009630 QualType BaseType = ExDeclType;
9631 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009632 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009633 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009634 BaseType = Ptr->getPointeeType();
9635 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009636 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009637 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009638 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009639 BaseType = Ref->getPointeeType();
9640 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009641 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009642 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009643 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009644 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009645 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009646
Mike Stump1eb44332009-09-09 15:08:12 +00009647 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009648 RequireNonAbstractType(Loc, ExDeclType,
9649 diag::err_abstract_type_in_decl,
9650 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009651 Invalid = true;
9652
John McCall5a180392010-07-24 00:37:23 +00009653 // Only the non-fragile NeXT runtime currently supports C++ catches
9654 // of ObjC types, and no runtime supports catching ObjC types by value.
David Blaikie4e4d0842012-03-11 07:00:24 +00009655 if (!Invalid && getLangOpts().ObjC1) {
John McCall5a180392010-07-24 00:37:23 +00009656 QualType T = ExDeclType;
9657 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9658 T = RT->getPointeeType();
9659
9660 if (T->isObjCObjectType()) {
9661 Diag(Loc, diag::err_objc_object_catch);
9662 Invalid = true;
9663 } else if (T->isObjCObjectPointerType()) {
John McCall260611a2012-06-20 06:18:46 +00009664 // FIXME: should this be a test for macosx-fragile specifically?
9665 if (getLangOpts().ObjCRuntime.isFragile())
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009666 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009667 }
9668 }
9669
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009670 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9671 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009672 ExDecl->setExceptionVariable(true);
9673
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009674 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00009675 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009676 Invalid = true;
9677
Douglas Gregorc41b8782011-07-06 18:14:43 +00009678 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009679 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009680 // C++ [except.handle]p16:
9681 // The object declared in an exception-declaration or, if the
9682 // exception-declaration does not specify a name, a temporary (12.2) is
9683 // copy-initialized (8.5) from the exception object. [...]
9684 // The object is destroyed when the handler exits, after the destruction
9685 // of any automatic objects initialized within the handler.
9686 //
9687 // We just pretend to initialize the object with itself, then make sure
9688 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009689 QualType initType = ExDeclType;
9690
9691 InitializedEntity entity =
9692 InitializedEntity::InitializeVariable(ExDecl);
9693 InitializationKind initKind =
9694 InitializationKind::CreateCopy(Loc, SourceLocation());
9695
9696 Expr *opaqueValue =
9697 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9698 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9699 ExprResult result = sequence.Perform(*this, entity, initKind,
9700 MultiExprArg(&opaqueValue, 1));
9701 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009702 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009703 else {
9704 // If the constructor used was non-trivial, set this as the
9705 // "initializer".
9706 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9707 if (!construct->getConstructor()->isTrivial()) {
9708 Expr *init = MaybeCreateExprWithCleanups(construct);
9709 ExDecl->setInit(init);
9710 }
9711
9712 // And make sure it's destructable.
9713 FinalizeVarWithDestructor(ExDecl, recordType);
9714 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009715 }
9716 }
9717
Douglas Gregord308e622009-05-18 20:51:54 +00009718 if (Invalid)
9719 ExDecl->setInvalidDecl();
9720
9721 return ExDecl;
9722}
9723
9724/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9725/// handler.
John McCalld226f652010-08-21 09:40:31 +00009726Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009727 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009728 bool Invalid = D.isInvalidType();
9729
9730 // Check for unexpanded parameter packs.
9731 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9732 UPPC_ExceptionType)) {
9733 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9734 D.getIdentifierLoc());
9735 Invalid = true;
9736 }
9737
Sebastian Redl4b07b292008-12-22 19:15:10 +00009738 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009739 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009740 LookupOrdinaryName,
9741 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009742 // The scope should be freshly made just for us. There is just no way
9743 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009744 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009745 if (PrevDecl->isTemplateParameter()) {
9746 // Maybe we will complain about the shadowed template parameter.
9747 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009748 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009749 }
9750 }
9751
Chris Lattnereaaebc72009-04-25 08:06:05 +00009752 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009753 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9754 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009755 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009756 }
9757
Douglas Gregor83cb9422010-09-09 17:09:21 +00009758 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Daniel Dunbar96a00142012-03-09 18:35:03 +00009759 D.getLocStart(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009760 D.getIdentifierLoc(),
9761 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009762 if (Invalid)
9763 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009764
Sebastian Redl4b07b292008-12-22 19:15:10 +00009765 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009766 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009767 PushOnScopeChains(ExDecl, S);
9768 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009769 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009770
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009771 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009772 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009773}
Anders Carlssonfb311762009-03-14 00:25:26 +00009774
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009775Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009776 Expr *AssertExpr,
Richard Smithe3f470a2012-07-11 22:37:56 +00009777 Expr *AssertMessageExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009778 SourceLocation RParenLoc) {
Richard Smithe3f470a2012-07-11 22:37:56 +00009779 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
Anders Carlssonfb311762009-03-14 00:25:26 +00009780
Richard Smithe3f470a2012-07-11 22:37:56 +00009781 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9782 return 0;
9783
9784 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
9785 AssertMessage, RParenLoc, false);
9786}
9787
9788Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9789 Expr *AssertExpr,
9790 StringLiteral *AssertMessage,
9791 SourceLocation RParenLoc,
9792 bool Failed) {
9793 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
9794 !Failed) {
Richard Smith282e7e62012-02-04 09:53:13 +00009795 // In a static_assert-declaration, the constant-expression shall be a
9796 // constant expression that can be contextually converted to bool.
9797 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9798 if (Converted.isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +00009799 Failed = true;
Richard Smith282e7e62012-02-04 09:53:13 +00009800
Richard Smithdaaefc52011-12-14 23:32:26 +00009801 llvm::APSInt Cond;
Richard Smithe3f470a2012-07-11 22:37:56 +00009802 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
Douglas Gregorab41fe92012-05-04 22:38:52 +00009803 diag::err_static_assert_expression_is_not_constant,
Richard Smith282e7e62012-02-04 09:53:13 +00009804 /*AllowFold=*/false).isInvalid())
Richard Smithe3f470a2012-07-11 22:37:56 +00009805 Failed = true;
Anders Carlssonfb311762009-03-14 00:25:26 +00009806
Richard Smithe3f470a2012-07-11 22:37:56 +00009807 if (!Failed && !Cond) {
Richard Smith0cc323c2012-03-05 23:20:05 +00009808 llvm::SmallString<256> MsgBuffer;
9809 llvm::raw_svector_ostream Msg(MsgBuffer);
Richard Smithd1420c62012-08-16 03:56:14 +00009810 AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009811 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Richard Smith0cc323c2012-03-05 23:20:05 +00009812 << Msg.str() << AssertExpr->getSourceRange();
Richard Smithe3f470a2012-07-11 22:37:56 +00009813 Failed = true;
Richard Smith0cc323c2012-03-05 23:20:05 +00009814 }
Anders Carlssonc3082412009-03-14 00:33:21 +00009815 }
Mike Stump1eb44332009-09-09 15:08:12 +00009816
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009817 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
Richard Smithe3f470a2012-07-11 22:37:56 +00009818 AssertExpr, AssertMessage, RParenLoc,
9819 Failed);
Mike Stump1eb44332009-09-09 15:08:12 +00009820
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009821 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009822 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009823}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009824
Douglas Gregor1d869352010-04-07 16:53:43 +00009825/// \brief Perform semantic analysis of the given friend type declaration.
9826///
9827/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009828FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9829 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009830 TypeSourceInfo *TSInfo) {
9831 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9832
9833 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009834 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009835
Richard Smith6b130222011-10-18 21:39:00 +00009836 // C++03 [class.friend]p2:
9837 // An elaborated-type-specifier shall be used in a friend declaration
9838 // for a class.*
9839 //
9840 // * The class-key of the elaborated-type-specifier is required.
9841 if (!ActiveTemplateInstantiations.empty()) {
9842 // Do not complain about the form of friend template types during
9843 // template instantiation; we will already have complained when the
9844 // template was declared.
9845 } else if (!T->isElaboratedTypeSpecifier()) {
9846 // If we evaluated the type to a record type, suggest putting
9847 // a tag in front.
9848 if (const RecordType *RT = T->getAs<RecordType>()) {
9849 RecordDecl *RD = RT->getDecl();
9850
9851 std::string InsertionText = std::string(" ") + RD->getKindName();
9852
9853 Diag(TypeRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00009854 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009855 diag::warn_cxx98_compat_unelaborated_friend_type :
9856 diag::ext_unelaborated_friend_type)
9857 << (unsigned) RD->getTagKind()
9858 << T
9859 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9860 InsertionText);
9861 } else {
9862 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009863 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009864 diag::warn_cxx98_compat_nonclass_type_friend :
9865 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009866 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009867 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009868 }
Richard Smith6b130222011-10-18 21:39:00 +00009869 } else if (T->getAs<EnumType>()) {
9870 Diag(FriendLoc,
David Blaikie4e4d0842012-03-11 07:00:24 +00009871 getLangOpts().CPlusPlus0x ?
Richard Smith6b130222011-10-18 21:39:00 +00009872 diag::warn_cxx98_compat_enum_friend :
9873 diag::ext_enum_friend)
9874 << T
9875 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009876 }
9877
Douglas Gregor06245bf2010-04-07 17:57:12 +00009878 // C++0x [class.friend]p3:
9879 // If the type specifier in a friend declaration designates a (possibly
9880 // cv-qualified) class type, that class is declared as a friend; otherwise,
9881 // the friend declaration is ignored.
9882
9883 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9884 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +00009885
Abramo Bagnara0216df82011-10-29 20:52:52 +00009886 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +00009887}
9888
John McCall9a34edb2010-10-19 01:40:49 +00009889/// Handle a friend tag declaration where the scope specifier was
9890/// templated.
9891Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9892 unsigned TagSpec, SourceLocation TagLoc,
9893 CXXScopeSpec &SS,
9894 IdentifierInfo *Name, SourceLocation NameLoc,
9895 AttributeList *Attr,
9896 MultiTemplateParamsArg TempParamLists) {
9897 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9898
9899 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +00009900 bool Invalid = false;
9901
9902 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +00009903 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
Benjamin Kramer5354e772012-08-23 23:38:35 +00009904 TempParamLists.data(),
John McCall9a34edb2010-10-19 01:40:49 +00009905 TempParamLists.size(),
9906 /*friend*/ true,
9907 isExplicitSpecialization,
9908 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +00009909 if (TemplateParams->size() > 0) {
9910 // This is a declaration of a class template.
9911 if (Invalid)
9912 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +00009913
Eric Christopher4110e132011-07-21 05:34:24 +00009914 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9915 SS, Name, NameLoc, Attr,
9916 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +00009917 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +00009918 TempParamLists.size() - 1,
Benjamin Kramer5354e772012-08-23 23:38:35 +00009919 TempParamLists.data()).take();
John McCall9a34edb2010-10-19 01:40:49 +00009920 } else {
9921 // The "template<>" header is extraneous.
9922 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9923 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9924 isExplicitSpecialization = true;
9925 }
9926 }
9927
9928 if (Invalid) return 0;
9929
John McCall9a34edb2010-10-19 01:40:49 +00009930 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +00009931 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00009932 if (TempParamLists[I]->size()) {
John McCall9a34edb2010-10-19 01:40:49 +00009933 isAllExplicitSpecializations = false;
9934 break;
9935 }
9936 }
9937
9938 // FIXME: don't ignore attributes.
9939
9940 // If it's explicit specializations all the way down, just forget
9941 // about the template header and build an appropriate non-templated
9942 // friend. TODO: for source fidelity, remember the headers.
9943 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009944 if (SS.isEmpty()) {
9945 bool Owned = false;
9946 bool IsDependent = false;
9947 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9948 Attr, AS_public,
9949 /*ModulePrivateLoc=*/SourceLocation(),
9950 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +00009951 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009952 /*ScopedEnumUsesClassTag=*/false,
9953 /*UnderlyingType=*/TypeResult());
9954 }
9955
Douglas Gregor2494dd02011-03-01 01:34:45 +00009956 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +00009957 ElaboratedTypeKeyword Keyword
9958 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009959 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +00009960 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009961 if (T.isNull())
9962 return 0;
9963
9964 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9965 if (isa<DependentNameType>(T)) {
9966 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009967 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009968 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009969 TL.setNameLoc(NameLoc);
9970 } else {
9971 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009972 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +00009973 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +00009974 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9975 }
9976
9977 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9978 TSI, FriendLoc);
9979 Friend->setAccess(AS_public);
9980 CurContext->addDecl(Friend);
9981 return Friend;
9982 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +00009983
9984 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9985
9986
John McCall9a34edb2010-10-19 01:40:49 +00009987
9988 // Handle the case of a templated-scope friend class. e.g.
9989 // template <class T> class A<T>::B;
9990 // FIXME: we don't support these right now.
9991 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9992 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9993 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9994 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +00009995 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +00009996 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +00009997 TL.setNameLoc(NameLoc);
9998
9999 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10000 TSI, FriendLoc);
10001 Friend->setAccess(AS_public);
10002 Friend->setUnsupportedFriend(true);
10003 CurContext->addDecl(Friend);
10004 return Friend;
10005}
10006
10007
John McCalldd4a3b02009-09-16 22:47:08 +000010008/// Handle a friend type declaration. This works in tandem with
10009/// ActOnTag.
10010///
10011/// Notes on friend class templates:
10012///
10013/// We generally treat friend class declarations as if they were
10014/// declaring a class. So, for example, the elaborated type specifier
10015/// in a friend declaration is required to obey the restrictions of a
10016/// class-head (i.e. no typedefs in the scope chain), template
10017/// parameters are required to match up with simple template-ids, &c.
10018/// However, unlike when declaring a template specialization, it's
10019/// okay to refer to a template specialization without an empty
10020/// template parameter declaration, e.g.
10021/// friend class A<T>::B<unsigned>;
10022/// We permit this as a special case; if there are any template
10023/// parameters present at all, require proper matching, i.e.
James Dennettef2b5b32012-06-15 22:23:43 +000010024/// template <> template \<class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010025Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010026 MultiTemplateParamsArg TempParams) {
Daniel Dunbar96a00142012-03-09 18:35:03 +000010027 SourceLocation Loc = DS.getLocStart();
John McCall67d1a672009-08-06 02:15:43 +000010028
10029 assert(DS.isFriendSpecified());
10030 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10031
John McCalldd4a3b02009-09-16 22:47:08 +000010032 // Try to convert the decl specifier to a type. This works for
10033 // friend templates because ActOnTag never produces a ClassTemplateDecl
10034 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010035 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010036 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10037 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010038 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010039 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010040
Douglas Gregor6ccab972010-12-16 01:14:37 +000010041 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10042 return 0;
10043
John McCalldd4a3b02009-09-16 22:47:08 +000010044 // This is definitely an error in C++98. It's probably meant to
10045 // be forbidden in C++0x, too, but the specification is just
10046 // poorly written.
10047 //
10048 // The problem is with declarations like the following:
10049 // template <T> friend A<T>::foo;
10050 // where deciding whether a class C is a friend or not now hinges
10051 // on whether there exists an instantiation of A that causes
10052 // 'foo' to equal C. There are restrictions on class-heads
10053 // (which we declare (by fiat) elaborated friend declarations to
10054 // be) that makes this tractable.
10055 //
10056 // FIXME: handle "template <> friend class A<T>;", which
10057 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010058 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010059 Diag(Loc, diag::err_tagless_friend_type_template)
10060 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010061 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010062 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010063
John McCall02cace72009-08-28 07:59:38 +000010064 // C++98 [class.friend]p1: A friend of a class is a function
10065 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010066 // This is fixed in DR77, which just barely didn't make the C++03
10067 // deadline. It's also a very silly restriction that seriously
10068 // affects inner classes and which nobody else seems to implement;
10069 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010070 //
10071 // But note that we could warn about it: it's always useless to
10072 // friend one of your own members (it's not, however, worthless to
10073 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010074
John McCalldd4a3b02009-09-16 22:47:08 +000010075 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010076 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010077 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010078 NumTempParamLists,
Benjamin Kramer5354e772012-08-23 23:38:35 +000010079 TempParams.data(),
John McCall32f2fb52010-03-25 18:04:51 +000010080 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010081 DS.getFriendSpecLoc());
10082 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010083 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010084
10085 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010086 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010087
John McCalldd4a3b02009-09-16 22:47:08 +000010088 D->setAccess(AS_public);
10089 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010090
John McCalld226f652010-08-21 09:40:31 +000010091 return D;
John McCall02cace72009-08-28 07:59:38 +000010092}
10093
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010094Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010095 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010096 const DeclSpec &DS = D.getDeclSpec();
10097
10098 assert(DS.isFriendSpecified());
10099 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10100
10101 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010102 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010103
10104 // C++ [class.friend]p1
10105 // A friend of a class is a function or class....
10106 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010107 // It *doesn't* see through dependent types, which is correct
10108 // according to [temp.arg.type]p3:
10109 // If a declaration acquires a function type through a
10110 // type dependent on a template-parameter and this causes
10111 // a declaration that does not use the syntactic form of a
10112 // function declarator to have a function type, the program
10113 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010114 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010115 Diag(Loc, diag::err_unexpected_friend);
10116
10117 // It might be worthwhile to try to recover by creating an
10118 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010119 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010120 }
10121
10122 // C++ [namespace.memdef]p3
10123 // - If a friend declaration in a non-local class first declares a
10124 // class or function, the friend class or function is a member
10125 // of the innermost enclosing namespace.
10126 // - The name of the friend is not found by simple name lookup
10127 // until a matching declaration is provided in that namespace
10128 // scope (either before or after the class declaration granting
10129 // friendship).
10130 // - If a friend function is called, its name may be found by the
10131 // name lookup that considers functions from namespaces and
10132 // classes associated with the types of the function arguments.
10133 // - When looking for a prior declaration of a class or a function
10134 // declared as a friend, scopes outside the innermost enclosing
10135 // namespace scope are not considered.
10136
John McCall337ec3d2010-10-12 23:13:28 +000010137 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010138 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10139 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010140 assert(Name);
10141
Douglas Gregor6ccab972010-12-16 01:14:37 +000010142 // Check for unexpanded parameter packs.
10143 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10144 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10145 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10146 return 0;
10147
John McCall67d1a672009-08-06 02:15:43 +000010148 // The context we found the declaration in, or in which we should
10149 // create the declaration.
10150 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010151 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010152 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010153 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010154
John McCall337ec3d2010-10-12 23:13:28 +000010155 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010156
John McCall337ec3d2010-10-12 23:13:28 +000010157 // There are four cases here.
10158 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010159 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010160 // there as appropriate.
10161 // Recover from invalid scope qualifiers as if they just weren't there.
10162 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010163 // C++0x [namespace.memdef]p3:
10164 // If the name in a friend declaration is neither qualified nor
10165 // a template-id and the declaration is a function or an
10166 // elaborated-type-specifier, the lookup to determine whether
10167 // the entity has been previously declared shall not consider
10168 // any scopes outside the innermost enclosing namespace.
10169 // C++0x [class.friend]p11:
10170 // If a friend declaration appears in a local class and the name
10171 // specified is an unqualified name, a prior declaration is
10172 // looked up without considering scopes that are outside the
10173 // innermost enclosing non-class scope. For a friend function
10174 // declaration, if there is no prior declaration, the program is
10175 // ill-formed.
10176 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010177 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010178
John McCall29ae6e52010-10-13 05:45:15 +000010179 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010180 DC = CurContext;
10181 while (true) {
10182 // Skip class contexts. If someone can cite chapter and verse
10183 // for this behavior, that would be nice --- it's what GCC and
10184 // EDG do, and it seems like a reasonable intent, but the spec
10185 // really only says that checks for unqualified existing
10186 // declarations should stop at the nearest enclosing namespace,
10187 // not that they should only consider the nearest enclosing
10188 // namespace.
Nick Lewycky9c6fde52012-03-16 19:51:19 +000010189 while (DC->isRecord() || DC->isTransparentContext())
Douglas Gregor182ddf02009-09-28 00:08:27 +000010190 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010191
John McCall68263142009-11-18 22:49:29 +000010192 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010193
10194 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010195 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010196 break;
John McCall29ae6e52010-10-13 05:45:15 +000010197
John McCall8a407372010-10-14 22:22:28 +000010198 if (isTemplateId) {
10199 if (isa<TranslationUnitDecl>(DC)) break;
10200 } else {
10201 if (DC->isFileContext()) break;
10202 }
John McCall67d1a672009-08-06 02:15:43 +000010203 DC = DC->getParent();
10204 }
10205
10206 // C++ [class.friend]p1: A friend of a class is a function or
10207 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010208 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010209 // Most C++ 98 compilers do seem to give an error here, so
10210 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010211 if (!Previous.empty() && DC->Equals(CurContext))
10212 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010213 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010214 diag::warn_cxx98_compat_friend_is_member :
10215 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010216
John McCall380aaa42010-10-13 06:22:15 +000010217 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010218
Douglas Gregor883af832011-10-10 01:11:59 +000010219 // C++ [class.friend]p6:
10220 // A function can be defined in a friend declaration of a class if and
10221 // only if the class is a non-local class (9.8), the function name is
10222 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010223 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010224 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10225 }
10226
John McCall337ec3d2010-10-12 23:13:28 +000010227 // - There's a non-dependent scope specifier, in which case we
10228 // compute it and do a previous lookup there for a function
10229 // or function template.
10230 } else if (!SS.getScopeRep()->isDependent()) {
10231 DC = computeDeclContext(SS);
10232 if (!DC) return 0;
10233
10234 if (RequireCompleteDeclContext(SS, DC)) return 0;
10235
10236 LookupQualifiedName(Previous, DC);
10237
10238 // Ignore things found implicitly in the wrong scope.
10239 // TODO: better diagnostics for this case. Suggesting the right
10240 // qualified scope would be nice...
10241 LookupResult::Filter F = Previous.makeFilter();
10242 while (F.hasNext()) {
10243 NamedDecl *D = F.next();
10244 if (!DC->InEnclosingNamespaceSetOf(
10245 D->getDeclContext()->getRedeclContext()))
10246 F.erase();
10247 }
10248 F.done();
10249
10250 if (Previous.empty()) {
10251 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010252 Diag(Loc, diag::err_qualified_friend_not_found)
10253 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010254 return 0;
10255 }
10256
10257 // C++ [class.friend]p1: A friend of a class is a function or
10258 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010259 if (DC->Equals(CurContext))
10260 Diag(DS.getFriendSpecLoc(),
David Blaikie4e4d0842012-03-11 07:00:24 +000010261 getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +000010262 diag::warn_cxx98_compat_friend_is_member :
10263 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010264
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010265 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010266 // C++ [class.friend]p6:
10267 // A function can be defined in a friend declaration of a class if and
10268 // only if the class is a non-local class (9.8), the function name is
10269 // unqualified, and the function has namespace scope.
10270 SemaDiagnosticBuilder DB
10271 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10272
10273 DB << SS.getScopeRep();
10274 if (DC->isFileContext())
10275 DB << FixItHint::CreateRemoval(SS.getRange());
10276 SS.clear();
10277 }
John McCall337ec3d2010-10-12 23:13:28 +000010278
10279 // - There's a scope specifier that does not match any template
10280 // parameter lists, in which case we use some arbitrary context,
10281 // create a method or method template, and wait for instantiation.
10282 // - There's a scope specifier that does match some template
10283 // parameter lists, which we don't handle right now.
10284 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010285 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010286 // C++ [class.friend]p6:
10287 // A function can be defined in a friend declaration of a class if and
10288 // only if the class is a non-local class (9.8), the function name is
10289 // unqualified, and the function has namespace scope.
10290 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10291 << SS.getScopeRep();
10292 }
10293
John McCall337ec3d2010-10-12 23:13:28 +000010294 DC = CurContext;
10295 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010296 }
Douglas Gregor883af832011-10-10 01:11:59 +000010297
John McCall29ae6e52010-10-13 05:45:15 +000010298 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010299 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010300 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10301 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10302 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010303 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010304 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10305 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010306 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010307 }
John McCall67d1a672009-08-06 02:15:43 +000010308 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010309
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010310 // FIXME: This is an egregious hack to cope with cases where the scope stack
10311 // does not contain the declaration context, i.e., in an out-of-line
10312 // definition of a class.
10313 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10314 if (!DCScope) {
10315 FakeDCScope.setEntity(DC);
10316 DCScope = &FakeDCScope;
10317 }
10318
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010319 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010320 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010321 TemplateParams, AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010322 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010323
Douglas Gregor182ddf02009-09-28 00:08:27 +000010324 assert(ND->getDeclContext() == DC);
10325 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010326
John McCallab88d972009-08-31 22:39:49 +000010327 // Add the function declaration to the appropriate lookup tables,
10328 // adjusting the redeclarations list as necessary. We don't
10329 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010330 //
John McCallab88d972009-08-31 22:39:49 +000010331 // Also update the scope-based lookup if the target context's
10332 // lookup context is in lexical scope.
10333 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010334 DC = DC->getRedeclContext();
Richard Smith1b7f9cb2012-03-13 03:12:56 +000010335 DC->makeDeclVisibleInContext(ND);
John McCallab88d972009-08-31 22:39:49 +000010336 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010337 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010338 }
John McCall02cace72009-08-28 07:59:38 +000010339
10340 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010341 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010342 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010343 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010344 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010345
John McCall1f2e1a92012-08-10 03:15:35 +000010346 if (ND->isInvalidDecl()) {
John McCall337ec3d2010-10-12 23:13:28 +000010347 FrD->setInvalidDecl();
John McCall1f2e1a92012-08-10 03:15:35 +000010348 } else {
10349 if (DC->isRecord()) CheckFriendAccess(ND);
10350
John McCall6102ca12010-10-16 06:59:13 +000010351 FunctionDecl *FD;
10352 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10353 FD = FTD->getTemplatedDecl();
10354 else
10355 FD = cast<FunctionDecl>(ND);
10356
10357 // Mark templated-scope function declarations as unsupported.
10358 if (FD->getNumTemplateParameterLists())
10359 FrD->setUnsupportedFriend(true);
10360 }
John McCall337ec3d2010-10-12 23:13:28 +000010361
John McCalld226f652010-08-21 09:40:31 +000010362 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010363}
10364
John McCalld226f652010-08-21 09:40:31 +000010365void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10366 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010367
Sebastian Redl50de12f2009-03-24 22:27:57 +000010368 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10369 if (!Fn) {
10370 Diag(DelLoc, diag::err_deleted_non_function);
10371 return;
10372 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010373 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010374 // Don't consider the implicit declaration we generate for explicit
10375 // specializations. FIXME: Do not generate these implicit declarations.
David Blaikie619ee6a2012-06-29 18:00:25 +000010376 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
10377 || Prev->getPreviousDecl()) && !Prev->isDefined()) {
David Blaikied9cf8262012-06-25 21:55:30 +000010378 Diag(DelLoc, diag::err_deleted_decl_not_first);
10379 Diag(Prev->getLocation(), diag::note_previous_declaration);
10380 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010381 // If the declaration wasn't the first, we delete the function anyway for
10382 // recovery.
10383 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010384 Fn->setDeletedAsWritten();
Richard Smithe653ba22012-02-26 00:31:33 +000010385
10386 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10387 if (!MD)
10388 return;
10389
10390 // A deleted special member function is trivial if the corresponding
10391 // implicitly-declared function would have been.
10392 switch (getSpecialMember(MD)) {
10393 case CXXInvalid:
10394 break;
10395 case CXXDefaultConstructor:
10396 MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10397 break;
10398 case CXXCopyConstructor:
10399 MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10400 break;
10401 case CXXMoveConstructor:
10402 MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10403 break;
10404 case CXXCopyAssignment:
10405 MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10406 break;
10407 case CXXMoveAssignment:
10408 MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10409 break;
10410 case CXXDestructor:
10411 MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10412 break;
10413 }
Sebastian Redl50de12f2009-03-24 22:27:57 +000010414}
Sebastian Redl13e88542009-04-27 21:33:24 +000010415
Sean Hunte4246a62011-05-12 06:15:49 +000010416void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10417 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10418
10419 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010420 if (MD->getParent()->isDependentType()) {
10421 MD->setDefaulted();
10422 MD->setExplicitlyDefaulted();
10423 return;
10424 }
10425
Sean Hunte4246a62011-05-12 06:15:49 +000010426 CXXSpecialMember Member = getSpecialMember(MD);
10427 if (Member == CXXInvalid) {
10428 Diag(DefaultLoc, diag::err_default_special_members);
10429 return;
10430 }
10431
10432 MD->setDefaulted();
10433 MD->setExplicitlyDefaulted();
10434
Sean Huntcd10dec2011-05-23 23:14:04 +000010435 // If this definition appears within the record, do the checking when
10436 // the record is complete.
10437 const FunctionDecl *Primary = MD;
Richard Smitha8eaf002012-08-23 06:16:52 +000010438 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
Sean Huntcd10dec2011-05-23 23:14:04 +000010439 // Find the uninstantiated declaration that actually had the '= default'
10440 // on it.
Richard Smitha8eaf002012-08-23 06:16:52 +000010441 Pattern->isDefined(Primary);
Sean Huntcd10dec2011-05-23 23:14:04 +000010442
10443 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010444 return;
10445
Richard Smithb9d0b762012-07-27 04:22:15 +000010446 CheckExplicitlyDefaultedSpecialMember(MD);
10447
Sean Hunte4246a62011-05-12 06:15:49 +000010448 switch (Member) {
10449 case CXXDefaultConstructor: {
10450 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010451 if (!CD->isInvalidDecl())
10452 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10453 break;
10454 }
10455
10456 case CXXCopyConstructor: {
10457 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010458 if (!CD->isInvalidDecl())
10459 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010460 break;
10461 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010462
Sean Hunt2b188082011-05-14 05:23:28 +000010463 case CXXCopyAssignment: {
Sean Hunt2b188082011-05-14 05:23:28 +000010464 if (!MD->isInvalidDecl())
10465 DefineImplicitCopyAssignment(DefaultLoc, MD);
10466 break;
10467 }
10468
Sean Huntcb45a0f2011-05-12 22:46:25 +000010469 case CXXDestructor: {
10470 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010471 if (!DD->isInvalidDecl())
10472 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010473 break;
10474 }
10475
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010476 case CXXMoveConstructor: {
10477 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010478 if (!CD->isInvalidDecl())
10479 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010480 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010481 }
Sean Hunt82713172011-05-25 23:16:36 +000010482
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010483 case CXXMoveAssignment: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010484 if (!MD->isInvalidDecl())
10485 DefineImplicitMoveAssignment(DefaultLoc, MD);
10486 break;
10487 }
10488
10489 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010490 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010491 }
10492 } else {
10493 Diag(DefaultLoc, diag::err_default_special_members);
10494 }
10495}
10496
Sebastian Redl13e88542009-04-27 21:33:24 +000010497static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010498 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010499 Stmt *SubStmt = *CI;
10500 if (!SubStmt)
10501 continue;
10502 if (isa<ReturnStmt>(SubStmt))
Daniel Dunbar96a00142012-03-09 18:35:03 +000010503 Self.Diag(SubStmt->getLocStart(),
Sebastian Redl13e88542009-04-27 21:33:24 +000010504 diag::err_return_in_constructor_handler);
10505 if (!isa<Expr>(SubStmt))
10506 SearchForReturnInStmt(Self, SubStmt);
10507 }
10508}
10509
10510void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10511 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10512 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10513 SearchForReturnInStmt(*this, Handler);
10514 }
10515}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010516
Mike Stump1eb44332009-09-09 15:08:12 +000010517bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010518 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010519 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10520 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010521
Chandler Carruth73857792010-02-15 11:53:20 +000010522 if (Context.hasSameType(NewTy, OldTy) ||
10523 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010524 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010525
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010526 // Check if the return types are covariant
10527 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010528
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010529 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010530 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10531 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010532 NewClassTy = NewPT->getPointeeType();
10533 OldClassTy = OldPT->getPointeeType();
10534 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010535 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10536 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10537 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10538 NewClassTy = NewRT->getPointeeType();
10539 OldClassTy = OldRT->getPointeeType();
10540 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010541 }
10542 }
Mike Stump1eb44332009-09-09 15:08:12 +000010543
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010544 // The return types aren't either both pointers or references to a class type.
10545 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010546 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010547 diag::err_different_return_type_for_overriding_virtual_function)
10548 << New->getDeclName() << NewTy << OldTy;
10549 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010550
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010551 return true;
10552 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010553
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010554 // C++ [class.virtual]p6:
10555 // If the return type of D::f differs from the return type of B::f, the
10556 // class type in the return type of D::f shall be complete at the point of
10557 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010558 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10559 if (!RT->isBeingDefined() &&
10560 RequireCompleteType(New->getLocation(), NewClassTy,
Douglas Gregord10099e2012-05-04 16:32:21 +000010561 diag::err_covariant_return_incomplete,
10562 New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010563 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010564 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010565
Douglas Gregora4923eb2009-11-16 21:35:15 +000010566 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010567 // Check if the new class derives from the old class.
10568 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10569 Diag(New->getLocation(),
10570 diag::err_covariant_return_not_derived)
10571 << New->getDeclName() << NewTy << OldTy;
10572 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10573 return true;
10574 }
Mike Stump1eb44332009-09-09 15:08:12 +000010575
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010576 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010577 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010578 diag::err_covariant_return_inaccessible_base,
10579 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10580 // FIXME: Should this point to the return type?
10581 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010582 // FIXME: this note won't trigger for delayed access control
10583 // diagnostics, and it's impossible to get an undelayed error
10584 // here from access control during the original parse because
10585 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010586 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10587 return true;
10588 }
10589 }
Mike Stump1eb44332009-09-09 15:08:12 +000010590
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010591 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010592 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010593 Diag(New->getLocation(),
10594 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010595 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010596 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10597 return true;
10598 };
Mike Stump1eb44332009-09-09 15:08:12 +000010599
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010600
10601 // The new class type must have the same or less qualifiers as the old type.
10602 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10603 Diag(New->getLocation(),
10604 diag::err_covariant_return_type_class_type_more_qualified)
10605 << New->getDeclName() << NewTy << OldTy;
10606 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10607 return true;
10608 };
Mike Stump1eb44332009-09-09 15:08:12 +000010609
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010610 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010611}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010612
Douglas Gregor4ba31362009-12-01 17:24:26 +000010613/// \brief Mark the given method pure.
10614///
10615/// \param Method the method to be marked pure.
10616///
10617/// \param InitRange the source range that covers the "0" initializer.
10618bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010619 SourceLocation EndLoc = InitRange.getEnd();
10620 if (EndLoc.isValid())
10621 Method->setRangeEnd(EndLoc);
10622
Douglas Gregor4ba31362009-12-01 17:24:26 +000010623 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10624 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010625 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010626 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010627
10628 if (!Method->isInvalidDecl())
10629 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10630 << Method->getDeclName() << InitRange;
10631 return true;
10632}
10633
Douglas Gregor552e2992012-02-21 02:22:07 +000010634/// \brief Determine whether the given declaration is a static data member.
10635static bool isStaticDataMember(Decl *D) {
10636 VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10637 if (!Var)
10638 return false;
10639
10640 return Var->isStaticDataMember();
10641}
John McCall731ad842009-12-19 09:28:58 +000010642/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10643/// an initializer for the out-of-line declaration 'Dcl'. The scope
10644/// is a fresh scope pushed for just this purpose.
10645///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010646/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10647/// static data member of class X, names should be looked up in the scope of
10648/// class X.
John McCalld226f652010-08-21 09:40:31 +000010649void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010650 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010651 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010652
John McCall731ad842009-12-19 09:28:58 +000010653 // We should only get called for declarations with scope specifiers, like:
10654 // int foo::bar;
10655 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010656 EnterDeclaratorContext(S, D->getDeclContext());
Douglas Gregor552e2992012-02-21 02:22:07 +000010657
10658 // If we are parsing the initializer for a static data member, push a
10659 // new expression evaluation context that is associated with this static
10660 // data member.
10661 if (isStaticDataMember(D))
10662 PushExpressionEvaluationContext(PotentiallyEvaluated, D);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010663}
10664
10665/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010666/// initializer for the out-of-line declaration 'D'.
10667void Sema::ActOnCXXExitDeclInitializer(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
Douglas Gregor552e2992012-02-21 02:22:07 +000010671 if (isStaticDataMember(D))
10672 PopExpressionEvaluationContext();
10673
John McCall731ad842009-12-19 09:28:58 +000010674 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010675 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010676}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010677
10678/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10679/// C++ if/switch/while/for statement.
10680/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010681DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010682 // C++ 6.4p2:
10683 // The declarator shall not specify a function or an array.
10684 // The type-specifier-seq shall not contain typedef and shall not declare a
10685 // new class or enumeration.
10686 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10687 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010688
10689 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010690 if (!Dcl)
10691 return true;
10692
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010693 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10694 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010695 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010696 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010697 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010698
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010699 return Dcl;
10700}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010701
Douglas Gregordfe65432011-07-28 19:11:31 +000010702void Sema::LoadExternalVTableUses() {
10703 if (!ExternalSource)
10704 return;
10705
10706 SmallVector<ExternalVTableUse, 4> VTables;
10707 ExternalSource->ReadUsedVTables(VTables);
10708 SmallVector<VTableUse, 4> NewUses;
10709 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10710 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10711 = VTablesUsed.find(VTables[I].Record);
10712 // Even if a definition wasn't required before, it may be required now.
10713 if (Pos != VTablesUsed.end()) {
10714 if (!Pos->second && VTables[I].DefinitionRequired)
10715 Pos->second = true;
10716 continue;
10717 }
10718
10719 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10720 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10721 }
10722
10723 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10724}
10725
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010726void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10727 bool DefinitionRequired) {
10728 // Ignore any vtable uses in unevaluated operands or for classes that do
10729 // not have a vtable.
10730 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10731 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010732 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010733 return;
10734
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010735 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010736 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010737 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10738 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10739 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10740 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010741 // If we already had an entry, check to see if we are promoting this vtable
10742 // to required a definition. If so, we need to reappend to the VTableUses
10743 // list, since we may have already processed the first entry.
10744 if (DefinitionRequired && !Pos.first->second) {
10745 Pos.first->second = true;
10746 } else {
10747 // Otherwise, we can early exit.
10748 return;
10749 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010750 }
10751
10752 // Local classes need to have their virtual members marked
10753 // immediately. For all other classes, we mark their virtual members
10754 // at the end of the translation unit.
10755 if (Class->isLocalClass())
10756 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010757 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010758 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010759}
10760
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010761bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010762 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010763 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010764 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010765
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010766 // Note: The VTableUses vector could grow as a result of marking
10767 // the members of a class as "used", so we check the size each
Richard Smithb9d0b762012-07-27 04:22:15 +000010768 // time through the loop and prefer indices (which are stable) to
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010769 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010770 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010771 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010772 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010773 if (!Class)
10774 continue;
10775
10776 SourceLocation Loc = VTableUses[I].second;
10777
Richard Smithb9d0b762012-07-27 04:22:15 +000010778 bool DefineVTable = true;
10779
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010780 // If this class has a key function, but that key function is
10781 // defined in another translation unit, we don't need to emit the
10782 // vtable even though we're using it.
10783 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010784 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010785 switch (KeyFunction->getTemplateSpecializationKind()) {
10786 case TSK_Undeclared:
10787 case TSK_ExplicitSpecialization:
10788 case TSK_ExplicitInstantiationDeclaration:
10789 // The key function is in another translation unit.
Richard Smithb9d0b762012-07-27 04:22:15 +000010790 DefineVTable = false;
10791 break;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010792
10793 case TSK_ExplicitInstantiationDefinition:
10794 case TSK_ImplicitInstantiation:
10795 // We will be instantiating the key function.
10796 break;
10797 }
10798 } else if (!KeyFunction) {
10799 // If we have a class with no key function that is the subject
10800 // of an explicit instantiation declaration, suppress the
10801 // vtable; it will live with the explicit instantiation
10802 // definition.
10803 bool IsExplicitInstantiationDeclaration
10804 = Class->getTemplateSpecializationKind()
10805 == TSK_ExplicitInstantiationDeclaration;
10806 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10807 REnd = Class->redecls_end();
10808 R != REnd; ++R) {
10809 TemplateSpecializationKind TSK
10810 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10811 if (TSK == TSK_ExplicitInstantiationDeclaration)
10812 IsExplicitInstantiationDeclaration = true;
10813 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10814 IsExplicitInstantiationDeclaration = false;
10815 break;
10816 }
10817 }
10818
10819 if (IsExplicitInstantiationDeclaration)
Richard Smithb9d0b762012-07-27 04:22:15 +000010820 DefineVTable = false;
10821 }
10822
10823 // The exception specifications for all virtual members may be needed even
10824 // if we are not providing an authoritative form of the vtable in this TU.
10825 // We may choose to emit it available_externally anyway.
10826 if (!DefineVTable) {
10827 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
10828 continue;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010829 }
10830
10831 // Mark all of the virtual members of this class as referenced, so
10832 // that we can build a vtable. Then, tell the AST consumer that a
10833 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010834 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010835 MarkVirtualMembersReferenced(Loc, Class);
10836 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10837 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10838
10839 // Optionally warn if we're emitting a weak vtable.
10840 if (Class->getLinkage() == ExternalLinkage &&
10841 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010842 const FunctionDecl *KeyFunctionDef = 0;
10843 if (!KeyFunction ||
10844 (KeyFunction->hasBody(KeyFunctionDef) &&
10845 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010846 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10847 TSK_ExplicitInstantiationDefinition
10848 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10849 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010850 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010851 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010852 VTableUses.clear();
10853
Douglas Gregor78844032011-04-22 22:25:37 +000010854 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010855}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010856
Richard Smithb9d0b762012-07-27 04:22:15 +000010857void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
10858 const CXXRecordDecl *RD) {
10859 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
10860 E = RD->method_end(); I != E; ++I)
10861 if ((*I)->isVirtual() && !(*I)->isPure())
10862 ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
10863}
10864
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010865void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10866 const CXXRecordDecl *RD) {
Richard Smithff817f72012-07-07 06:59:51 +000010867 // Mark all functions which will appear in RD's vtable as used.
10868 CXXFinalOverriderMap FinalOverriders;
10869 RD->getFinalOverriders(FinalOverriders);
10870 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
10871 E = FinalOverriders.end();
10872 I != E; ++I) {
10873 for (OverridingMethods::const_iterator OI = I->second.begin(),
10874 OE = I->second.end();
10875 OI != OE; ++OI) {
10876 assert(OI->second.size() > 0 && "no final overrider");
10877 CXXMethodDecl *Overrider = OI->second.front().Method;
Anders Carlssond6a637f2009-12-07 08:24:59 +000010878
Richard Smithff817f72012-07-07 06:59:51 +000010879 // C++ [basic.def.odr]p2:
10880 // [...] A virtual member function is used if it is not pure. [...]
10881 if (!Overrider->isPure())
10882 MarkFunctionReferenced(Loc, Overrider);
10883 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010884 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010885
10886 // Only classes that have virtual bases need a VTT.
10887 if (RD->getNumVBases() == 0)
10888 return;
10889
10890 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10891 e = RD->bases_end(); i != e; ++i) {
10892 const CXXRecordDecl *Base =
10893 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010894 if (Base->getNumVBases() == 0)
10895 continue;
10896 MarkVirtualMembersReferenced(Loc, Base);
10897 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010898}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010899
10900/// SetIvarInitializers - This routine builds initialization ASTs for the
10901/// Objective-C implementation whose ivars need be initialized.
10902void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
David Blaikie4e4d0842012-03-11 07:00:24 +000010903 if (!getLangOpts().CPlusPlus)
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010904 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010905 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010906 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010907 CollectIvarsToConstructOrDestruct(OID, ivars);
10908 if (ivars.empty())
10909 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010910 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010911 for (unsigned i = 0; i < ivars.size(); i++) {
10912 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010913 if (Field->isInvalidDecl())
10914 continue;
10915
Sean Huntcbb67482011-01-08 20:30:50 +000010916 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010917 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10918 InitializationKind InitKind =
10919 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10920
10921 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010922 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010923 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010924 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010925 // Note, MemberInit could actually come back empty if no initialization
10926 // is required (e.g., because it would call a trivial default constructor)
10927 if (!MemberInit.get() || MemberInit.isInvalid())
10928 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010929
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010930 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010931 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10932 SourceLocation(),
10933 MemberInit.takeAs<Expr>(),
10934 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010935 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010936
10937 // Be sure that the destructor is accessible and is marked as referenced.
10938 if (const RecordType *RecordTy
10939 = Context.getBaseElementType(Field->getType())
10940 ->getAs<RecordType>()) {
10941 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010942 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010943 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010944 CheckDestructorAccess(Field->getLocation(), Destructor,
10945 PDiag(diag::err_access_dtor_ivar)
10946 << Context.getBaseElementType(Field->getType()));
10947 }
10948 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010949 }
10950 ObjCImplementation->setIvarInitializers(Context,
10951 AllToInit.data(), AllToInit.size());
10952 }
10953}
Sean Huntfe57eef2011-05-04 05:57:24 +000010954
Sean Huntebcbe1d2011-05-04 23:29:54 +000010955static
10956void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10957 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10958 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10959 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10960 Sema &S) {
10961 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10962 CE = Current.end();
10963 if (Ctor->isInvalidDecl())
10964 return;
10965
Richard Smitha8eaf002012-08-23 06:16:52 +000010966 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
10967
10968 // Target may not be determinable yet, for instance if this is a dependent
10969 // call in an uninstantiated template.
10970 if (Target) {
10971 const FunctionDecl *FNTarget = 0;
10972 (void)Target->hasBody(FNTarget);
10973 Target = const_cast<CXXConstructorDecl*>(
10974 cast_or_null<CXXConstructorDecl>(FNTarget));
10975 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000010976
10977 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10978 // Avoid dereferencing a null pointer here.
10979 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10980
10981 if (!Current.insert(Canonical))
10982 return;
10983
10984 // We know that beyond here, we aren't chaining into a cycle.
10985 if (!Target || !Target->isDelegatingConstructor() ||
10986 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10987 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10988 Valid.insert(*CI);
10989 Current.clear();
10990 // We've hit a cycle.
10991 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10992 Current.count(TCanonical)) {
10993 // If we haven't diagnosed this cycle yet, do so now.
10994 if (!Invalid.count(TCanonical)) {
10995 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000010996 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000010997 << Ctor;
10998
Richard Smitha8eaf002012-08-23 06:16:52 +000010999 // Don't add a note for a function delegating directly to itself.
Sean Huntebcbe1d2011-05-04 23:29:54 +000011000 if (TCanonical != Canonical)
11001 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11002
11003 CXXConstructorDecl *C = Target;
11004 while (C->getCanonicalDecl() != Canonical) {
Richard Smitha8eaf002012-08-23 06:16:52 +000011005 const FunctionDecl *FNTarget = 0;
Sean Huntebcbe1d2011-05-04 23:29:54 +000011006 (void)C->getTargetConstructor()->hasBody(FNTarget);
11007 assert(FNTarget && "Ctor cycle through bodiless function");
11008
Richard Smitha8eaf002012-08-23 06:16:52 +000011009 C = const_cast<CXXConstructorDecl*>(
11010 cast<CXXConstructorDecl>(FNTarget));
Sean Huntebcbe1d2011-05-04 23:29:54 +000011011 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11012 }
11013 }
11014
11015 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11016 Invalid.insert(*CI);
11017 Current.clear();
11018 } else {
11019 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11020 }
11021}
11022
11023
Sean Huntfe57eef2011-05-04 05:57:24 +000011024void Sema::CheckDelegatingCtorCycles() {
11025 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11026
Sean Huntebcbe1d2011-05-04 23:29:54 +000011027 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11028 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011029
Douglas Gregor0129b562011-07-27 21:57:17 +000011030 for (DelegatingCtorDeclsType::iterator
11031 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011032 E = DelegatingCtorDecls.end();
Richard Smitha8eaf002012-08-23 06:16:52 +000011033 I != E; ++I)
11034 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntebcbe1d2011-05-04 23:29:54 +000011035
11036 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11037 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011038}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011039
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011040namespace {
11041 /// \brief AST visitor that finds references to the 'this' expression.
11042 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11043 Sema &S;
11044
11045 public:
11046 explicit FindCXXThisExpr(Sema &S) : S(S) { }
11047
11048 bool VisitCXXThisExpr(CXXThisExpr *E) {
11049 S.Diag(E->getLocation(), diag::err_this_static_member_func)
11050 << E->isImplicit();
11051 return false;
11052 }
11053 };
11054}
11055
11056bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11057 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11058 if (!TSInfo)
11059 return false;
11060
11061 TypeLoc TL = TSInfo->getTypeLoc();
11062 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11063 if (!ProtoTL)
11064 return false;
11065
11066 // C++11 [expr.prim.general]p3:
11067 // [The expression this] shall not appear before the optional
11068 // cv-qualifier-seq and it shall not appear within the declaration of a
11069 // static member function (although its type and value category are defined
11070 // within a static member function as they are within a non-static member
11071 // function). [ Note: this is because declaration matching does not occur
NAKAMURA Takumic86d1fd2012-04-21 09:40:04 +000011072 // until the complete declarator is known. - end note ]
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011073 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11074 FindCXXThisExpr Finder(*this);
11075
11076 // If the return type came after the cv-qualifier-seq, check it now.
11077 if (Proto->hasTrailingReturn() &&
11078 !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11079 return true;
11080
11081 // Check the exception specification.
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011082 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
11083 return true;
11084
11085 return checkThisInStaticMemberFunctionAttributes(Method);
11086}
11087
11088bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11089 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11090 if (!TSInfo)
11091 return false;
11092
11093 TypeLoc TL = TSInfo->getTypeLoc();
11094 FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11095 if (!ProtoTL)
11096 return false;
11097
11098 const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11099 FindCXXThisExpr Finder(*this);
11100
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011101 switch (Proto->getExceptionSpecType()) {
Richard Smithe6975e92012-04-17 00:58:00 +000011102 case EST_Uninstantiated:
Richard Smithb9d0b762012-07-27 04:22:15 +000011103 case EST_Unevaluated:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011104 case EST_BasicNoexcept:
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011105 case EST_DynamicNone:
11106 case EST_MSAny:
11107 case EST_None:
11108 break;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011109
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011110 case EST_ComputedNoexcept:
11111 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11112 return true;
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011113
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011114 case EST_Dynamic:
11115 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011116 EEnd = Proto->exception_end();
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011117 E != EEnd; ++E) {
11118 if (!Finder.TraverseType(*E))
11119 return true;
11120 }
11121 break;
11122 }
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011123
11124 return false;
Douglas Gregorcefc3af2012-04-16 07:05:22 +000011125}
11126
11127bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11128 FindCXXThisExpr Finder(*this);
11129
11130 // Check attributes.
11131 for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11132 A != AEnd; ++A) {
11133 // FIXME: This should be emitted by tblgen.
11134 Expr *Arg = 0;
11135 ArrayRef<Expr *> Args;
11136 if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11137 Arg = G->getArg();
11138 else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11139 Arg = G->getArg();
11140 else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11141 Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11142 else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11143 Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11144 else if (ExclusiveLockFunctionAttr *ELF
11145 = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11146 Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11147 else if (SharedLockFunctionAttr *SLF
11148 = dyn_cast<SharedLockFunctionAttr>(*A))
11149 Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11150 else if (ExclusiveTrylockFunctionAttr *ETLF
11151 = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11152 Arg = ETLF->getSuccessValue();
11153 Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11154 } else if (SharedTrylockFunctionAttr *STLF
11155 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11156 Arg = STLF->getSuccessValue();
11157 Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11158 } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11159 Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11160 else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11161 Arg = LR->getArg();
11162 else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11163 Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11164 else if (ExclusiveLocksRequiredAttr *ELR
11165 = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11166 Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11167 else if (SharedLocksRequiredAttr *SLR
11168 = dyn_cast<SharedLocksRequiredAttr>(*A))
11169 Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11170
11171 if (Arg && !Finder.TraverseStmt(Arg))
11172 return true;
11173
11174 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11175 if (!Finder.TraverseStmt(Args[I]))
11176 return true;
11177 }
11178 }
11179
11180 return false;
11181}
11182
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011183void
11184Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11185 ArrayRef<ParsedType> DynamicExceptions,
11186 ArrayRef<SourceRange> DynamicExceptionRanges,
11187 Expr *NoexceptExpr,
11188 llvm::SmallVectorImpl<QualType> &Exceptions,
11189 FunctionProtoType::ExtProtoInfo &EPI) {
11190 Exceptions.clear();
11191 EPI.ExceptionSpecType = EST;
11192 if (EST == EST_Dynamic) {
11193 Exceptions.reserve(DynamicExceptions.size());
11194 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11195 // FIXME: Preserve type source info.
11196 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11197
11198 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11199 collectUnexpandedParameterPacks(ET, Unexpanded);
11200 if (!Unexpanded.empty()) {
11201 DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11202 UPPC_ExceptionType,
11203 Unexpanded);
11204 continue;
11205 }
11206
11207 // Check that the type is valid for an exception spec, and
11208 // drop it if not.
11209 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11210 Exceptions.push_back(ET);
11211 }
11212 EPI.NumExceptions = Exceptions.size();
11213 EPI.Exceptions = Exceptions.data();
11214 return;
11215 }
11216
11217 if (EST == EST_ComputedNoexcept) {
11218 // If an error occurred, there's no expression here.
11219 if (NoexceptExpr) {
11220 assert((NoexceptExpr->isTypeDependent() ||
11221 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11222 Context.BoolTy) &&
11223 "Parser should have made sure that the expression is boolean");
11224 if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11225 EPI.ExceptionSpecType = EST_BasicNoexcept;
11226 return;
11227 }
11228
11229 if (!NoexceptExpr->isValueDependent())
11230 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
Douglas Gregorab41fe92012-05-04 22:38:52 +000011231 diag::err_noexcept_needs_constant_expression,
Douglas Gregor74e2fc32012-04-16 18:27:27 +000011232 /*AllowFold*/ false).take();
11233 EPI.NoexceptExpr = NoexceptExpr;
11234 }
11235 return;
11236 }
11237}
11238
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011239/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11240Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11241 // Implicitly declared functions (e.g. copy constructors) are
11242 // __host__ __device__
11243 if (D->isImplicit())
11244 return CFT_HostDevice;
11245
11246 if (D->hasAttr<CUDAGlobalAttr>())
11247 return CFT_Global;
11248
11249 if (D->hasAttr<CUDADeviceAttr>()) {
11250 if (D->hasAttr<CUDAHostAttr>())
11251 return CFT_HostDevice;
11252 else
11253 return CFT_Device;
11254 }
11255
11256 return CFT_Host;
11257}
11258
11259bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11260 CUDAFunctionTarget CalleeTarget) {
11261 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11262 // Callable from the device only."
11263 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11264 return true;
11265
11266 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11267 // Callable from the host only."
11268 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11269 // Callable from the host only."
11270 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11271 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11272 return true;
11273
11274 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11275 return true;
11276
11277 return false;
11278}