blob: a52d44c4f2e403cdfd395fe58654bba52bbad0a6 [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"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redl58a2cd82011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Sean Hunt41717662011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregor06a9f362010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregor802ab452009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregor02189362008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall19510852010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCall50df6ae2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000036#include "llvm/ADT/STLExtras.h"
Douglas Gregorf8268ae2008-10-22 17:49:05 +000037#include <map>
Douglas Gregora8f32e02009-10-06 17:59:45 +000038#include <set>
Chris Lattner3d1cee32008-04-08 05:04:30 +000039
40using namespace clang;
41
Chris Lattner8123a952008-04-10 02:22:51 +000042//===----------------------------------------------------------------------===//
43// CheckDefaultArgumentVisitor
44//===----------------------------------------------------------------------===//
45
Chris Lattner9e979552008-04-12 23:52:44 +000046namespace {
47 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
48 /// the default argument of a parameter to determine whether it
49 /// contains any ill-formed subexpressions. For example, this will
50 /// diagnose the use of local variables or parameters within the
51 /// default argument expression.
Benjamin Kramer85b45212009-11-28 19:45:26 +000052 class CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000053 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000054 Expr *DefaultArg;
55 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000056
Chris Lattner9e979552008-04-12 23:52:44 +000057 public:
Mike Stump1eb44332009-09-09 15:08:12 +000058 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattner9e979552008-04-12 23:52:44 +000059 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000060
Chris Lattner9e979552008-04-12 23:52:44 +000061 bool VisitExpr(Expr *Node);
62 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000063 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000064 };
Chris Lattner8123a952008-04-10 02:22:51 +000065
Chris Lattner9e979552008-04-12 23:52:44 +000066 /// VisitExpr - Visit all of the children of this expression.
67 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
68 bool IsInvalid = false;
John McCall7502c1d2011-02-13 04:07:26 +000069 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattnerb77792e2008-07-26 22:17:49 +000070 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000071 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000072 }
73
Chris Lattner9e979552008-04-12 23:52:44 +000074 /// VisitDeclRefExpr - Visit a reference to a declaration, to
75 /// determine whether this declaration can be used in the default
76 /// argument expression.
77 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000078 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000079 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
80 // C++ [dcl.fct.default]p9
81 // Default arguments are evaluated each time the function is
82 // called. The order of evaluation of function arguments is
83 // unspecified. Consequently, parameters of a function shall not
84 // be used in default argument expressions, even if they are not
85 // evaluated. Parameters of a function declared before a default
86 // argument expression are in scope and can hide namespace and
87 // class member names.
Mike Stump1eb44332009-09-09 15:08:12 +000088 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000089 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000090 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000091 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000092 // C++ [dcl.fct.default]p7
93 // Local variables shall not be used in default argument
94 // expressions.
John McCallb6bbcc92010-10-15 04:57:14 +000095 if (VDecl->isLocalVarDecl())
Mike Stump1eb44332009-09-09 15:08:12 +000096 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000097 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000098 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000099 }
Chris Lattner8123a952008-04-10 02:22:51 +0000100
Douglas Gregor3996f232008-11-04 13:41:56 +0000101 return false;
102 }
Chris Lattner9e979552008-04-12 23:52:44 +0000103
Douglas Gregor796da182008-11-04 14:32:21 +0000104 /// VisitCXXThisExpr - Visit a C++ "this" expression.
105 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
106 // C++ [dcl.fct.default]p8:
107 // The keyword this shall not be used in a default argument of a
108 // member function.
109 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000110 diag::err_param_default_argument_references_this)
111 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000112 }
Chris Lattner8123a952008-04-10 02:22:51 +0000113}
114
Sean Hunt001cad92011-05-10 00:49:42 +0000115void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000116 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith7a614d82011-06-11 17:19:42 +0000117 // If we have an MSAny or unknown spec already, don't bother.
118 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Sean Hunt001cad92011-05-10 00:49:42 +0000119 return;
120
121 const FunctionProtoType *Proto
122 = Method->getType()->getAs<FunctionProtoType>();
123
124 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
125
126 // If this function can throw any exceptions, make a note of that.
Richard Smith7a614d82011-06-11 17:19:42 +0000127 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Sean Hunt001cad92011-05-10 00:49:42 +0000128 ClearExceptions();
129 ComputedEST = EST;
130 return;
131 }
132
Richard Smith7a614d82011-06-11 17:19:42 +0000133 // FIXME: If the call to this decl is using any of its default arguments, we
134 // need to search them for potentially-throwing calls.
135
Sean Hunt001cad92011-05-10 00:49:42 +0000136 // If this function has a basic noexcept, it doesn't affect the outcome.
137 if (EST == EST_BasicNoexcept)
138 return;
139
140 // If we have a throw-all spec at this point, ignore the function.
141 if (ComputedEST == EST_None)
142 return;
143
144 // If we're still at noexcept(true) and there's a nothrow() callee,
145 // change to that specification.
146 if (EST == EST_DynamicNone) {
147 if (ComputedEST == EST_BasicNoexcept)
148 ComputedEST = EST_DynamicNone;
149 return;
150 }
151
152 // Check out noexcept specs.
153 if (EST == EST_ComputedNoexcept) {
Sean Hunt49634cf2011-05-13 06:10:58 +0000154 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Sean Hunt001cad92011-05-10 00:49:42 +0000155 assert(NR != FunctionProtoType::NR_NoNoexcept &&
156 "Must have noexcept result for EST_ComputedNoexcept.");
157 assert(NR != FunctionProtoType::NR_Dependent &&
158 "Should not generate implicit declarations for dependent cases, "
159 "and don't know how to handle them anyway.");
160
161 // noexcept(false) -> no spec on the new function
162 if (NR == FunctionProtoType::NR_Throw) {
163 ClearExceptions();
164 ComputedEST = EST_None;
165 }
166 // noexcept(true) won't change anything either.
167 return;
168 }
169
170 assert(EST == EST_Dynamic && "EST case not considered earlier.");
171 assert(ComputedEST != EST_None &&
172 "Shouldn't collect exceptions when throw-all is guaranteed.");
173 ComputedEST = EST_Dynamic;
174 // Record the exceptions in this function's exception specification.
175 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
176 EEnd = Proto->exception_end();
177 E != EEnd; ++E)
Sean Hunt49634cf2011-05-13 06:10:58 +0000178 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Sean Hunt001cad92011-05-10 00:49:42 +0000179 Exceptions.push_back(*E);
180}
181
Richard Smith7a614d82011-06-11 17:19:42 +0000182void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
183 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
184 return;
185
186 // FIXME:
187 //
188 // C++0x [except.spec]p14:
NAKAMURA Takumi48579472011-06-21 03:19:28 +0000189 // [An] implicit exception-specification specifies the type-id T if and
190 // only if T is allowed by the exception-specification of a function directly
191 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith7a614d82011-06-11 17:19:42 +0000192 // function it directly invokes allows all exceptions, and f shall allow no
193 // exceptions if every function it directly invokes allows no exceptions.
194 //
195 // Note in particular that if an implicit exception-specification is generated
196 // for a function containing a throw-expression, that specification can still
197 // be noexcept(true).
198 //
199 // Note also that 'directly invoked' is not defined in the standard, and there
200 // is no indication that we should only consider potentially-evaluated calls.
201 //
202 // Ultimately we should implement the intent of the standard: the exception
203 // specification should be the set of exceptions which can be thrown by the
204 // implicit definition. For now, we assume that any non-nothrow expression can
205 // throw any exception.
206
207 if (E->CanThrow(*Context))
208 ComputedEST = EST_None;
209}
210
Anders Carlssoned961f92009-08-25 02:29:20 +0000211bool
John McCall9ae2f072010-08-23 23:25:46 +0000212Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump1eb44332009-09-09 15:08:12 +0000213 SourceLocation EqualLoc) {
Anders Carlsson5653ca52009-08-25 13:46:13 +0000214 if (RequireCompleteType(Param->getLocation(), Param->getType(),
215 diag::err_typecheck_decl_incomplete_type)) {
216 Param->setInvalidDecl();
217 return true;
218 }
219
Anders Carlssoned961f92009-08-25 02:29:20 +0000220 // C++ [dcl.fct.default]p5
221 // A default argument expression is implicitly converted (clause
222 // 4) to the parameter type. The default argument expression has
223 // the same semantic constraints as the initializer expression in
224 // a declaration of a variable of the parameter type, using the
225 // copy-initialization semantics (8.5).
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000226 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
227 Param);
Douglas Gregor99a2e602009-12-16 01:38:02 +0000228 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
229 EqualLoc);
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000230 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCall60d7b3a2010-08-24 06:29:42 +0000231 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000232 MultiExprArg(*this, &Arg, 1));
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000233 if (Result.isInvalid())
Anders Carlsson9351c172009-08-25 03:18:48 +0000234 return true;
Eli Friedman4a2c19b2009-12-22 02:46:13 +0000235 Arg = Result.takeAs<Expr>();
Anders Carlssoned961f92009-08-25 02:29:20 +0000236
John McCallb4eb64d2010-10-08 02:01:28 +0000237 CheckImplicitConversions(Arg, EqualLoc);
John McCall4765fa02010-12-06 08:20:24 +0000238 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Anders Carlssoned961f92009-08-25 02:29:20 +0000240 // Okay: add the default argument to the parameter
241 Param->setDefaultArg(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Douglas Gregor8cfb7a32010-10-12 18:23:32 +0000243 // We have already instantiated this parameter; provide each of the
244 // instantiations with the uninstantiated default argument.
245 UnparsedDefaultArgInstantiationsMap::iterator InstPos
246 = UnparsedDefaultArgInstantiations.find(Param);
247 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
248 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
249 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
250
251 // We're done tracking this parameter's instantiations.
252 UnparsedDefaultArgInstantiations.erase(InstPos);
253 }
254
Anders Carlsson9351c172009-08-25 03:18:48 +0000255 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000256}
257
Chris Lattner8123a952008-04-10 02:22:51 +0000258/// ActOnParamDefaultArgument - Check whether the default argument
259/// provided for a function parameter is well-formed. If so, attach it
260/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000261void
John McCalld226f652010-08-21 09:40:31 +0000262Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000263 Expr *DefaultArg) {
264 if (!param || !DefaultArg)
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000265 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000266
John McCalld226f652010-08-21 09:40:31 +0000267 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000268 UnparsedDefaultArgLocs.erase(Param);
269
Chris Lattner3d1cee32008-04-08 05:04:30 +0000270 // Default arguments are only permitted in C++
271 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000272 Diag(EqualLoc, diag::err_param_default_argument)
273 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000274 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000275 return;
276 }
277
Douglas Gregor6f526752010-12-16 08:48:57 +0000278 // Check for unexpanded parameter packs.
279 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
280 Param->setInvalidDecl();
281 return;
282 }
283
Anders Carlsson66e30672009-08-25 01:02:06 +0000284 // Check that the default argument is well-formed
John McCall9ae2f072010-08-23 23:25:46 +0000285 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
286 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlsson66e30672009-08-25 01:02:06 +0000287 Param->setInvalidDecl();
288 return;
289 }
Mike Stump1eb44332009-09-09 15:08:12 +0000290
John McCall9ae2f072010-08-23 23:25:46 +0000291 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000292}
293
Douglas Gregor61366e92008-12-24 00:01:03 +0000294/// ActOnParamUnparsedDefaultArgument - We've seen a default
295/// argument for a function parameter, but we can't parse it yet
296/// because we're inside a class definition. Note that this default
297/// argument will be parsed later.
John McCalld226f652010-08-21 09:40:31 +0000298void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000299 SourceLocation EqualLoc,
300 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000301 if (!param)
302 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000303
John McCalld226f652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000305 if (Param)
306 Param->setUnparsedDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Anders Carlsson5e300d12009-06-12 16:51:40 +0000308 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000309}
310
Douglas Gregor72b505b2008-12-16 21:30:33 +0000311/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
312/// the default argument for the parameter param failed.
John McCalld226f652010-08-21 09:40:31 +0000313void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000314 if (!param)
315 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000316
John McCalld226f652010-08-21 09:40:31 +0000317 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Anders Carlsson5e300d12009-06-12 16:51:40 +0000319 Param->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Anders Carlsson5e300d12009-06-12 16:51:40 +0000321 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000322}
323
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000324/// CheckExtraCXXDefaultArguments - Check for any extra default
325/// arguments in the declarator, which is not a function declaration
326/// or definition and therefore is not permitted to have default
327/// arguments. This routine should be invoked for every declarator
328/// that is not a function declaration or definition.
329void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
330 // C++ [dcl.fct.default]p3
331 // A default argument expression shall be specified only in the
332 // parameter-declaration-clause of a function declaration or in a
333 // template-parameter (14.1). It shall not be specified for a
334 // parameter pack. If it is specified in a
335 // parameter-declaration-clause, it shall not occur within a
336 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000337 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000338 DeclaratorChunk &chunk = D.getTypeObject(i);
339 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000340 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
341 ParmVarDecl *Param =
John McCalld226f652010-08-21 09:40:31 +0000342 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor61366e92008-12-24 00:01:03 +0000343 if (Param->hasUnparsedDefaultArg()) {
344 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000345 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
346 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
347 delete Toks;
348 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000349 } else if (Param->getDefaultArg()) {
350 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
351 << Param->getDefaultArg()->getSourceRange();
352 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000353 }
354 }
355 }
356 }
357}
358
Chris Lattner3d1cee32008-04-08 05:04:30 +0000359// MergeCXXFunctionDecl - Merge two declarations of the same C++
360// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000361// type. Subroutine of MergeFunctionDecl. Returns true if there was an
362// error, false otherwise.
363bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
364 bool Invalid = false;
365
Chris Lattner3d1cee32008-04-08 05:04:30 +0000366 // C++ [dcl.fct.default]p4:
Chris Lattner3d1cee32008-04-08 05:04:30 +0000367 // For non-template functions, default arguments can be added in
368 // later declarations of a function in the same
369 // scope. Declarations in different scopes have completely
370 // distinct sets of default arguments. That is, declarations in
371 // inner scopes do not acquire default arguments from
372 // declarations in outer scopes, and vice versa. In a given
373 // function declaration, all parameters subsequent to a
374 // parameter with a default argument shall have default
375 // arguments supplied in this or previous declarations. A
376 // default argument shall not be redefined by a later
377 // declaration (not even to the same value).
Douglas Gregor6cc15182009-09-11 18:44:32 +0000378 //
379 // C++ [dcl.fct.default]p6:
380 // Except for member functions of class templates, the default arguments
381 // in a member function definition that appears outside of the class
382 // definition are added to the set of default arguments provided by the
383 // member function declaration in the class definition.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000384 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
385 ParmVarDecl *OldParam = Old->getParamDecl(p);
386 ParmVarDecl *NewParam = New->getParamDecl(p);
387
Douglas Gregor6cc15182009-09-11 18:44:32 +0000388 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000389
Francois Pichet8d051e02011-04-10 03:03:52 +0000390 unsigned DiagDefaultParamID =
391 diag::err_param_default_argument_redefinition;
392
393 // MSVC accepts that default parameters be redefined for member functions
394 // of template class. The new default parameter's value is ignored.
395 Invalid = true;
Francois Pichet62ec1f22011-09-17 17:15:52 +0000396 if (getLangOptions().MicrosoftExt) {
Francois Pichet8d051e02011-04-10 03:03:52 +0000397 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
398 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cf90492011-04-10 04:58:30 +0000399 // Merge the old default argument into the new parameter.
400 NewParam->setHasInheritedDefaultArg();
401 if (OldParam->hasUninstantiatedDefaultArg())
402 NewParam->setUninstantiatedDefaultArg(
403 OldParam->getUninstantiatedDefaultArg());
404 else
405 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichetcf320c62011-04-22 08:25:24 +0000406 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet8d051e02011-04-10 03:03:52 +0000407 Invalid = false;
408 }
409 }
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000410
Francois Pichet8cf90492011-04-10 04:58:30 +0000411 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
412 // hint here. Alternatively, we could walk the type-source information
413 // for NewParam to find the last source location in the type... but it
414 // isn't worth the effort right now. This is the kind of test case that
415 // is hard to get right:
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000416 // int f(int);
417 // void g(int (*fp)(int) = f);
418 // void g(int (*fp)(int) = &f);
Francois Pichet8d051e02011-04-10 03:03:52 +0000419 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor4f123ff2010-01-13 00:12:48 +0000420 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000421
422 // Look for the function declaration where the default argument was
423 // actually written, which may be a declaration prior to Old.
Douglas Gregoref96ee02012-01-14 16:38:05 +0000424 for (FunctionDecl *Older = Old->getPreviousDecl();
425 Older; Older = Older->getPreviousDecl()) {
Douglas Gregor6cc15182009-09-11 18:44:32 +0000426 if (!Older->getParamDecl(p)->hasDefaultArg())
427 break;
428
429 OldParam = Older->getParamDecl(p);
430 }
431
432 Diag(OldParam->getLocation(), diag::note_previous_definition)
433 << OldParam->getDefaultArgRange();
Douglas Gregord85cef52009-09-17 19:51:30 +0000434 } else if (OldParam->hasDefaultArg()) {
John McCall3d6c1782010-05-04 01:53:42 +0000435 // Merge the old default argument into the new parameter.
436 // It's important to use getInit() here; getDefaultArg()
John McCall4765fa02010-12-06 08:20:24 +0000437 // strips off any top-level ExprWithCleanups.
John McCallbf73b352010-03-12 18:31:32 +0000438 NewParam->setHasInheritedDefaultArg();
Douglas Gregord85cef52009-09-17 19:51:30 +0000439 if (OldParam->hasUninstantiatedDefaultArg())
440 NewParam->setUninstantiatedDefaultArg(
441 OldParam->getUninstantiatedDefaultArg());
442 else
John McCall3d6c1782010-05-04 01:53:42 +0000443 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregor6cc15182009-09-11 18:44:32 +0000444 } else if (NewParam->hasDefaultArg()) {
445 if (New->getDescribedFunctionTemplate()) {
446 // Paragraph 4, quoted above, only applies to non-template functions.
447 Diag(NewParam->getLocation(),
448 diag::err_param_default_argument_template_redecl)
449 << NewParam->getDefaultArgRange();
450 Diag(Old->getLocation(), diag::note_template_prev_declaration)
451 << false;
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000452 } else if (New->getTemplateSpecializationKind()
453 != TSK_ImplicitInstantiation &&
454 New->getTemplateSpecializationKind() != TSK_Undeclared) {
455 // C++ [temp.expr.spec]p21:
456 // Default function arguments shall not be specified in a declaration
457 // or a definition for one of the following explicit specializations:
458 // - the explicit specialization of a function template;
Douglas Gregor8c638ab2009-10-13 23:52:38 +0000459 // - the explicit specialization of a member function template;
460 // - the explicit specialization of a member function of a class
Douglas Gregor096ebfd2009-10-13 17:02:54 +0000461 // template where the class template specialization to which the
462 // member function specialization belongs is implicitly
463 // instantiated.
464 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
465 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
466 << New->getDeclName()
467 << NewParam->getDefaultArgRange();
Douglas Gregor6cc15182009-09-11 18:44:32 +0000468 } else if (New->getDeclContext()->isDependentContext()) {
469 // C++ [dcl.fct.default]p6 (DR217):
470 // Default arguments for a member function of a class template shall
471 // be specified on the initial declaration of the member function
472 // within the class template.
473 //
474 // Reading the tea leaves a bit in DR217 and its reference to DR205
475 // leads me to the conclusion that one cannot add default function
476 // arguments for an out-of-line definition of a member function of a
477 // dependent type.
478 int WhichKind = 2;
479 if (CXXRecordDecl *Record
480 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
481 if (Record->getDescribedClassTemplate())
482 WhichKind = 0;
483 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
484 WhichKind = 1;
485 else
486 WhichKind = 2;
487 }
488
489 Diag(NewParam->getLocation(),
490 diag::err_param_default_argument_member_template_redecl)
491 << WhichKind
492 << NewParam->getDefaultArgRange();
Sean Hunt9ae60d52011-05-26 01:26:05 +0000493 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
494 CXXSpecialMember NewSM = getSpecialMember(Ctor),
495 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
496 if (NewSM != OldSM) {
497 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
498 << NewParam->getDefaultArgRange() << NewSM;
499 Diag(Old->getLocation(), diag::note_previous_declaration_special)
500 << OldSM;
501 }
Douglas Gregor6cc15182009-09-11 18:44:32 +0000502 }
Chris Lattner3d1cee32008-04-08 05:04:30 +0000503 }
504 }
505
Richard Smith9f569cc2011-10-01 02:31:28 +0000506 // C++0x [dcl.constexpr]p1: If any declaration of a function or function
507 // template has a constexpr specifier then all its declarations shall
508 // contain the constexpr specifier. [Note: An explicit specialization can
509 // differ from the template declaration with respect to the constexpr
510 // specifier. -- end note]
511 //
512 // FIXME: Don't reject changes in constexpr in explicit specializations.
513 if (New->isConstexpr() != Old->isConstexpr()) {
514 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
515 << New << New->isConstexpr();
516 Diag(Old->getLocation(), diag::note_previous_declaration);
517 Invalid = true;
518 }
519
Douglas Gregore13ad832010-02-12 07:32:17 +0000520 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000521 Invalid = true;
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000522
Douglas Gregorcda9c672009-02-16 17:45:42 +0000523 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000524}
525
Sebastian Redl60618fa2011-03-12 11:50:43 +0000526/// \brief Merge the exception specifications of two variable declarations.
527///
528/// This is called when there's a redeclaration of a VarDecl. The function
529/// checks if the redeclaration might have an exception specification and
530/// validates compatibility and merges the specs if necessary.
531void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
532 // Shortcut if exceptions are disabled.
533 if (!getLangOptions().CXXExceptions)
534 return;
535
536 assert(Context.hasSameType(New->getType(), Old->getType()) &&
537 "Should only be called if types are otherwise the same.");
538
539 QualType NewType = New->getType();
540 QualType OldType = Old->getType();
541
542 // We're only interested in pointers and references to functions, as well
543 // as pointers to member functions.
544 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
545 NewType = R->getPointeeType();
546 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
547 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
548 NewType = P->getPointeeType();
549 OldType = OldType->getAs<PointerType>()->getPointeeType();
550 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
551 NewType = M->getPointeeType();
552 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
553 }
554
555 if (!NewType->isFunctionProtoType())
556 return;
557
558 // There's lots of special cases for functions. For function pointers, system
559 // libraries are hopefully not as broken so that we don't need these
560 // workarounds.
561 if (CheckEquivalentExceptionSpec(
562 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
563 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
564 New->setInvalidDecl();
565 }
566}
567
Chris Lattner3d1cee32008-04-08 05:04:30 +0000568/// CheckCXXDefaultArguments - Verify that the default arguments for a
569/// function declaration are well-formed according to C++
570/// [dcl.fct.default].
571void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
572 unsigned NumParams = FD->getNumParams();
573 unsigned p;
574
575 // Find first parameter with a default argument
576 for (p = 0; p < NumParams; ++p) {
577 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000578 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000579 break;
580 }
581
582 // C++ [dcl.fct.default]p4:
583 // In a given function declaration, all parameters
584 // subsequent to a parameter with a default argument shall
585 // have default arguments supplied in this or previous
586 // declarations. A default argument shall not be redefined
587 // by a later declaration (not even to the same value).
588 unsigned LastMissingDefaultArg = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000589 for (; p < NumParams; ++p) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000590 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000591 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000592 if (Param->isInvalidDecl())
593 /* We already complained about this parameter. */;
594 else if (Param->getIdentifier())
Mike Stump1eb44332009-09-09 15:08:12 +0000595 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000596 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000597 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000598 else
Mike Stump1eb44332009-09-09 15:08:12 +0000599 Diag(Param->getLocation(),
Chris Lattner3d1cee32008-04-08 05:04:30 +0000600 diag::err_param_default_argument_missing);
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Chris Lattner3d1cee32008-04-08 05:04:30 +0000602 LastMissingDefaultArg = p;
603 }
604 }
605
606 if (LastMissingDefaultArg > 0) {
607 // Some default arguments were missing. Clear out all of the
608 // default arguments up to (and including) the last missing
609 // default argument, so that we leave the function parameters
610 // in a semantically valid state.
611 for (p = 0; p <= LastMissingDefaultArg; ++p) {
612 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000613 if (Param->hasDefaultArg()) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000614 Param->setDefaultArg(0);
615 }
616 }
617 }
618}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000619
Richard Smith9f569cc2011-10-01 02:31:28 +0000620// CheckConstexprParameterTypes - Check whether a function's parameter types
621// are all literal types. If so, return true. If not, produce a suitable
622// diagnostic depending on @p CCK and return false.
623static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD,
624 Sema::CheckConstexprKind CCK) {
625 unsigned ArgIndex = 0;
626 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
627 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
628 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
629 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
630 SourceLocation ParamLoc = PD->getLocation();
631 if (!(*i)->isDependentType() &&
632 SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ?
633 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
634 << ArgIndex+1 << PD->getSourceRange()
635 << isa<CXXConstructorDecl>(FD) :
636 SemaRef.PDiag(),
637 /*AllowIncompleteType*/ true)) {
638 if (CCK == Sema::CCK_NoteNonConstexprInstantiation)
639 SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param)
640 << ArgIndex+1 << PD->getSourceRange()
641 << isa<CXXConstructorDecl>(FD) << *i;
642 return false;
643 }
644 }
645 return true;
646}
647
648// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
649// the requirements of a constexpr function declaration or a constexpr
650// constructor declaration. Return true if it does, false if not.
651//
Richard Smith35340502012-01-13 04:54:00 +0000652// This implements C++11 [dcl.constexpr]p3,4, as amended by N3308.
Richard Smith9f569cc2011-10-01 02:31:28 +0000653//
654// \param CCK Specifies whether to produce diagnostics if the function does not
655// satisfy the requirements.
656bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD,
657 CheckConstexprKind CCK) {
658 assert((CCK != CCK_NoteNonConstexprInstantiation ||
659 (NewFD->getTemplateInstantiationPattern() &&
660 NewFD->getTemplateInstantiationPattern()->isConstexpr())) &&
661 "only constexpr templates can be instantiated non-constexpr");
662
Richard Smith35340502012-01-13 04:54:00 +0000663 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
664 if (MD && MD->isInstance()) {
665 // C++11 [dcl.constexpr]p4: In the definition of a constexpr constructor...
Richard Smith9f569cc2011-10-01 02:31:28 +0000666 // In addition, either its function-body shall be = delete or = default or
667 // it shall satisfy the following constraints:
668 // - the class shall not have any virtual base classes;
Richard Smith35340502012-01-13 04:54:00 +0000669 //
670 // We apply this to constexpr member functions too: the class cannot be a
671 // literal type, so the members are not permitted to be constexpr.
672 const CXXRecordDecl *RD = MD->getParent();
Richard Smith9f569cc2011-10-01 02:31:28 +0000673 if (RD->getNumVBases()) {
674 // Note, this is still illegal if the body is = default, since the
675 // implicit body does not satisfy the requirements of a constexpr
676 // constructor. We also reject cases where the body is = delete, as
677 // required by N3308.
678 if (CCK != CCK_Instantiation) {
679 Diag(NewFD->getLocation(),
680 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base
681 : diag::note_constexpr_tmpl_virtual_base)
Richard Smith35340502012-01-13 04:54:00 +0000682 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
683 << RD->getNumVBases();
Richard Smith9f569cc2011-10-01 02:31:28 +0000684 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
685 E = RD->vbases_end(); I != E; ++I)
686 Diag(I->getSourceRange().getBegin(),
687 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
688 }
689 return false;
690 }
Richard Smith35340502012-01-13 04:54:00 +0000691 }
692
693 if (!isa<CXXConstructorDecl>(NewFD)) {
694 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000695 // The definition of a constexpr function shall satisfy the following
696 // constraints:
697 // - it shall not be virtual;
698 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
699 if (Method && Method->isVirtual()) {
700 if (CCK != CCK_Instantiation) {
701 Diag(NewFD->getLocation(),
702 CCK == CCK_Declaration ? diag::err_constexpr_virtual
703 : diag::note_constexpr_tmpl_virtual);
704
705 // If it's not obvious why this function is virtual, find an overridden
706 // function which uses the 'virtual' keyword.
707 const CXXMethodDecl *WrittenVirtual = Method;
708 while (!WrittenVirtual->isVirtualAsWritten())
709 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
710 if (WrittenVirtual != Method)
Richard Smith35340502012-01-13 04:54:00 +0000711 Diag(WrittenVirtual->getLocation(),
Richard Smith9f569cc2011-10-01 02:31:28 +0000712 diag::note_overridden_virtual_function);
713 }
714 return false;
715 }
716
717 // - its return type shall be a literal type;
718 QualType RT = NewFD->getResultType();
719 if (!RT->isDependentType() &&
720 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
721 PDiag(diag::err_constexpr_non_literal_return) :
722 PDiag(),
723 /*AllowIncompleteType*/ true)) {
724 if (CCK == CCK_NoteNonConstexprInstantiation)
725 Diag(NewFD->getLocation(),
726 diag::note_constexpr_tmpl_non_literal_return) << RT;
727 return false;
728 }
Richard Smith9f569cc2011-10-01 02:31:28 +0000729 }
730
Richard Smith35340502012-01-13 04:54:00 +0000731 // - each of its parameter types shall be a literal type;
732 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
733 return false;
734
Richard Smith9f569cc2011-10-01 02:31:28 +0000735 return true;
736}
737
738/// Check the given declaration statement is legal within a constexpr function
739/// body. C++0x [dcl.constexpr]p3,p4.
740///
741/// \return true if the body is OK, false if we have diagnosed a problem.
742static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
743 DeclStmt *DS) {
744 // C++0x [dcl.constexpr]p3 and p4:
745 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
746 // contain only
747 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
748 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
749 switch ((*DclIt)->getKind()) {
750 case Decl::StaticAssert:
751 case Decl::Using:
752 case Decl::UsingShadow:
753 case Decl::UsingDirective:
754 case Decl::UnresolvedUsingTypename:
755 // - static_assert-declarations
756 // - using-declarations,
757 // - using-directives,
758 continue;
759
760 case Decl::Typedef:
761 case Decl::TypeAlias: {
762 // - typedef declarations and alias-declarations that do not define
763 // classes or enumerations,
764 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
765 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
766 // Don't allow variably-modified types in constexpr functions.
767 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
768 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
769 << TL.getSourceRange() << TL.getType()
770 << isa<CXXConstructorDecl>(Dcl);
771 return false;
772 }
773 continue;
774 }
775
776 case Decl::Enum:
777 case Decl::CXXRecord:
778 // As an extension, we allow the declaration (but not the definition) of
779 // classes and enumerations in all declarations, not just in typedef and
780 // alias declarations.
781 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
782 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
783 << isa<CXXConstructorDecl>(Dcl);
784 return false;
785 }
786 continue;
787
788 case Decl::Var:
789 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
790 << isa<CXXConstructorDecl>(Dcl);
791 return false;
792
793 default:
794 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
795 << isa<CXXConstructorDecl>(Dcl);
796 return false;
797 }
798 }
799
800 return true;
801}
802
803/// Check that the given field is initialized within a constexpr constructor.
804///
805/// \param Dcl The constexpr constructor being checked.
806/// \param Field The field being checked. This may be a member of an anonymous
807/// struct or union nested within the class being checked.
808/// \param Inits All declarations, including anonymous struct/union members and
809/// indirect members, for which any initialization was provided.
810/// \param Diagnosed Set to true if an error is produced.
811static void CheckConstexprCtorInitializer(Sema &SemaRef,
812 const FunctionDecl *Dcl,
813 FieldDecl *Field,
814 llvm::SmallSet<Decl*, 16> &Inits,
815 bool &Diagnosed) {
Douglas Gregord61db332011-10-10 17:22:13 +0000816 if (Field->isUnnamedBitfield())
817 return;
818
Richard Smith9f569cc2011-10-01 02:31:28 +0000819 if (!Inits.count(Field)) {
820 if (!Diagnosed) {
821 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
822 Diagnosed = true;
823 }
824 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
825 } else if (Field->isAnonymousStructOrUnion()) {
826 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
827 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
828 I != E; ++I)
829 // If an anonymous union contains an anonymous struct of which any member
830 // is initialized, all members must be initialized.
831 if (!RD->isUnion() || Inits.count(*I))
832 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
833 }
834}
835
836/// Check the body for the given constexpr function declaration only contains
837/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
838///
839/// \return true if the body is OK, false if we have diagnosed a problem.
840bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
841 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000842 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000843 // The definition of a constexpr function shall satisfy the following
844 // constraints: [...]
845 // - its function-body shall be = delete, = default, or a
846 // compound-statement
847 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000848 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000849 // In the definition of a constexpr constructor, [...]
850 // - its function-body shall not be a function-try-block;
851 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
852 << isa<CXXConstructorDecl>(Dcl);
853 return false;
854 }
855
856 // - its function-body shall be [...] a compound-statement that contains only
857 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
858
859 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
860 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
861 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
862 switch ((*BodyIt)->getStmtClass()) {
863 case Stmt::NullStmtClass:
864 // - null statements,
865 continue;
866
867 case Stmt::DeclStmtClass:
868 // - static_assert-declarations
869 // - using-declarations,
870 // - using-directives,
871 // - typedef declarations and alias-declarations that do not define
872 // classes or enumerations,
873 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
874 return false;
875 continue;
876
877 case Stmt::ReturnStmtClass:
878 // - and exactly one return statement;
879 if (isa<CXXConstructorDecl>(Dcl))
880 break;
881
882 ReturnStmts.push_back((*BodyIt)->getLocStart());
883 // FIXME
884 // - every constructor call and implicit conversion used in initializing
885 // the return value shall be one of those allowed in a constant
886 // expression.
887 // Deal with this as part of a general check that the function can produce
888 // a constant expression (for [dcl.constexpr]p5).
889 continue;
890
891 default:
892 break;
893 }
894
895 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
896 << isa<CXXConstructorDecl>(Dcl);
897 return false;
898 }
899
900 if (const CXXConstructorDecl *Constructor
901 = dyn_cast<CXXConstructorDecl>(Dcl)) {
902 const CXXRecordDecl *RD = Constructor->getParent();
903 // - every non-static data member and base class sub-object shall be
904 // initialized;
905 if (RD->isUnion()) {
906 // DR1359: Exactly one member of a union shall be initialized.
907 if (Constructor->getNumCtorInitializers() == 0) {
908 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
909 return false;
910 }
Richard Smith6e433752011-10-10 16:38:04 +0000911 } else if (!Constructor->isDependentContext() &&
912 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000913 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
914
915 // Skip detailed checking if we have enough initializers, and we would
916 // allow at most one initializer per member.
917 bool AnyAnonStructUnionMembers = false;
918 unsigned Fields = 0;
919 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
920 E = RD->field_end(); I != E; ++I, ++Fields) {
921 if ((*I)->isAnonymousStructOrUnion()) {
922 AnyAnonStructUnionMembers = true;
923 break;
924 }
925 }
926 if (AnyAnonStructUnionMembers ||
927 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
928 // Check initialization of non-static data members. Base classes are
929 // always initialized so do not need to be checked. Dependent bases
930 // might not have initializers in the member initializer list.
931 llvm::SmallSet<Decl*, 16> Inits;
932 for (CXXConstructorDecl::init_const_iterator
933 I = Constructor->init_begin(), E = Constructor->init_end();
934 I != E; ++I) {
935 if (FieldDecl *FD = (*I)->getMember())
936 Inits.insert(FD);
937 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
938 Inits.insert(ID->chain_begin(), ID->chain_end());
939 }
940
941 bool Diagnosed = false;
942 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
943 E = RD->field_end(); I != E; ++I)
944 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
945 if (Diagnosed)
946 return false;
947 }
948 }
949
950 // FIXME
951 // - every constructor involved in initializing non-static data members
952 // and base class sub-objects shall be a constexpr constructor;
953 // - every assignment-expression that is an initializer-clause appearing
954 // directly or indirectly within a brace-or-equal-initializer for
955 // a non-static data member that is not named by a mem-initializer-id
956 // shall be a constant expression; and
957 // - every implicit conversion used in converting a constructor argument
958 // to the corresponding parameter type and converting
959 // a full-expression to the corresponding member type shall be one of
960 // those allowed in a constant expression.
961 // Deal with these as part of a general check that the function can produce
962 // a constant expression (for [dcl.constexpr]p5).
963 } else {
964 if (ReturnStmts.empty()) {
965 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
966 return false;
967 }
968 if (ReturnStmts.size() > 1) {
969 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
970 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
971 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
972 return false;
973 }
974 }
975
Richard Smith5ba73e12012-02-04 00:33:54 +0000976 // C++11 [dcl.constexpr]p5:
977 // if no function argument values exist such that the function invocation
978 // substitution would produce a constant expression, the program is
979 // ill-formed; no diagnostic required.
980 // C++11 [dcl.constexpr]p3:
981 // - every constructor call and implicit conversion used in initializing the
982 // return value shall be one of those allowed in a constant expression.
983 // C++11 [dcl.constexpr]p4:
984 // - every constructor involved in initializing non-static data members and
985 // base class sub-objects shall be a constexpr constructor.
986 //
987 // FIXME: We currently disable this check inside system headers, to work
988 // around early STL implementations which contain constexpr functions which
989 // can't produce constant expressions.
Richard Smith745f5142012-01-27 01:14:48 +0000990 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith5ba73e12012-02-04 00:33:54 +0000991 if (!Context.getSourceManager().isInSystemHeader(Dcl->getLocation()) &&
992 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000993 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
994 << isa<CXXConstructorDecl>(Dcl);
995 for (size_t I = 0, N = Diags.size(); I != N; ++I)
996 Diag(Diags[I].first, Diags[I].second);
997 return false;
998 }
999
Richard Smith9f569cc2011-10-01 02:31:28 +00001000 return true;
1001}
1002
Douglas Gregorb48fe382008-10-31 09:07:45 +00001003/// isCurrentClassName - Determine whether the identifier II is the
1004/// name of the class type currently being defined. In the case of
1005/// nested classes, this will only return true if II is the name of
1006/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001007bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1008 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001009 assert(getLangOptions().CPlusPlus && "No class names in C!");
1010
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001011 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001012 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001013 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001014 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1015 } else
1016 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1017
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001018 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001019 return &II == CurDecl->getIdentifier();
1020 else
1021 return false;
1022}
1023
Mike Stump1eb44332009-09-09 15:08:12 +00001024/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001025///
1026/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1027/// and returns NULL otherwise.
1028CXXBaseSpecifier *
1029Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1030 SourceRange SpecifierRange,
1031 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001032 TypeSourceInfo *TInfo,
1033 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001034 QualType BaseType = TInfo->getType();
1035
Douglas Gregor2943aed2009-03-03 04:44:36 +00001036 // C++ [class.union]p1:
1037 // A union shall not have base classes.
1038 if (Class->isUnion()) {
1039 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1040 << SpecifierRange;
1041 return 0;
1042 }
1043
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001044 if (EllipsisLoc.isValid() &&
1045 !TInfo->getType()->containsUnexpandedParameterPack()) {
1046 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1047 << TInfo->getTypeLoc().getSourceRange();
1048 EllipsisLoc = SourceLocation();
1049 }
1050
Douglas Gregor2943aed2009-03-03 04:44:36 +00001051 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001052 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001053 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001054 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001055
1056 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001057
1058 // Base specifiers must be record types.
1059 if (!BaseType->isRecordType()) {
1060 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1061 return 0;
1062 }
1063
1064 // C++ [class.union]p1:
1065 // A union shall not be used as a base class.
1066 if (BaseType->isUnionType()) {
1067 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1068 return 0;
1069 }
1070
1071 // C++ [class.derived]p2:
1072 // The class-name in a base-specifier shall not be an incompletely
1073 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001074 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001075 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001076 << SpecifierRange)) {
1077 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001078 return 0;
John McCall572fc622010-08-17 07:23:57 +00001079 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001080
Eli Friedman1d954f62009-08-15 21:55:26 +00001081 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001082 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001083 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001084 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001085 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001086 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1087 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001088
Anders Carlsson1d209272011-03-25 14:55:14 +00001089 // C++ [class]p3:
1090 // If a class is marked final and it appears as a base-type-specifier in
1091 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001092 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001093 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1094 << CXXBaseDecl->getDeclName();
1095 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1096 << CXXBaseDecl->getDeclName();
1097 return 0;
1098 }
1099
John McCall572fc622010-08-17 07:23:57 +00001100 if (BaseDecl->isInvalidDecl())
1101 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001102
1103 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001104 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001105 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001106 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001107}
1108
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001109/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1110/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001111/// example:
1112/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001113/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001114BaseResult
John McCalld226f652010-08-21 09:40:31 +00001115Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001116 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001117 ParsedType basetype, SourceLocation BaseLoc,
1118 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001119 if (!classdecl)
1120 return true;
1121
Douglas Gregor40808ce2009-03-09 23:48:35 +00001122 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001123 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001124 if (!Class)
1125 return true;
1126
Nick Lewycky56062202010-07-26 16:56:01 +00001127 TypeSourceInfo *TInfo = 0;
1128 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001129
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001130 if (EllipsisLoc.isInvalid() &&
1131 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001132 UPPC_BaseType))
1133 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001134
Douglas Gregor2943aed2009-03-03 04:44:36 +00001135 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001136 Virtual, Access, TInfo,
1137 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001138 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Douglas Gregor2943aed2009-03-03 04:44:36 +00001140 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001141}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001142
Douglas Gregor2943aed2009-03-03 04:44:36 +00001143/// \brief Performs the actual work of attaching the given base class
1144/// specifiers to a C++ class.
1145bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1146 unsigned NumBases) {
1147 if (NumBases == 0)
1148 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001149
1150 // Used to keep track of which base types we have already seen, so
1151 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001152 // that the key is always the unqualified canonical type of the base
1153 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001154 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1155
1156 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001157 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001158 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001159 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001160 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001161 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001162 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001163 if (KnownBaseTypes[NewBaseType]) {
1164 // C++ [class.mi]p3:
1165 // A class shall not be specified as a direct base class of a
1166 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001167 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001168 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +00001169 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001170 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001171
1172 // Delete the duplicate base class specifier; we're going to
1173 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001174 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001175
1176 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001177 } else {
1178 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001179 KnownBaseTypes[NewBaseType] = Bases[idx];
1180 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001181 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001182 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1183 if (RD->hasAttr<WeakAttr>())
1184 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001185 }
1186 }
1187
1188 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001189 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001190
1191 // Delete the remaining (good) base class specifiers, since their
1192 // data has been copied into the CXXRecordDecl.
1193 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001194 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001195
1196 return Invalid;
1197}
1198
1199/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1200/// class, after checking whether there are any duplicate base
1201/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001202void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001203 unsigned NumBases) {
1204 if (!ClassDecl || !Bases || !NumBases)
1205 return;
1206
1207 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001208 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001209 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001210}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001211
John McCall3cb0ebd2010-03-10 03:28:59 +00001212static CXXRecordDecl *GetClassForType(QualType T) {
1213 if (const RecordType *RT = T->getAs<RecordType>())
1214 return cast<CXXRecordDecl>(RT->getDecl());
1215 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1216 return ICT->getDecl();
1217 else
1218 return 0;
1219}
1220
Douglas Gregora8f32e02009-10-06 17:59:45 +00001221/// \brief Determine whether the type \p Derived is a C++ class that is
1222/// derived from the type \p Base.
1223bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1224 if (!getLangOptions().CPlusPlus)
1225 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001226
1227 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1228 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001229 return false;
1230
John McCall3cb0ebd2010-03-10 03:28:59 +00001231 CXXRecordDecl *BaseRD = GetClassForType(Base);
1232 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001233 return false;
1234
John McCall86ff3082010-02-04 22:26:26 +00001235 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1236 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001237}
1238
1239/// \brief Determine whether the type \p Derived is a C++ class that is
1240/// derived from the type \p Base.
1241bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1242 if (!getLangOptions().CPlusPlus)
1243 return false;
1244
John McCall3cb0ebd2010-03-10 03:28:59 +00001245 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1246 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001247 return false;
1248
John McCall3cb0ebd2010-03-10 03:28:59 +00001249 CXXRecordDecl *BaseRD = GetClassForType(Base);
1250 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001251 return false;
1252
Douglas Gregora8f32e02009-10-06 17:59:45 +00001253 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1254}
1255
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001256void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001257 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001258 assert(BasePathArray.empty() && "Base path array must be empty!");
1259 assert(Paths.isRecordingPaths() && "Must record paths!");
1260
1261 const CXXBasePath &Path = Paths.front();
1262
1263 // We first go backward and check if we have a virtual base.
1264 // FIXME: It would be better if CXXBasePath had the base specifier for
1265 // the nearest virtual base.
1266 unsigned Start = 0;
1267 for (unsigned I = Path.size(); I != 0; --I) {
1268 if (Path[I - 1].Base->isVirtual()) {
1269 Start = I - 1;
1270 break;
1271 }
1272 }
1273
1274 // Now add all bases.
1275 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001276 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001277}
1278
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001279/// \brief Determine whether the given base path includes a virtual
1280/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001281bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1282 for (CXXCastPath::const_iterator B = BasePath.begin(),
1283 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001284 B != BEnd; ++B)
1285 if ((*B)->isVirtual())
1286 return true;
1287
1288 return false;
1289}
1290
Douglas Gregora8f32e02009-10-06 17:59:45 +00001291/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1292/// conversion (where Derived and Base are class types) is
1293/// well-formed, meaning that the conversion is unambiguous (and
1294/// that all of the base classes are accessible). Returns true
1295/// and emits a diagnostic if the code is ill-formed, returns false
1296/// otherwise. Loc is the location where this routine should point to
1297/// if there is an error, and Range is the source range to highlight
1298/// if there is an error.
1299bool
1300Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001301 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001302 unsigned AmbigiousBaseConvID,
1303 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001304 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001305 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001306 // First, determine whether the path from Derived to Base is
1307 // ambiguous. This is slightly more expensive than checking whether
1308 // the Derived to Base conversion exists, because here we need to
1309 // explore multiple paths to determine if there is an ambiguity.
1310 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1311 /*DetectVirtual=*/false);
1312 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1313 assert(DerivationOkay &&
1314 "Can only be used with a derived-to-base conversion");
1315 (void)DerivationOkay;
1316
1317 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001318 if (InaccessibleBaseID) {
1319 // Check that the base class can be accessed.
1320 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1321 InaccessibleBaseID)) {
1322 case AR_inaccessible:
1323 return true;
1324 case AR_accessible:
1325 case AR_dependent:
1326 case AR_delayed:
1327 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001328 }
John McCall6b2accb2010-02-10 09:31:12 +00001329 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001330
1331 // Build a base path if necessary.
1332 if (BasePath)
1333 BuildBasePathArray(Paths, *BasePath);
1334 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001335 }
1336
1337 // We know that the derived-to-base conversion is ambiguous, and
1338 // we're going to produce a diagnostic. Perform the derived-to-base
1339 // search just one more time to compute all of the possible paths so
1340 // that we can print them out. This is more expensive than any of
1341 // the previous derived-to-base checks we've done, but at this point
1342 // performance isn't as much of an issue.
1343 Paths.clear();
1344 Paths.setRecordingPaths(true);
1345 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1346 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1347 (void)StillOkay;
1348
1349 // Build up a textual representation of the ambiguous paths, e.g.,
1350 // D -> B -> A, that will be used to illustrate the ambiguous
1351 // conversions in the diagnostic. We only print one of the paths
1352 // to each base class subobject.
1353 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1354
1355 Diag(Loc, AmbigiousBaseConvID)
1356 << Derived << Base << PathDisplayStr << Range << Name;
1357 return true;
1358}
1359
1360bool
1361Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001362 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001363 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001364 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001365 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001366 IgnoreAccess ? 0
1367 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001368 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001369 Loc, Range, DeclarationName(),
1370 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001371}
1372
1373
1374/// @brief Builds a string representing ambiguous paths from a
1375/// specific derived class to different subobjects of the same base
1376/// class.
1377///
1378/// This function builds a string that can be used in error messages
1379/// to show the different paths that one can take through the
1380/// inheritance hierarchy to go from the derived class to different
1381/// subobjects of a base class. The result looks something like this:
1382/// @code
1383/// struct D -> struct B -> struct A
1384/// struct D -> struct C -> struct A
1385/// @endcode
1386std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1387 std::string PathDisplayStr;
1388 std::set<unsigned> DisplayedPaths;
1389 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1390 Path != Paths.end(); ++Path) {
1391 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1392 // We haven't displayed a path to this particular base
1393 // class subobject yet.
1394 PathDisplayStr += "\n ";
1395 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1396 for (CXXBasePath::const_iterator Element = Path->begin();
1397 Element != Path->end(); ++Element)
1398 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1399 }
1400 }
1401
1402 return PathDisplayStr;
1403}
1404
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001405//===----------------------------------------------------------------------===//
1406// C++ class member Handling
1407//===----------------------------------------------------------------------===//
1408
Abramo Bagnara6206d532010-06-05 05:09:32 +00001409/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001410bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1411 SourceLocation ASLoc,
1412 SourceLocation ColonLoc,
1413 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001414 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001415 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001416 ASLoc, ColonLoc);
1417 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001418 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001419}
1420
Anders Carlsson9e682d92011-01-20 05:57:14 +00001421/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001422void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001423 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001424 if (!MD || !MD->isVirtual())
1425 return;
1426
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001427 if (MD->isDependentContext())
1428 return;
1429
Anders Carlsson9e682d92011-01-20 05:57:14 +00001430 // C++0x [class.virtual]p3:
1431 // If a virtual function is marked with the virt-specifier override and does
1432 // not override a member function of a base class,
1433 // the program is ill-formed.
1434 bool HasOverriddenMethods =
1435 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001436 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001437 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001438 diag::err_function_marked_override_not_overriding)
1439 << MD->getDeclName();
1440 return;
1441 }
1442}
1443
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001444/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1445/// function overrides a virtual member function marked 'final', according to
1446/// C++0x [class.virtual]p3.
1447bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1448 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001449 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001450 return false;
1451
1452 Diag(New->getLocation(), diag::err_final_function_overridden)
1453 << New->getDeclName();
1454 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1455 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001456}
1457
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001458/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1459/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001460/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1461/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1462/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001463Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001464Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001465 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001466 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001467 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001468 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001469 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1470 DeclarationName Name = NameInfo.getName();
1471 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001472
1473 // For anonymous bitfields, the location should point to the type.
1474 if (Loc.isInvalid())
1475 Loc = D.getSourceRange().getBegin();
1476
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001477 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001478
John McCall4bde1e12010-06-04 08:34:12 +00001479 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001480 assert(!DS.isFriendSpecified());
1481
Richard Smith1ab0d902011-06-25 02:28:38 +00001482 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001483
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001484 // C++ 9.2p6: A member shall not be declared to have automatic storage
1485 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001486 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1487 // data members and cannot be applied to names declared const or static,
1488 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001489 switch (DS.getStorageClassSpec()) {
1490 case DeclSpec::SCS_unspecified:
1491 case DeclSpec::SCS_typedef:
1492 case DeclSpec::SCS_static:
1493 // FALL THROUGH.
1494 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001495 case DeclSpec::SCS_mutable:
1496 if (isFunc) {
1497 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001498 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001499 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001500 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Sebastian Redla11f42f2008-11-17 23:24:37 +00001502 // FIXME: It would be nicer if the keyword was ignored only for this
1503 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001504 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001505 }
1506 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001507 default:
1508 if (DS.getStorageClassSpecLoc().isValid())
1509 Diag(DS.getStorageClassSpecLoc(),
1510 diag::err_storageclass_invalid_for_member);
1511 else
1512 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1513 D.getMutableDeclSpec().ClearStorageClassSpecs();
1514 }
1515
Sebastian Redl669d5d72008-11-14 23:42:31 +00001516 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1517 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001518 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001519
1520 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001521 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001522 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001523
1524 // Data members must have identifiers for names.
1525 if (Name.getNameKind() != DeclarationName::Identifier) {
1526 Diag(Loc, diag::err_bad_variable_name)
1527 << Name;
1528 return 0;
1529 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001530
Douglas Gregorf2503652011-09-21 14:40:46 +00001531 IdentifierInfo *II = Name.getAsIdentifierInfo();
1532
1533 // Member field could not be with "template" keyword.
1534 // So TemplateParameterLists should be empty in this case.
1535 if (TemplateParameterLists.size()) {
1536 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1537 if (TemplateParams->size()) {
1538 // There is no such thing as a member field template.
1539 Diag(D.getIdentifierLoc(), diag::err_template_member)
1540 << II
1541 << SourceRange(TemplateParams->getTemplateLoc(),
1542 TemplateParams->getRAngleLoc());
1543 } else {
1544 // There is an extraneous 'template<>' for this member.
1545 Diag(TemplateParams->getTemplateLoc(),
1546 diag::err_template_member_noparams)
1547 << II
1548 << SourceRange(TemplateParams->getTemplateLoc(),
1549 TemplateParams->getRAngleLoc());
1550 }
1551 return 0;
1552 }
1553
Douglas Gregor922fff22010-10-13 22:19:53 +00001554 if (SS.isSet() && !SS.isInvalid()) {
1555 // The user provided a superfluous scope specifier inside a class
1556 // definition:
1557 //
1558 // class X {
1559 // int X::member;
1560 // };
1561 DeclContext *DC = 0;
1562 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1563 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001564 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001565 else
1566 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1567 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001568
Douglas Gregor922fff22010-10-13 22:19:53 +00001569 SS.clear();
1570 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001571
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001572 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001573 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001574 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001575 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001576 assert(!HasDeferredInit);
1577
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001578 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001579 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001580 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001581 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001582
1583 // Non-instance-fields can't have a bitfield.
1584 if (BitWidth) {
1585 if (Member->isInvalidDecl()) {
1586 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001587 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001588 // C++ 9.6p3: A bit-field shall not be a static member.
1589 // "static member 'A' cannot be a bit-field"
1590 Diag(Loc, diag::err_static_not_bitfield)
1591 << Name << BitWidth->getSourceRange();
1592 } else if (isa<TypedefDecl>(Member)) {
1593 // "typedef member 'x' cannot be a bit-field"
1594 Diag(Loc, diag::err_typedef_not_bitfield)
1595 << Name << BitWidth->getSourceRange();
1596 } else {
1597 // A function typedef ("typedef int f(); f a;").
1598 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1599 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001600 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001601 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001602 }
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Chris Lattner8b963ef2009-03-05 23:01:03 +00001604 BitWidth = 0;
1605 Member->setInvalidDecl();
1606 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001607
1608 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Douglas Gregor37b372b2009-08-20 22:52:58 +00001610 // If we have declared a member function template, set the access of the
1611 // templated declaration as well.
1612 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1613 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001614 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001615
Anders Carlssonaae5af22011-01-20 04:34:22 +00001616 if (VS.isOverrideSpecified()) {
1617 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1618 if (!MD || !MD->isVirtual()) {
1619 Diag(Member->getLocStart(),
1620 diag::override_keyword_only_allowed_on_virtual_member_functions)
1621 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001622 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001623 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001624 }
1625 if (VS.isFinalSpecified()) {
1626 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1627 if (!MD || !MD->isVirtual()) {
1628 Diag(Member->getLocStart(),
1629 diag::override_keyword_only_allowed_on_virtual_member_functions)
1630 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001631 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001632 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001633 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001634
Douglas Gregorf5251602011-03-08 17:10:18 +00001635 if (VS.getLastLocation().isValid()) {
1636 // Update the end location of a method that has a virt-specifiers.
1637 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1638 MD->setRangeEnd(VS.getLastLocation());
1639 }
1640
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001641 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001642
Douglas Gregor10bd3682008-11-17 22:58:34 +00001643 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001644
John McCallb25b2952011-02-15 07:12:36 +00001645 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001646 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001647 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001648}
1649
Richard Smith7a614d82011-06-11 17:19:42 +00001650/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001651/// in-class initializer for a non-static C++ class member, and after
1652/// instantiating an in-class initializer in a class template. Such actions
1653/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001654void
1655Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1656 Expr *InitExpr) {
1657 FieldDecl *FD = cast<FieldDecl>(D);
1658
1659 if (!InitExpr) {
1660 FD->setInvalidDecl();
1661 FD->removeInClassInitializer();
1662 return;
1663 }
1664
Peter Collingbournefef21892011-10-23 18:59:44 +00001665 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1666 FD->setInvalidDecl();
1667 FD->removeInClassInitializer();
1668 return;
1669 }
1670
Richard Smith7a614d82011-06-11 17:19:42 +00001671 ExprResult Init = InitExpr;
1672 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1673 // FIXME: if there is no EqualLoc, this is list-initialization.
1674 Init = PerformCopyInitialization(
1675 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1676 if (Init.isInvalid()) {
1677 FD->setInvalidDecl();
1678 return;
1679 }
1680
1681 CheckImplicitConversions(Init.get(), EqualLoc);
1682 }
1683
1684 // C++0x [class.base.init]p7:
1685 // The initialization of each base and member constitutes a
1686 // full-expression.
1687 Init = MaybeCreateExprWithCleanups(Init);
1688 if (Init.isInvalid()) {
1689 FD->setInvalidDecl();
1690 return;
1691 }
1692
1693 InitExpr = Init.release();
1694
1695 FD->setInClassInitializer(InitExpr);
1696}
1697
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001698/// \brief Find the direct and/or virtual base specifiers that
1699/// correspond to the given base type, for use in base initialization
1700/// within a constructor.
1701static bool FindBaseInitializer(Sema &SemaRef,
1702 CXXRecordDecl *ClassDecl,
1703 QualType BaseType,
1704 const CXXBaseSpecifier *&DirectBaseSpec,
1705 const CXXBaseSpecifier *&VirtualBaseSpec) {
1706 // First, check for a direct base class.
1707 DirectBaseSpec = 0;
1708 for (CXXRecordDecl::base_class_const_iterator Base
1709 = ClassDecl->bases_begin();
1710 Base != ClassDecl->bases_end(); ++Base) {
1711 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1712 // We found a direct base of this type. That's what we're
1713 // initializing.
1714 DirectBaseSpec = &*Base;
1715 break;
1716 }
1717 }
1718
1719 // Check for a virtual base class.
1720 // FIXME: We might be able to short-circuit this if we know in advance that
1721 // there are no virtual bases.
1722 VirtualBaseSpec = 0;
1723 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1724 // We haven't found a base yet; search the class hierarchy for a
1725 // virtual base class.
1726 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1727 /*DetectVirtual=*/false);
1728 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1729 BaseType, Paths)) {
1730 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1731 Path != Paths.end(); ++Path) {
1732 if (Path->back().Base->isVirtual()) {
1733 VirtualBaseSpec = Path->back().Base;
1734 break;
1735 }
1736 }
1737 }
1738 }
1739
1740 return DirectBaseSpec || VirtualBaseSpec;
1741}
1742
Sebastian Redl6df65482011-09-24 17:48:25 +00001743/// \brief Handle a C++ member initializer using braced-init-list syntax.
1744MemInitResult
1745Sema::ActOnMemInitializer(Decl *ConstructorD,
1746 Scope *S,
1747 CXXScopeSpec &SS,
1748 IdentifierInfo *MemberOrBase,
1749 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001750 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001751 SourceLocation IdLoc,
1752 Expr *InitList,
1753 SourceLocation EllipsisLoc) {
1754 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001755 DS, IdLoc, MultiInitializer(InitList),
1756 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001757}
1758
1759/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001760MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001761Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001762 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001763 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001764 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001765 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001766 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001767 SourceLocation IdLoc,
1768 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001769 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001770 SourceLocation RParenLoc,
1771 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00001772 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001773 DS, IdLoc, MultiInitializer(LParenLoc, Args,
1774 NumArgs, RParenLoc),
Sebastian Redl6df65482011-09-24 17:48:25 +00001775 EllipsisLoc);
1776}
1777
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001778namespace {
1779
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001780// Callback to only accept typo corrections that can be a valid C++ member
1781// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001782class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1783 public:
1784 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1785 : ClassDecl(ClassDecl) {}
1786
1787 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1788 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1789 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1790 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1791 else
1792 return isa<TypeDecl>(ND);
1793 }
1794 return false;
1795 }
1796
1797 private:
1798 CXXRecordDecl *ClassDecl;
1799};
1800
1801}
1802
Sebastian Redl6df65482011-09-24 17:48:25 +00001803/// \brief Handle a C++ member initializer.
1804MemInitResult
1805Sema::BuildMemInitializer(Decl *ConstructorD,
1806 Scope *S,
1807 CXXScopeSpec &SS,
1808 IdentifierInfo *MemberOrBase,
1809 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001810 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001811 SourceLocation IdLoc,
1812 const MultiInitializer &Args,
1813 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001814 if (!ConstructorD)
1815 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001817 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001818
1819 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001820 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001821 if (!Constructor) {
1822 // The user wrote a constructor initializer on a function that is
1823 // not a C++ constructor. Ignore the error for now, because we may
1824 // have more member initializers coming; we'll diagnose it just
1825 // once in ActOnMemInitializers.
1826 return true;
1827 }
1828
1829 CXXRecordDecl *ClassDecl = Constructor->getParent();
1830
1831 // C++ [class.base.init]p2:
1832 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001833 // constructor's class and, if not found in that scope, are looked
1834 // up in the scope containing the constructor's definition.
1835 // [Note: if the constructor's class contains a member with the
1836 // same name as a direct or virtual base class of the class, a
1837 // mem-initializer-id naming the member or base class and composed
1838 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001839 // mem-initializer-id for the hidden base class may be specified
1840 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001841 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001842 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001843 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001844 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001845 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001846 ValueDecl *Member;
1847 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1848 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001849 if (EllipsisLoc.isValid())
1850 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl6df65482011-09-24 17:48:25 +00001851 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1852
1853 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001854 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001855 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001856 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001857 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001858 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001859 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001860
1861 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001862 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001863 } else if (DS.getTypeSpecType() == TST_decltype) {
1864 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001865 } else {
1866 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1867 LookupParsedName(R, S, &SS);
1868
1869 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1870 if (!TyD) {
1871 if (R.isAmbiguous()) return true;
1872
John McCallfd225442010-04-09 19:01:14 +00001873 // We don't want access-control diagnostics here.
1874 R.suppressDiagnostics();
1875
Douglas Gregor7a886e12010-01-19 06:46:48 +00001876 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1877 bool NotUnknownSpecialization = false;
1878 DeclContext *DC = computeDeclContext(SS, false);
1879 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1880 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1881
1882 if (!NotUnknownSpecialization) {
1883 // When the scope specifier can refer to a member of an unknown
1884 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001885 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1886 SS.getWithLocInContext(Context),
1887 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001888 if (BaseType.isNull())
1889 return true;
1890
Douglas Gregor7a886e12010-01-19 06:46:48 +00001891 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001892 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001893 }
1894 }
1895
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001896 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001897 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001898 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001899 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001900 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001901 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001902 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1903 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1904 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001905 // We have found a non-static data member with a similar
1906 // name to what was typed; complain and initialize that
1907 // member.
1908 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1909 << MemberOrBase << true << CorrectedQuotedStr
1910 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1911 Diag(Member->getLocation(), diag::note_previous_decl)
1912 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001913
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001914 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001915 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001916 const CXXBaseSpecifier *DirectBaseSpec;
1917 const CXXBaseSpecifier *VirtualBaseSpec;
1918 if (FindBaseInitializer(*this, ClassDecl,
1919 Context.getTypeDeclType(Type),
1920 DirectBaseSpec, VirtualBaseSpec)) {
1921 // We have found a direct or virtual base class with a
1922 // similar name to what was typed; complain and initialize
1923 // that base class.
1924 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001925 << MemberOrBase << false << CorrectedQuotedStr
1926 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001927
1928 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1929 : VirtualBaseSpec;
1930 Diag(BaseSpec->getSourceRange().getBegin(),
1931 diag::note_base_class_specified_here)
1932 << BaseSpec->getType()
1933 << BaseSpec->getSourceRange();
1934
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001935 TyD = Type;
1936 }
1937 }
1938 }
1939
Douglas Gregor7a886e12010-01-19 06:46:48 +00001940 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001941 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl6df65482011-09-24 17:48:25 +00001942 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001943 return true;
1944 }
John McCall2b194412009-12-21 10:41:20 +00001945 }
1946
Douglas Gregor7a886e12010-01-19 06:46:48 +00001947 if (BaseType.isNull()) {
1948 BaseType = Context.getTypeDeclType(TyD);
1949 if (SS.isSet()) {
1950 NestedNameSpecifier *Qualifier =
1951 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001952
Douglas Gregor7a886e12010-01-19 06:46:48 +00001953 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001954 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001955 }
John McCall2b194412009-12-21 10:41:20 +00001956 }
1957 }
Mike Stump1eb44332009-09-09 15:08:12 +00001958
John McCalla93c9342009-12-07 02:54:59 +00001959 if (!TInfo)
1960 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001961
Sebastian Redl6df65482011-09-24 17:48:25 +00001962 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001963}
1964
Chandler Carruth81c64772011-09-03 01:14:15 +00001965/// Checks a member initializer expression for cases where reference (or
1966/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001967static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1968 Expr *Init,
1969 SourceLocation IdLoc) {
1970 QualType MemberTy = Member->getType();
1971
1972 // We only handle pointers and references currently.
1973 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1974 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1975 return;
1976
1977 const bool IsPointer = MemberTy->isPointerType();
1978 if (IsPointer) {
1979 if (const UnaryOperator *Op
1980 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1981 // The only case we're worried about with pointers requires taking the
1982 // address.
1983 if (Op->getOpcode() != UO_AddrOf)
1984 return;
1985
1986 Init = Op->getSubExpr();
1987 } else {
1988 // We only handle address-of expression initializers for pointers.
1989 return;
1990 }
1991 }
1992
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001993 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1994 // Taking the address of a temporary will be diagnosed as a hard error.
1995 if (IsPointer)
1996 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001997
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001998 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1999 << Member << Init->getSourceRange();
2000 } else if (const DeclRefExpr *DRE
2001 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2002 // We only warn when referring to a non-reference parameter declaration.
2003 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2004 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002005 return;
2006
2007 S.Diag(Init->getExprLoc(),
2008 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2009 : diag::warn_bind_ref_member_to_parameter)
2010 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002011 } else {
2012 // Other initializers are fine.
2013 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002014 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002015
2016 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2017 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002018}
2019
John McCallb4190042009-11-04 23:02:40 +00002020/// Checks an initializer expression for use of uninitialized fields, such as
2021/// containing the field that is being initialized. Returns true if there is an
2022/// uninitialized field was used an updates the SourceLocation parameter; false
2023/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002024static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002025 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002026 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002027 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2028
Nick Lewycky43ad1822010-06-15 07:32:55 +00002029 if (isa<CallExpr>(S)) {
2030 // Do not descend into function calls or constructors, as the use
2031 // of an uninitialized field may be valid. One would have to inspect
2032 // the contents of the function/ctor to determine if it is safe or not.
2033 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2034 // may be safe, depending on what the function/ctor does.
2035 return false;
2036 }
2037 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2038 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002039
2040 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2041 // The member expression points to a static data member.
2042 assert(VD->isStaticDataMember() &&
2043 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002044 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002045 return false;
2046 }
2047
2048 if (isa<EnumConstantDecl>(RhsField)) {
2049 // The member expression points to an enum.
2050 return false;
2051 }
2052
John McCallb4190042009-11-04 23:02:40 +00002053 if (RhsField == LhsField) {
2054 // Initializing a field with itself. Throw a warning.
2055 // But wait; there are exceptions!
2056 // Exception #1: The field may not belong to this record.
2057 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002058 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002059 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2060 // Even though the field matches, it does not belong to this record.
2061 return false;
2062 }
2063 // None of the exceptions triggered; return true to indicate an
2064 // uninitialized field was used.
2065 *L = ME->getMemberLoc();
2066 return true;
2067 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002068 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002069 // sizeof/alignof doesn't reference contents, do not warn.
2070 return false;
2071 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2072 // address-of doesn't reference contents (the pointer may be dereferenced
2073 // in the same expression but it would be rare; and weird).
2074 if (UOE->getOpcode() == UO_AddrOf)
2075 return false;
John McCallb4190042009-11-04 23:02:40 +00002076 }
John McCall7502c1d2011-02-13 04:07:26 +00002077 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002078 if (!*it) {
2079 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002080 continue;
2081 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002082 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2083 return true;
John McCallb4190042009-11-04 23:02:40 +00002084 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002085 return false;
John McCallb4190042009-11-04 23:02:40 +00002086}
2087
John McCallf312b1e2010-08-26 23:41:50 +00002088MemInitResult
Sebastian Redl6df65482011-09-24 17:48:25 +00002089Sema::BuildMemberInitializer(ValueDecl *Member,
2090 const MultiInitializer &Args,
2091 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002092 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2093 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2094 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002095 "Member must be a FieldDecl or IndirectFieldDecl");
2096
Peter Collingbournefef21892011-10-23 18:59:44 +00002097 if (Args.DiagnoseUnexpandedParameterPack(*this))
2098 return true;
2099
Douglas Gregor464b2f02010-11-05 22:21:31 +00002100 if (Member->isInvalidDecl())
2101 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002102
John McCallb4190042009-11-04 23:02:40 +00002103 // Diagnose value-uses of fields to initialize themselves, e.g.
2104 // foo(foo)
2105 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002106 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl6df65482011-09-24 17:48:25 +00002107 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2108 I != E; ++I) {
John McCallb4190042009-11-04 23:02:40 +00002109 SourceLocation L;
Sebastian Redl6df65482011-09-24 17:48:25 +00002110 Expr *Arg = *I;
2111 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2112 Arg = DIE->getInit();
2113 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002114 // FIXME: Return true in the case when other fields are used before being
2115 // uninitialized. For example, let this field be the i'th field. When
2116 // initializing the i'th field, throw a warning if any of the >= i'th
2117 // fields are used, as they are not yet initialized.
2118 // Right now we are only handling the case where the i'th field uses
2119 // itself in its initializer.
2120 Diag(L, diag::warn_field_is_uninit);
2121 }
2122 }
2123
Sebastian Redl6df65482011-09-24 17:48:25 +00002124 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002125
Chandler Carruth894aed92010-12-06 09:23:57 +00002126 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00002127 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002128 // Can't check initialization for a member of dependent type or when
2129 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002130 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002131
John McCallf85e1932011-06-15 23:02:42 +00002132 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002133 } else {
2134 // Initialize the member.
2135 InitializedEntity MemberEntity =
2136 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2137 : InitializedEntity::InitializeMember(IndirectMember, 0);
2138 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002139 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2140 Args.getEndLoc());
John McCallb4eb64d2010-10-08 02:01:28 +00002141
Sebastian Redl6df65482011-09-24 17:48:25 +00002142 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruth894aed92010-12-06 09:23:57 +00002143 if (MemberInit.isInvalid())
2144 return true;
2145
Sebastian Redl6df65482011-09-24 17:48:25 +00002146 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002147
2148 // C++0x [class.base.init]p7:
2149 // The initialization of each base and member constitutes a
2150 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002151 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002152 if (MemberInit.isInvalid())
2153 return true;
2154
2155 // If we are in a dependent context, template instantiation will
2156 // perform this type-checking again. Just save the arguments that we
2157 // received in a ParenListExpr.
2158 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2159 // of the information that we have about the member
2160 // initializer. However, deconstructing the ASTs is a dicey process,
2161 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002162 if (CurContext->isDependentContext()) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002163 Init = Args.CreateInitExpr(Context,
2164 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00002165 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002166 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002167 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2168 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002169 }
2170
Chandler Carruth894aed92010-12-06 09:23:57 +00002171 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00002172 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002173 IdLoc, Args.getStartLoc(),
2174 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002175 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00002176 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002177 IdLoc, Args.getStartLoc(),
2178 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002179 }
Eli Friedman59c04372009-07-29 19:44:27 +00002180}
2181
John McCallf312b1e2010-08-26 23:41:50 +00002182MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00002183Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002184 const MultiInitializer &Args,
Sean Hunt41717662011-02-26 19:13:13 +00002185 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002186 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002187 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002188 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002189 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002190 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002191
Sean Hunt41717662011-02-26 19:13:13 +00002192 // Initialize the object.
2193 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2194 QualType(ClassDecl->getTypeForDecl(), 0));
2195 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002196 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2197 Args.getEndLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002198
Sebastian Redl6df65482011-09-24 17:48:25 +00002199 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Sean Hunt41717662011-02-26 19:13:13 +00002200 if (DelegationInit.isInvalid())
2201 return true;
2202
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002203 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2204 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002205
Sebastian Redl6df65482011-09-24 17:48:25 +00002206 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002207
2208 // C++0x [class.base.init]p7:
2209 // The initialization of each base and member constitutes a
2210 // full-expression.
2211 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2212 if (DelegationInit.isInvalid())
2213 return true;
2214
Douglas Gregor76852c22011-11-01 01:16:03 +00002215 return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
Sean Hunt41717662011-02-26 19:13:13 +00002216 DelegationInit.takeAs<Expr>(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002217 Args.getEndLoc());
Sean Hunt97fcc492011-01-08 19:20:43 +00002218}
2219
2220MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002221Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002222 const MultiInitializer &Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002223 CXXRecordDecl *ClassDecl,
2224 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002225 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002226
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002227 SourceLocation BaseLoc
2228 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002229
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002230 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2231 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2232 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2233
2234 // C++ [class.base.init]p2:
2235 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002236 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002237 // of that class, the mem-initializer is ill-formed. A
2238 // mem-initializer-list can initialize a base class using any
2239 // name that denotes that base class type.
2240 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2241
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002242 if (EllipsisLoc.isValid()) {
2243 // This is a pack expansion.
2244 if (!BaseType->containsUnexpandedParameterPack()) {
2245 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl6df65482011-09-24 17:48:25 +00002246 << SourceRange(BaseLoc, Args.getEndLoc());
2247
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002248 EllipsisLoc = SourceLocation();
2249 }
2250 } else {
2251 // Check for any unexpanded parameter packs.
2252 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2253 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002254
2255 if (Args.DiagnoseUnexpandedParameterPack(*this))
2256 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002257 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002258
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002259 // Check for direct and virtual base classes.
2260 const CXXBaseSpecifier *DirectBaseSpec = 0;
2261 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2262 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002263 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2264 BaseType))
Douglas Gregor76852c22011-11-01 01:16:03 +00002265 return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002266
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002267 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2268 VirtualBaseSpec);
2269
2270 // C++ [base.class.init]p2:
2271 // Unless the mem-initializer-id names a nonstatic data member of the
2272 // constructor's class or a direct or virtual base of that class, the
2273 // mem-initializer is ill-formed.
2274 if (!DirectBaseSpec && !VirtualBaseSpec) {
2275 // If the class has any dependent bases, then it's possible that
2276 // one of those types will resolve to the same type as
2277 // BaseType. Therefore, just treat this as a dependent base
2278 // class initialization. FIXME: Should we try to check the
2279 // initialization anyway? It seems odd.
2280 if (ClassDecl->hasAnyDependentBases())
2281 Dependent = true;
2282 else
2283 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2284 << BaseType << Context.getTypeDeclType(ClassDecl)
2285 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2286 }
2287 }
2288
2289 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002290 // Can't check initialization for a base of dependent type or when
2291 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002292 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman59c04372009-07-29 19:44:27 +00002293
John McCallf85e1932011-06-15 23:02:42 +00002294 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Sebastian Redl6df65482011-09-24 17:48:25 +00002296 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2297 /*IsVirtual=*/false,
2298 Args.getStartLoc(), BaseInit,
2299 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002300 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002301
2302 // C++ [base.class.init]p2:
2303 // If a mem-initializer-id is ambiguous because it designates both
2304 // a direct non-virtual base class and an inherited virtual base
2305 // class, the mem-initializer is ill-formed.
2306 if (DirectBaseSpec && VirtualBaseSpec)
2307 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002308 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002309
2310 CXXBaseSpecifier *BaseSpec
2311 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2312 if (!BaseSpec)
2313 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2314
2315 // Initialize the base.
2316 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00002317 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002318 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002319 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2320 Args.getEndLoc());
2321
2322 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002323 if (BaseInit.isInvalid())
2324 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002325
Sebastian Redl6df65482011-09-24 17:48:25 +00002326 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2327
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002328 // C++0x [class.base.init]p7:
2329 // The initialization of each base and member constitutes a
2330 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002331 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002332 if (BaseInit.isInvalid())
2333 return true;
2334
2335 // If we are in a dependent context, template instantiation will
2336 // perform this type-checking again. Just save the arguments that we
2337 // received in a ParenListExpr.
2338 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2339 // of the information that we have about the base
2340 // initializer. However, deconstructing the ASTs is a dicey process,
2341 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002342 if (CurContext->isDependentContext())
2343 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002344
Sean Huntcbb67482011-01-08 20:30:50 +00002345 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002346 BaseSpec->isVirtual(),
2347 Args.getStartLoc(),
2348 BaseInit.takeAs<Expr>(),
2349 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002350}
2351
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002352// Create a static_cast\<T&&>(expr).
2353static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2354 QualType ExprType = E->getType();
2355 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2356 SourceLocation ExprLoc = E->getLocStart();
2357 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2358 TargetType, ExprLoc);
2359
2360 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2361 SourceRange(ExprLoc, ExprLoc),
2362 E->getSourceRange()).take();
2363}
2364
Anders Carlssone5ef7402010-04-23 03:10:23 +00002365/// ImplicitInitializerKind - How an implicit base or member initializer should
2366/// initialize its base or member.
2367enum ImplicitInitializerKind {
2368 IIK_Default,
2369 IIK_Copy,
2370 IIK_Move
2371};
2372
Anders Carlssondefefd22010-04-23 02:00:02 +00002373static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002374BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002375 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002376 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002377 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002378 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002379 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002380 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2381 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002382
John McCall60d7b3a2010-08-24 06:29:42 +00002383 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002384
2385 switch (ImplicitInitKind) {
2386 case IIK_Default: {
2387 InitializationKind InitKind
2388 = InitializationKind::CreateDefault(Constructor->getLocation());
2389 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2390 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002391 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002392 break;
2393 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002394
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002395 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002396 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002397 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002398 ParmVarDecl *Param = Constructor->getParamDecl(0);
2399 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002400
Anders Carlssone5ef7402010-04-23 03:10:23 +00002401 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002402 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2403 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002404 Constructor->getLocation(), ParamType,
2405 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002406
Eli Friedman5f2987c2012-02-02 03:46:19 +00002407 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2408
Anders Carlssonc7957502010-04-24 22:02:54 +00002409 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002410 QualType ArgTy =
2411 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2412 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002413
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002414 if (Moving) {
2415 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2416 }
2417
John McCallf871d0c2010-08-07 06:22:56 +00002418 CXXCastPath BasePath;
2419 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002420 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2421 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002422 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002423 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002424
Anders Carlssone5ef7402010-04-23 03:10:23 +00002425 InitializationKind InitKind
2426 = InitializationKind::CreateDirect(Constructor->getLocation(),
2427 SourceLocation(), SourceLocation());
2428 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2429 &CopyCtorArg, 1);
2430 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002431 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002432 break;
2433 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002434 }
John McCall9ae2f072010-08-23 23:25:46 +00002435
Douglas Gregor53c374f2010-12-07 00:41:46 +00002436 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002437 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002438 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002439
Anders Carlssondefefd22010-04-23 02:00:02 +00002440 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002441 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002442 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2443 SourceLocation()),
2444 BaseSpec->isVirtual(),
2445 SourceLocation(),
2446 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002447 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002448 SourceLocation());
2449
Anders Carlssondefefd22010-04-23 02:00:02 +00002450 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002451}
2452
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002453static bool RefersToRValueRef(Expr *MemRef) {
2454 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2455 return Referenced->getType()->isRValueReferenceType();
2456}
2457
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002458static bool
2459BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002460 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002461 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002462 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002463 if (Field->isInvalidDecl())
2464 return true;
2465
Chandler Carruthf186b542010-06-29 23:50:44 +00002466 SourceLocation Loc = Constructor->getLocation();
2467
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002468 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2469 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002470 ParmVarDecl *Param = Constructor->getParamDecl(0);
2471 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002472
2473 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002474 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2475 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002476
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002477 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002478 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2479 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002480 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002481
Eli Friedman5f2987c2012-02-02 03:46:19 +00002482 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2483
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002484 if (Moving) {
2485 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2486 }
2487
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002488 // Build a reference to this field within the parameter.
2489 CXXScopeSpec SS;
2490 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2491 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002492 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2493 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002494 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002495 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002496 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002497 ParamType, Loc,
2498 /*IsArrow=*/false,
2499 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002500 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002501 /*FirstQualifierInScope=*/0,
2502 MemberLookup,
2503 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002504 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002505 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002506
2507 // C++11 [class.copy]p15:
2508 // - if a member m has rvalue reference type T&&, it is direct-initialized
2509 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002510 if (RefersToRValueRef(CtorArg.get())) {
2511 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002512 }
2513
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002514 // When the field we are copying is an array, create index variables for
2515 // each dimension of the array. We use these index variables to subscript
2516 // the source array, and other clients (e.g., CodeGen) will perform the
2517 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002518 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002519 QualType BaseType = Field->getType();
2520 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002521 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002522 while (const ConstantArrayType *Array
2523 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002524 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002525 // Create the iteration variable for this array index.
2526 IdentifierInfo *IterationVarName = 0;
2527 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002528 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002529 llvm::raw_svector_ostream OS(Str);
2530 OS << "__i" << IndexVariables.size();
2531 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2532 }
2533 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002534 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002535 IterationVarName, SizeType,
2536 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002537 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002538 IndexVariables.push_back(IterationVar);
2539
2540 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002541 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002542 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002543 assert(!IterationVarRef.isInvalid() &&
2544 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002545 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2546 assert(!IterationVarRef.isInvalid() &&
2547 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002548
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002549 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002550 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002551 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002552 Loc);
2553 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002554 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002555
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002556 BaseType = Array->getElementType();
2557 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002558
2559 // The array subscript expression is an lvalue, which is wrong for moving.
2560 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002561 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002562
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002563 // Construct the entity that we will be initializing. For an array, this
2564 // will be first element in the array, which may require several levels
2565 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002566 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002567 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002568 if (Indirect)
2569 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2570 else
2571 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002572 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2573 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2574 0,
2575 Entities.back()));
2576
2577 // Direct-initialize to use the copy constructor.
2578 InitializationKind InitKind =
2579 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2580
Sebastian Redl74e611a2011-09-04 18:14:28 +00002581 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002582 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002583 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002584
John McCall60d7b3a2010-08-24 06:29:42 +00002585 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002586 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002587 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002588 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002589 if (MemberInit.isInvalid())
2590 return true;
2591
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002592 if (Indirect) {
2593 assert(IndexVariables.size() == 0 &&
2594 "Indirect field improperly initialized");
2595 CXXMemberInit
2596 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2597 Loc, Loc,
2598 MemberInit.takeAs<Expr>(),
2599 Loc);
2600 } else
2601 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2602 Loc, MemberInit.takeAs<Expr>(),
2603 Loc,
2604 IndexVariables.data(),
2605 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002606 return false;
2607 }
2608
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002609 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2610
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002611 QualType FieldBaseElementType =
2612 SemaRef.Context.getBaseElementType(Field->getType());
2613
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002614 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002615 InitializedEntity InitEntity
2616 = Indirect? InitializedEntity::InitializeMember(Indirect)
2617 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002618 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002619 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002620
2621 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002622 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002623 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002624
Douglas Gregor53c374f2010-12-07 00:41:46 +00002625 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002626 if (MemberInit.isInvalid())
2627 return true;
2628
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002629 if (Indirect)
2630 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2631 Indirect, Loc,
2632 Loc,
2633 MemberInit.get(),
2634 Loc);
2635 else
2636 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2637 Field, Loc, Loc,
2638 MemberInit.get(),
2639 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002640 return false;
2641 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002642
Sean Hunt1f2f3842011-05-17 00:19:05 +00002643 if (!Field->getParent()->isUnion()) {
2644 if (FieldBaseElementType->isReferenceType()) {
2645 SemaRef.Diag(Constructor->getLocation(),
2646 diag::err_uninitialized_member_in_ctor)
2647 << (int)Constructor->isImplicit()
2648 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2649 << 0 << Field->getDeclName();
2650 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2651 return true;
2652 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002653
Sean Hunt1f2f3842011-05-17 00:19:05 +00002654 if (FieldBaseElementType.isConstQualified()) {
2655 SemaRef.Diag(Constructor->getLocation(),
2656 diag::err_uninitialized_member_in_ctor)
2657 << (int)Constructor->isImplicit()
2658 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2659 << 1 << Field->getDeclName();
2660 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2661 return true;
2662 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002663 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002664
John McCallf85e1932011-06-15 23:02:42 +00002665 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2666 FieldBaseElementType->isObjCRetainableType() &&
2667 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2668 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2669 // Instant objects:
2670 // Default-initialize Objective-C pointers to NULL.
2671 CXXMemberInit
2672 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2673 Loc, Loc,
2674 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2675 Loc);
2676 return false;
2677 }
2678
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002679 // Nothing to initialize.
2680 CXXMemberInit = 0;
2681 return false;
2682}
John McCallf1860e52010-05-20 23:23:51 +00002683
2684namespace {
2685struct BaseAndFieldInfo {
2686 Sema &S;
2687 CXXConstructorDecl *Ctor;
2688 bool AnyErrorsInInits;
2689 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002690 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002691 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002692
2693 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2694 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002695 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2696 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002697 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002698 else if (Generated && Ctor->isMoveConstructor())
2699 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002700 else
2701 IIK = IIK_Default;
2702 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002703
2704 bool isImplicitCopyOrMove() const {
2705 switch (IIK) {
2706 case IIK_Copy:
2707 case IIK_Move:
2708 return true;
2709
2710 case IIK_Default:
2711 return false;
2712 }
David Blaikie30263482012-01-20 21:50:17 +00002713
2714 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002715 }
John McCallf1860e52010-05-20 23:23:51 +00002716};
2717}
2718
Richard Smitha4950662011-09-19 13:34:43 +00002719/// \brief Determine whether the given indirect field declaration is somewhere
2720/// within an anonymous union.
2721static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2722 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2723 CEnd = F->chain_end();
2724 C != CEnd; ++C)
2725 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2726 if (Record->isUnion())
2727 return true;
2728
2729 return false;
2730}
2731
Douglas Gregorddb21472011-11-02 23:04:16 +00002732/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2733/// array type.
2734static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2735 if (T->isIncompleteArrayType())
2736 return true;
2737
2738 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2739 if (!ArrayT->getSize())
2740 return true;
2741
2742 T = ArrayT->getElementType();
2743 }
2744
2745 return false;
2746}
2747
Richard Smith7a614d82011-06-11 17:19:42 +00002748static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002749 FieldDecl *Field,
2750 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002751
Chandler Carruthe861c602010-06-30 02:59:29 +00002752 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002753 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002754 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002755 return false;
2756 }
2757
Richard Smith7a614d82011-06-11 17:19:42 +00002758 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2759 // has a brace-or-equal-initializer, the entity is initialized as specified
2760 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002761 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002762 CXXCtorInitializer *Init;
2763 if (Indirect)
2764 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2765 SourceLocation(),
2766 SourceLocation(), 0,
2767 SourceLocation());
2768 else
2769 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2770 SourceLocation(),
2771 SourceLocation(), 0,
2772 SourceLocation());
2773 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002774 return false;
2775 }
2776
Richard Smithc115f632011-09-18 11:14:50 +00002777 // Don't build an implicit initializer for union members if none was
2778 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002779 if (Field->getParent()->isUnion() ||
2780 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002781 return false;
2782
Douglas Gregorddb21472011-11-02 23:04:16 +00002783 // Don't initialize incomplete or zero-length arrays.
2784 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2785 return false;
2786
John McCallf1860e52010-05-20 23:23:51 +00002787 // Don't try to build an implicit initializer if there were semantic
2788 // errors in any of the initializers (and therefore we might be
2789 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002790 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002791 return false;
2792
Sean Huntcbb67482011-01-08 20:30:50 +00002793 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002794 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2795 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002796 return true;
John McCallf1860e52010-05-20 23:23:51 +00002797
Francois Pichet00eb3f92010-12-04 09:14:42 +00002798 if (Init)
2799 Info.AllToInit.push_back(Init);
2800
John McCallf1860e52010-05-20 23:23:51 +00002801 return false;
2802}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002803
2804bool
2805Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2806 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002807 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002808 Constructor->setNumCtorInitializers(1);
2809 CXXCtorInitializer **initializer =
2810 new (Context) CXXCtorInitializer*[1];
2811 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2812 Constructor->setCtorInitializers(initializer);
2813
Sean Huntb76af9c2011-05-03 23:05:34 +00002814 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002815 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002816 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2817 }
2818
Sean Huntc1598702011-05-05 00:05:47 +00002819 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002820
Sean Hunt059ce0d2011-05-01 07:04:31 +00002821 return false;
2822}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002823
John McCallb77115d2011-06-17 00:18:42 +00002824bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2825 CXXCtorInitializer **Initializers,
2826 unsigned NumInitializers,
2827 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002828 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002829 // Just store the initializers as written, they will be checked during
2830 // instantiation.
2831 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002832 Constructor->setNumCtorInitializers(NumInitializers);
2833 CXXCtorInitializer **baseOrMemberInitializers =
2834 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002835 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002836 NumInitializers * sizeof(CXXCtorInitializer*));
2837 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002838 }
2839
2840 return false;
2841 }
2842
John McCallf1860e52010-05-20 23:23:51 +00002843 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002844
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002845 // We need to build the initializer AST according to order of construction
2846 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002847 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002848 if (!ClassDecl)
2849 return true;
2850
Eli Friedman80c30da2009-11-09 19:20:36 +00002851 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002852
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002853 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002854 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002855
2856 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002857 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002858 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002859 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002860 }
2861
Anders Carlsson711f34a2010-04-21 19:52:01 +00002862 // Keep track of the direct virtual bases.
2863 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2864 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2865 E = ClassDecl->bases_end(); I != E; ++I) {
2866 if (I->isVirtual())
2867 DirectVBases.insert(I);
2868 }
2869
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002870 // Push virtual bases before others.
2871 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2872 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2873
Sean Huntcbb67482011-01-08 20:30:50 +00002874 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002875 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2876 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002877 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002878 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002879 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002880 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002881 VBase, IsInheritedVirtualBase,
2882 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002883 HadError = true;
2884 continue;
2885 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002886
John McCallf1860e52010-05-20 23:23:51 +00002887 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002888 }
2889 }
Mike Stump1eb44332009-09-09 15:08:12 +00002890
John McCallf1860e52010-05-20 23:23:51 +00002891 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002892 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2893 E = ClassDecl->bases_end(); Base != E; ++Base) {
2894 // Virtuals are in the virtual base list and already constructed.
2895 if (Base->isVirtual())
2896 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002897
Sean Huntcbb67482011-01-08 20:30:50 +00002898 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002899 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2900 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002901 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002902 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002903 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002904 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002905 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002906 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002907 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002908 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002909
John McCallf1860e52010-05-20 23:23:51 +00002910 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002911 }
2912 }
Mike Stump1eb44332009-09-09 15:08:12 +00002913
John McCallf1860e52010-05-20 23:23:51 +00002914 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002915 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2916 MemEnd = ClassDecl->decls_end();
2917 Mem != MemEnd; ++Mem) {
2918 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002919 // C++ [class.bit]p2:
2920 // A declaration for a bit-field that omits the identifier declares an
2921 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2922 // initialized.
2923 if (F->isUnnamedBitfield())
2924 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002925
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002926 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002927 // handle anonymous struct/union fields based on their individual
2928 // indirect fields.
2929 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2930 continue;
2931
2932 if (CollectFieldInitializer(*this, Info, F))
2933 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002934 continue;
2935 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002936
2937 // Beyond this point, we only consider default initialization.
2938 if (Info.IIK != IIK_Default)
2939 continue;
2940
2941 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2942 if (F->getType()->isIncompleteArrayType()) {
2943 assert(ClassDecl->hasFlexibleArrayMember() &&
2944 "Incomplete array type is not valid");
2945 continue;
2946 }
2947
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002948 // Initialize each field of an anonymous struct individually.
2949 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2950 HadError = true;
2951
2952 continue;
2953 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002954 }
Mike Stump1eb44332009-09-09 15:08:12 +00002955
John McCallf1860e52010-05-20 23:23:51 +00002956 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002957 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002958 Constructor->setNumCtorInitializers(NumInitializers);
2959 CXXCtorInitializer **baseOrMemberInitializers =
2960 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002961 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002962 NumInitializers * sizeof(CXXCtorInitializer*));
2963 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002964
John McCallef027fe2010-03-16 21:39:52 +00002965 // Constructors implicitly reference the base and member
2966 // destructors.
2967 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2968 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002969 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002970
2971 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002972}
2973
Eli Friedman6347f422009-07-21 19:28:10 +00002974static void *GetKeyForTopLevelField(FieldDecl *Field) {
2975 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002976 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002977 if (RT->getDecl()->isAnonymousStructOrUnion())
2978 return static_cast<void *>(RT->getDecl());
2979 }
2980 return static_cast<void *>(Field);
2981}
2982
Anders Carlssonea356fb2010-04-02 05:42:15 +00002983static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002984 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002985}
2986
Anders Carlssonea356fb2010-04-02 05:42:15 +00002987static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002988 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002989 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002990 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002991
Eli Friedman6347f422009-07-21 19:28:10 +00002992 // For fields injected into the class via declaration of an anonymous union,
2993 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002994 FieldDecl *Field = Member->getAnyMember();
2995
John McCall3c3ccdb2010-04-10 09:28:51 +00002996 // If the field is a member of an anonymous struct or union, our key
2997 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002998 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002999 if (RD->isAnonymousStructOrUnion()) {
3000 while (true) {
3001 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3002 if (Parent->isAnonymousStructOrUnion())
3003 RD = Parent;
3004 else
3005 break;
3006 }
3007
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003008 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003009 }
Mike Stump1eb44332009-09-09 15:08:12 +00003010
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003011 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003012}
3013
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003014static void
3015DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003016 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003017 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003018 unsigned NumInits) {
3019 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003020 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003021
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003022 // Don't check initializers order unless the warning is enabled at the
3023 // location of at least one initializer.
3024 bool ShouldCheckOrder = false;
3025 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003026 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003027 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3028 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003029 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003030 ShouldCheckOrder = true;
3031 break;
3032 }
3033 }
3034 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003035 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003036
John McCalld6ca8da2010-04-10 07:37:23 +00003037 // Build the list of bases and members in the order that they'll
3038 // actually be initialized. The explicit initializers should be in
3039 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003040 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Anders Carlsson071d6102010-04-02 03:38:04 +00003042 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3043
John McCalld6ca8da2010-04-10 07:37:23 +00003044 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003045 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003046 ClassDecl->vbases_begin(),
3047 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003048 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003049
John McCalld6ca8da2010-04-10 07:37:23 +00003050 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003051 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003052 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003053 if (Base->isVirtual())
3054 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003055 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003056 }
Mike Stump1eb44332009-09-09 15:08:12 +00003057
John McCalld6ca8da2010-04-10 07:37:23 +00003058 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003059 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003060 E = ClassDecl->field_end(); Field != E; ++Field) {
3061 if (Field->isUnnamedBitfield())
3062 continue;
3063
John McCalld6ca8da2010-04-10 07:37:23 +00003064 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003065 }
3066
John McCalld6ca8da2010-04-10 07:37:23 +00003067 unsigned NumIdealInits = IdealInitKeys.size();
3068 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003069
Sean Huntcbb67482011-01-08 20:30:50 +00003070 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003071 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003072 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003073 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003074
3075 // Scan forward to try to find this initializer in the idealized
3076 // initializers list.
3077 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3078 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003079 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003080
3081 // If we didn't find this initializer, it must be because we
3082 // scanned past it on a previous iteration. That can only
3083 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003084 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003085 Sema::SemaDiagnosticBuilder D =
3086 SemaRef.Diag(PrevInit->getSourceLocation(),
3087 diag::warn_initializer_out_of_order);
3088
Francois Pichet00eb3f92010-12-04 09:14:42 +00003089 if (PrevInit->isAnyMemberInitializer())
3090 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003091 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003092 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003093
Francois Pichet00eb3f92010-12-04 09:14:42 +00003094 if (Init->isAnyMemberInitializer())
3095 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003096 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003097 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003098
3099 // Move back to the initializer's location in the ideal list.
3100 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3101 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003102 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003103
3104 assert(IdealIndex != NumIdealInits &&
3105 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003106 }
John McCalld6ca8da2010-04-10 07:37:23 +00003107
3108 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003109 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003110}
3111
John McCall3c3ccdb2010-04-10 09:28:51 +00003112namespace {
3113bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003114 CXXCtorInitializer *Init,
3115 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003116 if (!PrevInit) {
3117 PrevInit = Init;
3118 return false;
3119 }
3120
3121 if (FieldDecl *Field = Init->getMember())
3122 S.Diag(Init->getSourceLocation(),
3123 diag::err_multiple_mem_initialization)
3124 << Field->getDeclName()
3125 << Init->getSourceRange();
3126 else {
John McCallf4c73712011-01-19 06:33:43 +00003127 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003128 assert(BaseClass && "neither field nor base");
3129 S.Diag(Init->getSourceLocation(),
3130 diag::err_multiple_base_initialization)
3131 << QualType(BaseClass, 0)
3132 << Init->getSourceRange();
3133 }
3134 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3135 << 0 << PrevInit->getSourceRange();
3136
3137 return true;
3138}
3139
Sean Huntcbb67482011-01-08 20:30:50 +00003140typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003141typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3142
3143bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003144 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003145 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003146 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003147 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003148 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003149
3150 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003151 if (Parent->isUnion()) {
3152 UnionEntry &En = Unions[Parent];
3153 if (En.first && En.first != Child) {
3154 S.Diag(Init->getSourceLocation(),
3155 diag::err_multiple_mem_union_initialization)
3156 << Field->getDeclName()
3157 << Init->getSourceRange();
3158 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3159 << 0 << En.second->getSourceRange();
3160 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003161 }
3162 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003163 En.first = Child;
3164 En.second = Init;
3165 }
David Blaikie6fe29652011-11-17 06:01:57 +00003166 if (!Parent->isAnonymousStructOrUnion())
3167 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003168 }
3169
3170 Child = Parent;
3171 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003172 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003173
3174 return false;
3175}
3176}
3177
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003178/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003179void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003180 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003181 CXXCtorInitializer **meminits,
3182 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003183 bool AnyErrors) {
3184 if (!ConstructorDecl)
3185 return;
3186
3187 AdjustDeclIfTemplate(ConstructorDecl);
3188
3189 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003190 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003191
3192 if (!Constructor) {
3193 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3194 return;
3195 }
3196
Sean Huntcbb67482011-01-08 20:30:50 +00003197 CXXCtorInitializer **MemInits =
3198 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003199
3200 // Mapping for the duplicate initializers check.
3201 // For member initializers, this is keyed with a FieldDecl*.
3202 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003203 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003204
3205 // Mapping for the inconsistent anonymous-union initializers check.
3206 RedundantUnionMap MemberUnions;
3207
Anders Carlssonea356fb2010-04-02 05:42:15 +00003208 bool HadError = false;
3209 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003210 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003211
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003212 // Set the source order index.
3213 Init->setSourceOrder(i);
3214
Francois Pichet00eb3f92010-12-04 09:14:42 +00003215 if (Init->isAnyMemberInitializer()) {
3216 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003217 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3218 CheckRedundantUnionInit(*this, Init, MemberUnions))
3219 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003220 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003221 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3222 if (CheckRedundantInit(*this, Init, Members[Key]))
3223 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003224 } else {
3225 assert(Init->isDelegatingInitializer());
3226 // This must be the only initializer
3227 if (i != 0 || NumMemInits > 1) {
3228 Diag(MemInits[0]->getSourceLocation(),
3229 diag::err_delegating_initializer_alone)
3230 << MemInits[0]->getSourceRange();
3231 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003232 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003233 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003234 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003235 // Return immediately as the initializer is set.
3236 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003237 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003238 }
3239
Anders Carlssonea356fb2010-04-02 05:42:15 +00003240 if (HadError)
3241 return;
3242
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003243 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003244
Sean Huntcbb67482011-01-08 20:30:50 +00003245 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003246}
3247
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003248void
John McCallef027fe2010-03-16 21:39:52 +00003249Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3250 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003251 // Ignore dependent contexts. Also ignore unions, since their members never
3252 // have destructors implicitly called.
3253 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003254 return;
John McCall58e6f342010-03-16 05:22:47 +00003255
3256 // FIXME: all the access-control diagnostics are positioned on the
3257 // field/base declaration. That's probably good; that said, the
3258 // user might reasonably want to know why the destructor is being
3259 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003260
Anders Carlsson9f853df2009-11-17 04:44:12 +00003261 // Non-static data members.
3262 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3263 E = ClassDecl->field_end(); I != E; ++I) {
3264 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003265 if (Field->isInvalidDecl())
3266 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003267
3268 // Don't destroy incomplete or zero-length arrays.
3269 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3270 continue;
3271
Anders Carlsson9f853df2009-11-17 04:44:12 +00003272 QualType FieldType = Context.getBaseElementType(Field->getType());
3273
3274 const RecordType* RT = FieldType->getAs<RecordType>();
3275 if (!RT)
3276 continue;
3277
3278 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003279 if (FieldClassDecl->isInvalidDecl())
3280 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003281 if (FieldClassDecl->hasTrivialDestructor())
3282 continue;
3283
Douglas Gregordb89f282010-07-01 22:47:18 +00003284 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003285 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003286 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003287 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003288 << Field->getDeclName()
3289 << FieldType);
3290
Eli Friedman5f2987c2012-02-02 03:46:19 +00003291 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003292 }
3293
John McCall58e6f342010-03-16 05:22:47 +00003294 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3295
Anders Carlsson9f853df2009-11-17 04:44:12 +00003296 // Bases.
3297 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3298 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003299 // Bases are always records in a well-formed non-dependent class.
3300 const RecordType *RT = Base->getType()->getAs<RecordType>();
3301
3302 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003303 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003304 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003305
John McCall58e6f342010-03-16 05:22:47 +00003306 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003307 // If our base class is invalid, we probably can't get its dtor anyway.
3308 if (BaseClassDecl->isInvalidDecl())
3309 continue;
3310 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003311 if (BaseClassDecl->hasTrivialDestructor())
3312 continue;
John McCall58e6f342010-03-16 05:22:47 +00003313
Douglas Gregordb89f282010-07-01 22:47:18 +00003314 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003315 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003316
3317 // FIXME: caret should be on the start of the class name
3318 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003319 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003320 << Base->getType()
3321 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003322
Eli Friedman5f2987c2012-02-02 03:46:19 +00003323 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003324 }
3325
3326 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003327 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3328 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003329
3330 // Bases are always records in a well-formed non-dependent class.
3331 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3332
3333 // Ignore direct virtual bases.
3334 if (DirectVirtualBases.count(RT))
3335 continue;
3336
John McCall58e6f342010-03-16 05:22:47 +00003337 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003338 // If our base class is invalid, we probably can't get its dtor anyway.
3339 if (BaseClassDecl->isInvalidDecl())
3340 continue;
3341 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003342 if (BaseClassDecl->hasTrivialDestructor())
3343 continue;
John McCall58e6f342010-03-16 05:22:47 +00003344
Douglas Gregordb89f282010-07-01 22:47:18 +00003345 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003346 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003347 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003348 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003349 << VBase->getType());
3350
Eli Friedman5f2987c2012-02-02 03:46:19 +00003351 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003352 }
3353}
3354
John McCalld226f652010-08-21 09:40:31 +00003355void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003356 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003357 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003358
Mike Stump1eb44332009-09-09 15:08:12 +00003359 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003360 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003361 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003362}
3363
Mike Stump1eb44332009-09-09 15:08:12 +00003364bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003365 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003366 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003367 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003368 else
John McCall94c3b562010-08-18 09:41:07 +00003369 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003370}
3371
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003372bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003373 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003374 if (!getLangOptions().CPlusPlus)
3375 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003376
Anders Carlsson11f21a02009-03-23 19:10:31 +00003377 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003378 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003379
Ted Kremenek6217b802009-07-29 21:53:49 +00003380 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003381 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003382 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003383 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003384
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003385 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003386 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003387 }
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Ted Kremenek6217b802009-07-29 21:53:49 +00003389 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003390 if (!RT)
3391 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003392
John McCall86ff3082010-02-04 22:26:26 +00003393 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003394
John McCall94c3b562010-08-18 09:41:07 +00003395 // We can't answer whether something is abstract until it has a
3396 // definition. If it's currently being defined, we'll walk back
3397 // over all the declarations when we have a full definition.
3398 const CXXRecordDecl *Def = RD->getDefinition();
3399 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003400 return false;
3401
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003402 if (!RD->isAbstract())
3403 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003404
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003405 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003406 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003407
John McCall94c3b562010-08-18 09:41:07 +00003408 return true;
3409}
3410
3411void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3412 // Check if we've already emitted the list of pure virtual functions
3413 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003414 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003415 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003416
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003417 CXXFinalOverriderMap FinalOverriders;
3418 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003419
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003420 // Keep a set of seen pure methods so we won't diagnose the same method
3421 // more than once.
3422 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3423
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003424 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3425 MEnd = FinalOverriders.end();
3426 M != MEnd;
3427 ++M) {
3428 for (OverridingMethods::iterator SO = M->second.begin(),
3429 SOEnd = M->second.end();
3430 SO != SOEnd; ++SO) {
3431 // C++ [class.abstract]p4:
3432 // A class is abstract if it contains or inherits at least one
3433 // pure virtual function for which the final overrider is pure
3434 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003436 //
3437 if (SO->second.size() != 1)
3438 continue;
3439
3440 if (!SO->second.front().Method->isPure())
3441 continue;
3442
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003443 if (!SeenPureMethods.insert(SO->second.front().Method))
3444 continue;
3445
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003446 Diag(SO->second.front().Method->getLocation(),
3447 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003448 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003449 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003450 }
3451
3452 if (!PureVirtualClassDiagSet)
3453 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3454 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003455}
3456
Anders Carlsson8211eff2009-03-24 01:19:16 +00003457namespace {
John McCall94c3b562010-08-18 09:41:07 +00003458struct AbstractUsageInfo {
3459 Sema &S;
3460 CXXRecordDecl *Record;
3461 CanQualType AbstractType;
3462 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003463
John McCall94c3b562010-08-18 09:41:07 +00003464 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3465 : S(S), Record(Record),
3466 AbstractType(S.Context.getCanonicalType(
3467 S.Context.getTypeDeclType(Record))),
3468 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003469
John McCall94c3b562010-08-18 09:41:07 +00003470 void DiagnoseAbstractType() {
3471 if (Invalid) return;
3472 S.DiagnoseAbstractType(Record);
3473 Invalid = true;
3474 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003475
John McCall94c3b562010-08-18 09:41:07 +00003476 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3477};
3478
3479struct CheckAbstractUsage {
3480 AbstractUsageInfo &Info;
3481 const NamedDecl *Ctx;
3482
3483 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3484 : Info(Info), Ctx(Ctx) {}
3485
3486 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3487 switch (TL.getTypeLocClass()) {
3488#define ABSTRACT_TYPELOC(CLASS, PARENT)
3489#define TYPELOC(CLASS, PARENT) \
3490 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3491#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003492 }
John McCall94c3b562010-08-18 09:41:07 +00003493 }
Mike Stump1eb44332009-09-09 15:08:12 +00003494
John McCall94c3b562010-08-18 09:41:07 +00003495 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3496 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3497 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003498 if (!TL.getArg(I))
3499 continue;
3500
John McCall94c3b562010-08-18 09:41:07 +00003501 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3502 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003503 }
John McCall94c3b562010-08-18 09:41:07 +00003504 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003505
John McCall94c3b562010-08-18 09:41:07 +00003506 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3507 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3508 }
Mike Stump1eb44332009-09-09 15:08:12 +00003509
John McCall94c3b562010-08-18 09:41:07 +00003510 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3511 // Visit the type parameters from a permissive context.
3512 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3513 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3514 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3515 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3516 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3517 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003518 }
John McCall94c3b562010-08-18 09:41:07 +00003519 }
Mike Stump1eb44332009-09-09 15:08:12 +00003520
John McCall94c3b562010-08-18 09:41:07 +00003521 // Visit pointee types from a permissive context.
3522#define CheckPolymorphic(Type) \
3523 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3524 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3525 }
3526 CheckPolymorphic(PointerTypeLoc)
3527 CheckPolymorphic(ReferenceTypeLoc)
3528 CheckPolymorphic(MemberPointerTypeLoc)
3529 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003530 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003531
John McCall94c3b562010-08-18 09:41:07 +00003532 /// Handle all the types we haven't given a more specific
3533 /// implementation for above.
3534 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3535 // Every other kind of type that we haven't called out already
3536 // that has an inner type is either (1) sugar or (2) contains that
3537 // inner type in some way as a subobject.
3538 if (TypeLoc Next = TL.getNextTypeLoc())
3539 return Visit(Next, Sel);
3540
3541 // If there's no inner type and we're in a permissive context,
3542 // don't diagnose.
3543 if (Sel == Sema::AbstractNone) return;
3544
3545 // Check whether the type matches the abstract type.
3546 QualType T = TL.getType();
3547 if (T->isArrayType()) {
3548 Sel = Sema::AbstractArrayType;
3549 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003550 }
John McCall94c3b562010-08-18 09:41:07 +00003551 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3552 if (CT != Info.AbstractType) return;
3553
3554 // It matched; do some magic.
3555 if (Sel == Sema::AbstractArrayType) {
3556 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3557 << T << TL.getSourceRange();
3558 } else {
3559 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3560 << Sel << T << TL.getSourceRange();
3561 }
3562 Info.DiagnoseAbstractType();
3563 }
3564};
3565
3566void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3567 Sema::AbstractDiagSelID Sel) {
3568 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3569}
3570
3571}
3572
3573/// Check for invalid uses of an abstract type in a method declaration.
3574static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3575 CXXMethodDecl *MD) {
3576 // No need to do the check on definitions, which require that
3577 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003578 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003579 return;
3580
3581 // For safety's sake, just ignore it if we don't have type source
3582 // information. This should never happen for non-implicit methods,
3583 // but...
3584 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3585 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3586}
3587
3588/// Check for invalid uses of an abstract type within a class definition.
3589static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3590 CXXRecordDecl *RD) {
3591 for (CXXRecordDecl::decl_iterator
3592 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3593 Decl *D = *I;
3594 if (D->isImplicit()) continue;
3595
3596 // Methods and method templates.
3597 if (isa<CXXMethodDecl>(D)) {
3598 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3599 } else if (isa<FunctionTemplateDecl>(D)) {
3600 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3601 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3602
3603 // Fields and static variables.
3604 } else if (isa<FieldDecl>(D)) {
3605 FieldDecl *FD = cast<FieldDecl>(D);
3606 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3607 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3608 } else if (isa<VarDecl>(D)) {
3609 VarDecl *VD = cast<VarDecl>(D);
3610 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3611 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3612
3613 // Nested classes and class templates.
3614 } else if (isa<CXXRecordDecl>(D)) {
3615 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3616 } else if (isa<ClassTemplateDecl>(D)) {
3617 CheckAbstractClassUsage(Info,
3618 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3619 }
3620 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003621}
3622
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003623/// \brief Perform semantic checks on a class definition that has been
3624/// completing, introducing implicitly-declared members, checking for
3625/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003626void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003627 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003628 return;
3629
John McCall94c3b562010-08-18 09:41:07 +00003630 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3631 AbstractUsageInfo Info(*this, Record);
3632 CheckAbstractClassUsage(Info, Record);
3633 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003634
3635 // If this is not an aggregate type and has no user-declared constructor,
3636 // complain about any non-static data members of reference or const scalar
3637 // type, since they will never get initializers.
3638 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3639 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3640 bool Complained = false;
3641 for (RecordDecl::field_iterator F = Record->field_begin(),
3642 FEnd = Record->field_end();
3643 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003644 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003645 continue;
3646
Douglas Gregor325e5932010-04-15 00:00:53 +00003647 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003648 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003649 if (!Complained) {
3650 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3651 << Record->getTagKind() << Record;
3652 Complained = true;
3653 }
3654
3655 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3656 << F->getType()->isReferenceType()
3657 << F->getDeclName();
3658 }
3659 }
3660 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003661
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003662 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003663 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003664
3665 if (Record->getIdentifier()) {
3666 // C++ [class.mem]p13:
3667 // If T is the name of a class, then each of the following shall have a
3668 // name different from T:
3669 // - every member of every anonymous union that is a member of class T.
3670 //
3671 // C++ [class.mem]p14:
3672 // In addition, if class T has a user-declared constructor (12.1), every
3673 // non-static data member of class T shall have a name different from T.
3674 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003675 R.first != R.second; ++R.first) {
3676 NamedDecl *D = *R.first;
3677 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3678 isa<IndirectFieldDecl>(D)) {
3679 Diag(D->getLocation(), diag::err_member_name_of_class)
3680 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003681 break;
3682 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003683 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003684 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003685
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003686 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003687 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003688 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003689 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003690 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3691 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3692 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003693
3694 // See if a method overloads virtual methods in a base
3695 /// class without overriding any.
3696 if (!Record->isDependentType()) {
3697 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3698 MEnd = Record->method_end();
3699 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003700 if (!(*M)->isStatic())
3701 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003702 }
3703 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003704
Richard Smith9f569cc2011-10-01 02:31:28 +00003705 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3706 // function that is not a constructor declares that member function to be
3707 // const. [...] The class of which that function is a member shall be
3708 // a literal type.
3709 //
3710 // It's fine to diagnose constructors here too: such constructors cannot
3711 // produce a constant expression, so are ill-formed (no diagnostic required).
3712 //
3713 // If the class has virtual bases, any constexpr members will already have
3714 // been diagnosed by the checks performed on the member declaration, so
3715 // suppress this (less useful) diagnostic.
3716 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3717 !Record->isLiteral() && !Record->getNumVBases()) {
3718 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3719 MEnd = Record->method_end();
3720 M != MEnd; ++M) {
Eli Friedman9ec0ef32012-01-13 02:31:53 +00003721 if (M->isConstexpr() && M->isInstance()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003722 switch (Record->getTemplateSpecializationKind()) {
3723 case TSK_ImplicitInstantiation:
3724 case TSK_ExplicitInstantiationDeclaration:
3725 case TSK_ExplicitInstantiationDefinition:
3726 // If a template instantiates to a non-literal type, but its members
3727 // instantiate to constexpr functions, the template is technically
3728 // ill-formed, but we allow it for sanity. Such members are treated as
3729 // non-constexpr.
3730 (*M)->setConstexpr(false);
3731 continue;
3732
3733 case TSK_Undeclared:
3734 case TSK_ExplicitSpecialization:
3735 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3736 PDiag(diag::err_constexpr_method_non_literal));
3737 break;
3738 }
3739
3740 // Only produce one error per class.
3741 break;
3742 }
3743 }
3744 }
3745
Sebastian Redlf677ea32011-02-05 19:23:19 +00003746 // Declare inherited constructors. We do this eagerly here because:
3747 // - The standard requires an eager diagnostic for conflicting inherited
3748 // constructors from different classes.
3749 // - The lazy declaration of the other implicit constructors is so as to not
3750 // waste space and performance on classes that are not meant to be
3751 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3752 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003753 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003754
Sean Hunteb88ae52011-05-23 21:07:59 +00003755 if (!Record->isDependentType())
3756 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003757}
3758
3759void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003760 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3761 ME = Record->method_end();
3762 MI != ME; ++MI) {
3763 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3764 switch (getSpecialMember(*MI)) {
3765 case CXXDefaultConstructor:
3766 CheckExplicitlyDefaultedDefaultConstructor(
3767 cast<CXXConstructorDecl>(*MI));
3768 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003769
Sean Huntcb45a0f2011-05-12 22:46:25 +00003770 case CXXDestructor:
3771 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3772 break;
3773
3774 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003775 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3776 break;
3777
Sean Huntcb45a0f2011-05-12 22:46:25 +00003778 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003779 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003780 break;
3781
Sean Hunt82713172011-05-25 23:16:36 +00003782 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003783 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003784 break;
3785
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003786 case CXXMoveAssignment:
3787 CheckExplicitlyDefaultedMoveAssignment(*MI);
3788 break;
3789
3790 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003791 llvm_unreachable("non-special member explicitly defaulted!");
3792 }
Sean Hunt001cad92011-05-10 00:49:42 +00003793 }
3794 }
3795
Sean Hunt001cad92011-05-10 00:49:42 +00003796}
3797
3798void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3799 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3800
3801 // Whether this was the first-declared instance of the constructor.
3802 // This affects whether we implicitly add an exception spec (and, eventually,
3803 // constexpr). It is also ill-formed to explicitly default a constructor such
3804 // that it would be deleted. (C++0x [decl.fct.def.default])
3805 bool First = CD == CD->getCanonicalDecl();
3806
Sean Hunt49634cf2011-05-13 06:10:58 +00003807 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003808 if (CD->getNumParams() != 0) {
3809 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3810 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003811 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003812 }
3813
3814 ImplicitExceptionSpecification Spec
3815 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3816 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003817 if (EPI.ExceptionSpecType == EST_Delayed) {
3818 // Exception specification depends on some deferred part of the class. We'll
3819 // try again when the class's definition has been fully processed.
3820 return;
3821 }
Sean Hunt001cad92011-05-10 00:49:42 +00003822 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3823 *ExceptionType = Context.getFunctionType(
3824 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3825
Richard Smith61802452011-12-22 02:22:31 +00003826 // C++11 [dcl.fct.def.default]p2:
3827 // An explicitly-defaulted function may be declared constexpr only if it
3828 // would have been implicitly declared as constexpr,
3829 if (CD->isConstexpr()) {
3830 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3831 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3832 << CXXDefaultConstructor;
3833 HadError = true;
3834 }
3835 }
3836 // and may have an explicit exception-specification only if it is compatible
3837 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003838 if (CtorType->hasExceptionSpec()) {
3839 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003840 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003841 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003842 PDiag(),
3843 ExceptionType, SourceLocation(),
3844 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003845 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003846 }
Richard Smith61802452011-12-22 02:22:31 +00003847 }
3848
3849 // If a function is explicitly defaulted on its first declaration,
3850 if (First) {
3851 // -- it is implicitly considered to be constexpr if the implicit
3852 // definition would be,
3853 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3854
3855 // -- it is implicitly considered to have the same
3856 // exception-specification as if it had been implicitly declared
3857 //
3858 // FIXME: a compatible, but different, explicit exception specification
3859 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003860 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003861 }
Sean Huntca46d132011-05-12 03:51:48 +00003862
Sean Hunt49634cf2011-05-13 06:10:58 +00003863 if (HadError) {
3864 CD->setInvalidDecl();
3865 return;
3866 }
3867
Sean Hunte16da072011-10-10 06:18:57 +00003868 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003869 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003870 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003871 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003872 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003873 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003874 CD->setInvalidDecl();
3875 }
3876 }
3877}
3878
3879void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3880 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3881
3882 // Whether this was the first-declared instance of the constructor.
3883 bool First = CD == CD->getCanonicalDecl();
3884
3885 bool HadError = false;
3886 if (CD->getNumParams() != 1) {
3887 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3888 << CD->getSourceRange();
3889 HadError = true;
3890 }
3891
3892 ImplicitExceptionSpecification Spec(Context);
3893 bool Const;
3894 llvm::tie(Spec, Const) =
3895 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3896
3897 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3898 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3899 *ExceptionType = Context.getFunctionType(
3900 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3901
3902 // Check for parameter type matching.
3903 // This is a copy ctor so we know it's a cv-qualified reference to T.
3904 QualType ArgType = CtorType->getArgType(0);
3905 if (ArgType->getPointeeType().isVolatileQualified()) {
3906 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3907 HadError = true;
3908 }
3909 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3910 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3911 HadError = true;
3912 }
3913
Richard Smith61802452011-12-22 02:22:31 +00003914 // C++11 [dcl.fct.def.default]p2:
3915 // An explicitly-defaulted function may be declared constexpr only if it
3916 // would have been implicitly declared as constexpr,
3917 if (CD->isConstexpr()) {
3918 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3919 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3920 << CXXCopyConstructor;
3921 HadError = true;
3922 }
3923 }
3924 // and may have an explicit exception-specification only if it is compatible
3925 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003926 if (CtorType->hasExceptionSpec()) {
3927 if (CheckEquivalentExceptionSpec(
3928 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003929 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003930 PDiag(),
3931 ExceptionType, SourceLocation(),
3932 CtorType, CD->getLocation())) {
3933 HadError = true;
3934 }
Richard Smith61802452011-12-22 02:22:31 +00003935 }
3936
3937 // If a function is explicitly defaulted on its first declaration,
3938 if (First) {
3939 // -- it is implicitly considered to be constexpr if the implicit
3940 // definition would be,
3941 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3942
3943 // -- it is implicitly considered to have the same
3944 // exception-specification as if it had been implicitly declared, and
3945 //
3946 // FIXME: a compatible, but different, explicit exception specification
3947 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003948 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003949
3950 // -- [...] it shall have the same parameter type as if it had been
3951 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003952 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3953 }
3954
3955 if (HadError) {
3956 CD->setInvalidDecl();
3957 return;
3958 }
3959
Sean Huntc32d6842011-10-11 04:55:36 +00003960 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003961 if (First) {
3962 CD->setDeletedAsWritten();
3963 } else {
3964 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003965 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003966 CD->setInvalidDecl();
3967 }
Sean Huntca46d132011-05-12 03:51:48 +00003968 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003969}
Sean Hunt001cad92011-05-10 00:49:42 +00003970
Sean Hunt2b188082011-05-14 05:23:28 +00003971void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3972 assert(MD->isExplicitlyDefaulted());
3973
3974 // Whether this was the first-declared instance of the operator
3975 bool First = MD == MD->getCanonicalDecl();
3976
3977 bool HadError = false;
3978 if (MD->getNumParams() != 1) {
3979 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3980 << MD->getSourceRange();
3981 HadError = true;
3982 }
3983
3984 QualType ReturnType =
3985 MD->getType()->getAs<FunctionType>()->getResultType();
3986 if (!ReturnType->isLValueReferenceType() ||
3987 !Context.hasSameType(
3988 Context.getCanonicalType(ReturnType->getPointeeType()),
3989 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3990 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3991 HadError = true;
3992 }
3993
3994 ImplicitExceptionSpecification Spec(Context);
3995 bool Const;
3996 llvm::tie(Spec, Const) =
3997 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3998
3999 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4000 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4001 *ExceptionType = Context.getFunctionType(
4002 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4003
Sean Hunt2b188082011-05-14 05:23:28 +00004004 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004005 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004006 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004007 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004008 } else {
4009 if (ArgType->getPointeeType().isVolatileQualified()) {
4010 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4011 HadError = true;
4012 }
4013 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4014 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4015 HadError = true;
4016 }
Sean Hunt2b188082011-05-14 05:23:28 +00004017 }
Sean Huntbe631222011-05-17 20:44:43 +00004018
Sean Hunt2b188082011-05-14 05:23:28 +00004019 if (OperType->getTypeQuals()) {
4020 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4021 HadError = true;
4022 }
4023
4024 if (OperType->hasExceptionSpec()) {
4025 if (CheckEquivalentExceptionSpec(
4026 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004027 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004028 PDiag(),
4029 ExceptionType, SourceLocation(),
4030 OperType, MD->getLocation())) {
4031 HadError = true;
4032 }
Richard Smith61802452011-12-22 02:22:31 +00004033 }
4034 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004035 // We set the declaration to have the computed exception spec here.
4036 // We duplicate the one parameter type.
4037 EPI.RefQualifier = OperType->getRefQualifier();
4038 EPI.ExtInfo = OperType->getExtInfo();
4039 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4040 }
4041
4042 if (HadError) {
4043 MD->setInvalidDecl();
4044 return;
4045 }
4046
4047 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4048 if (First) {
4049 MD->setDeletedAsWritten();
4050 } else {
4051 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004052 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004053 MD->setInvalidDecl();
4054 }
4055 }
4056}
4057
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004058void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4059 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4060
4061 // Whether this was the first-declared instance of the constructor.
4062 bool First = CD == CD->getCanonicalDecl();
4063
4064 bool HadError = false;
4065 if (CD->getNumParams() != 1) {
4066 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4067 << CD->getSourceRange();
4068 HadError = true;
4069 }
4070
4071 ImplicitExceptionSpecification Spec(
4072 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4073
4074 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4075 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4076 *ExceptionType = Context.getFunctionType(
4077 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4078
4079 // Check for parameter type matching.
4080 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4081 QualType ArgType = CtorType->getArgType(0);
4082 if (ArgType->getPointeeType().isVolatileQualified()) {
4083 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4084 HadError = true;
4085 }
4086 if (ArgType->getPointeeType().isConstQualified()) {
4087 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4088 HadError = true;
4089 }
4090
Richard Smith61802452011-12-22 02:22:31 +00004091 // C++11 [dcl.fct.def.default]p2:
4092 // An explicitly-defaulted function may be declared constexpr only if it
4093 // would have been implicitly declared as constexpr,
4094 if (CD->isConstexpr()) {
4095 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4096 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4097 << CXXMoveConstructor;
4098 HadError = true;
4099 }
4100 }
4101 // and may have an explicit exception-specification only if it is compatible
4102 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004103 if (CtorType->hasExceptionSpec()) {
4104 if (CheckEquivalentExceptionSpec(
4105 PDiag(diag::err_incorrect_defaulted_exception_spec)
4106 << CXXMoveConstructor,
4107 PDiag(),
4108 ExceptionType, SourceLocation(),
4109 CtorType, CD->getLocation())) {
4110 HadError = true;
4111 }
Richard Smith61802452011-12-22 02:22:31 +00004112 }
4113
4114 // If a function is explicitly defaulted on its first declaration,
4115 if (First) {
4116 // -- it is implicitly considered to be constexpr if the implicit
4117 // definition would be,
4118 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4119
4120 // -- it is implicitly considered to have the same
4121 // exception-specification as if it had been implicitly declared, and
4122 //
4123 // FIXME: a compatible, but different, explicit exception specification
4124 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004125 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004126
4127 // -- [...] it shall have the same parameter type as if it had been
4128 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004129 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4130 }
4131
4132 if (HadError) {
4133 CD->setInvalidDecl();
4134 return;
4135 }
4136
Sean Hunt769bb2d2011-10-11 06:43:29 +00004137 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004138 if (First) {
4139 CD->setDeletedAsWritten();
4140 } else {
4141 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4142 << CXXMoveConstructor;
4143 CD->setInvalidDecl();
4144 }
4145 }
4146}
4147
4148void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4149 assert(MD->isExplicitlyDefaulted());
4150
4151 // Whether this was the first-declared instance of the operator
4152 bool First = MD == MD->getCanonicalDecl();
4153
4154 bool HadError = false;
4155 if (MD->getNumParams() != 1) {
4156 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4157 << MD->getSourceRange();
4158 HadError = true;
4159 }
4160
4161 QualType ReturnType =
4162 MD->getType()->getAs<FunctionType>()->getResultType();
4163 if (!ReturnType->isLValueReferenceType() ||
4164 !Context.hasSameType(
4165 Context.getCanonicalType(ReturnType->getPointeeType()),
4166 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4167 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4168 HadError = true;
4169 }
4170
4171 ImplicitExceptionSpecification Spec(
4172 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4173
4174 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4175 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4176 *ExceptionType = Context.getFunctionType(
4177 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4178
4179 QualType ArgType = OperType->getArgType(0);
4180 if (!ArgType->isRValueReferenceType()) {
4181 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4182 HadError = true;
4183 } else {
4184 if (ArgType->getPointeeType().isVolatileQualified()) {
4185 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4186 HadError = true;
4187 }
4188 if (ArgType->getPointeeType().isConstQualified()) {
4189 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4190 HadError = true;
4191 }
4192 }
4193
4194 if (OperType->getTypeQuals()) {
4195 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4196 HadError = true;
4197 }
4198
4199 if (OperType->hasExceptionSpec()) {
4200 if (CheckEquivalentExceptionSpec(
4201 PDiag(diag::err_incorrect_defaulted_exception_spec)
4202 << CXXMoveAssignment,
4203 PDiag(),
4204 ExceptionType, SourceLocation(),
4205 OperType, MD->getLocation())) {
4206 HadError = true;
4207 }
Richard Smith61802452011-12-22 02:22:31 +00004208 }
4209 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004210 // We set the declaration to have the computed exception spec here.
4211 // We duplicate the one parameter type.
4212 EPI.RefQualifier = OperType->getRefQualifier();
4213 EPI.ExtInfo = OperType->getExtInfo();
4214 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4215 }
4216
4217 if (HadError) {
4218 MD->setInvalidDecl();
4219 return;
4220 }
4221
4222 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4223 if (First) {
4224 MD->setDeletedAsWritten();
4225 } else {
4226 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4227 << CXXMoveAssignment;
4228 MD->setInvalidDecl();
4229 }
4230 }
4231}
4232
Sean Huntcb45a0f2011-05-12 22:46:25 +00004233void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4234 assert(DD->isExplicitlyDefaulted());
4235
4236 // Whether this was the first-declared instance of the destructor.
4237 bool First = DD == DD->getCanonicalDecl();
4238
4239 ImplicitExceptionSpecification Spec
4240 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4241 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4242 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4243 *ExceptionType = Context.getFunctionType(
4244 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4245
4246 if (DtorType->hasExceptionSpec()) {
4247 if (CheckEquivalentExceptionSpec(
4248 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004249 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004250 PDiag(),
4251 ExceptionType, SourceLocation(),
4252 DtorType, DD->getLocation())) {
4253 DD->setInvalidDecl();
4254 return;
4255 }
Richard Smith61802452011-12-22 02:22:31 +00004256 }
4257 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004258 // We set the declaration to have the computed exception spec here.
4259 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004260 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004261 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4262 }
4263
4264 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004265 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004266 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004267 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004268 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004269 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004270 DD->setInvalidDecl();
4271 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004272 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004273}
4274
Sean Hunte16da072011-10-10 06:18:57 +00004275/// This function implements the following C++0x paragraphs:
4276/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004277/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004278bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4279 assert(!MD->isInvalidDecl());
4280 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004281 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004282 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004283 return false;
4284
Sean Hunte16da072011-10-10 06:18:57 +00004285 bool IsUnion = RD->isUnion();
4286 bool IsConstructor = false;
4287 bool IsAssignment = false;
4288 bool IsMove = false;
4289
4290 bool ConstArg = false;
4291
4292 switch (CSM) {
4293 case CXXDefaultConstructor:
4294 IsConstructor = true;
4295 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004296 case CXXCopyConstructor:
4297 IsConstructor = true;
4298 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4299 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004300 case CXXMoveConstructor:
4301 IsConstructor = true;
4302 IsMove = true;
4303 break;
Sean Hunte16da072011-10-10 06:18:57 +00004304 default:
4305 llvm_unreachable("function only currently implemented for default ctors");
4306 }
4307
4308 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004309
Sean Huntc32d6842011-10-11 04:55:36 +00004310 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004311 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004312
Sean Huntcdee3fe2011-05-11 22:34:38 +00004313 bool AllConst = true;
4314
Sean Huntcdee3fe2011-05-11 22:34:38 +00004315 // We do this because we should never actually use an anonymous
4316 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004317 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004318 return false;
4319
4320 // FIXME: We should put some diagnostic logic right into this function.
4321
Sean Huntcdee3fe2011-05-11 22:34:38 +00004322 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4323 BE = RD->bases_end();
4324 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004325 // We'll handle this one later
4326 if (BI->isVirtual())
4327 continue;
4328
Sean Huntcdee3fe2011-05-11 22:34:38 +00004329 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4330 assert(BaseDecl && "base isn't a CXXRecordDecl");
4331
Sean Hunte16da072011-10-10 06:18:57 +00004332 // Unless we have an assignment operator, the base's destructor must
4333 // be accessible and not deleted.
4334 if (!IsAssignment) {
4335 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4336 if (BaseDtor->isDeleted())
4337 return true;
4338 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4339 AR_accessible)
4340 return true;
4341 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004342
Sean Hunte16da072011-10-10 06:18:57 +00004343 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004344 // unique, accessible, non-deleted function. If we are doing
4345 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004346 if (CSM != CXXDestructor) {
4347 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004348 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004349 false);
4350 if (!SMOR->hasSuccess())
4351 return true;
4352 CXXMethodDecl *BaseMember = SMOR->getMethod();
4353 if (IsConstructor) {
4354 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4355 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4356 PDiag()) != AR_accessible)
4357 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004358
4359 // For a move operation, the corresponding operation must actually
4360 // be a move operation (and not a copy selected by overload
4361 // resolution) unless we are working on a trivially copyable class.
4362 if (IsMove && !BaseCtor->isMoveConstructor() &&
4363 !BaseDecl->isTriviallyCopyable())
4364 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004365 }
4366 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004367 }
4368
4369 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4370 BE = RD->vbases_end();
4371 BI != BE; ++BI) {
4372 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4373 assert(BaseDecl && "base isn't a CXXRecordDecl");
4374
Sean Hunte16da072011-10-10 06:18:57 +00004375 // Unless we have an assignment operator, the base's destructor must
4376 // be accessible and not deleted.
4377 if (!IsAssignment) {
4378 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4379 if (BaseDtor->isDeleted())
4380 return true;
4381 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4382 AR_accessible)
4383 return true;
4384 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004385
Sean Hunte16da072011-10-10 06:18:57 +00004386 // Finding the corresponding member in the base should lead to a
4387 // unique, accessible, non-deleted function.
4388 if (CSM != CXXDestructor) {
4389 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004390 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004391 false);
4392 if (!SMOR->hasSuccess())
4393 return true;
4394 CXXMethodDecl *BaseMember = SMOR->getMethod();
4395 if (IsConstructor) {
4396 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4397 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4398 PDiag()) != AR_accessible)
4399 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004400
4401 // For a move operation, the corresponding operation must actually
4402 // be a move operation (and not a copy selected by overload
4403 // resolution) unless we are working on a trivially copyable class.
4404 if (IsMove && !BaseCtor->isMoveConstructor() &&
4405 !BaseDecl->isTriviallyCopyable())
4406 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004407 }
4408 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004409 }
4410
4411 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4412 FE = RD->field_end();
4413 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004414 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004415 continue;
4416
Sean Huntcdee3fe2011-05-11 22:34:38 +00004417 QualType FieldType = Context.getBaseElementType(FI->getType());
4418 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004419
Sean Hunte16da072011-10-10 06:18:57 +00004420 // For a default constructor, all references must be initialized in-class
4421 // and, if a union, it must have a non-const member.
4422 if (CSM == CXXDefaultConstructor) {
4423 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4424 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004425
Sean Hunte16da072011-10-10 06:18:57 +00004426 if (IsUnion && !FieldType.isConstQualified())
4427 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004428 // For a copy constructor, data members must not be of rvalue reference
4429 // type.
4430 } else if (CSM == CXXCopyConstructor) {
4431 if (FieldType->isRValueReferenceType())
4432 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004433 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004434
4435 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004436 // For a default constructor, a const member must have a user-provided
4437 // default constructor or else be explicitly initialized.
4438 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004439 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004440 !FieldRecord->hasUserProvidedDefaultConstructor())
4441 return true;
4442
Sean Huntc32d6842011-10-11 04:55:36 +00004443 // Some additional restrictions exist on the variant members.
4444 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004445 FieldRecord->isAnonymousStructOrUnion()) {
4446 // We're okay to reuse AllConst here since we only care about the
4447 // value otherwise if we're in a union.
4448 AllConst = true;
4449
4450 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4451 UE = FieldRecord->field_end();
4452 UI != UE; ++UI) {
4453 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4454 CXXRecordDecl *UnionFieldRecord =
4455 UnionFieldType->getAsCXXRecordDecl();
4456
4457 if (!UnionFieldType.isConstQualified())
4458 AllConst = false;
4459
Sean Huntc32d6842011-10-11 04:55:36 +00004460 if (UnionFieldRecord) {
4461 // FIXME: Checking for accessibility and validity of this
4462 // destructor is technically going beyond the
4463 // standard, but this is believed to be a defect.
4464 if (!IsAssignment) {
4465 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4466 if (FieldDtor->isDeleted())
4467 return true;
4468 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4469 AR_accessible)
4470 return true;
4471 if (!FieldDtor->isTrivial())
4472 return true;
4473 }
4474
4475 if (CSM != CXXDestructor) {
4476 SpecialMemberOverloadResult *SMOR =
4477 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004478 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004479 // FIXME: Checking for accessibility and validity of this
4480 // corresponding member is technically going beyond the
4481 // standard, but this is believed to be a defect.
4482 if (!SMOR->hasSuccess())
4483 return true;
4484
4485 CXXMethodDecl *FieldMember = SMOR->getMethod();
4486 // A member of a union must have a trivial corresponding
4487 // constructor.
4488 if (!FieldMember->isTrivial())
4489 return true;
4490
4491 if (IsConstructor) {
4492 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4493 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4494 PDiag()) != AR_accessible)
4495 return true;
4496 }
4497 }
4498 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004499 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004500
Sean Huntc32d6842011-10-11 04:55:36 +00004501 // At least one member in each anonymous union must be non-const
4502 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004503 return true;
4504
4505 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004506 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004507 continue;
4508 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004509
Sean Huntc32d6842011-10-11 04:55:36 +00004510 // Unless we're doing assignment, the field's destructor must be
4511 // accessible and not deleted.
4512 if (!IsAssignment) {
4513 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4514 if (FieldDtor->isDeleted())
4515 return true;
4516 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4517 AR_accessible)
4518 return true;
4519 }
4520
Sean Hunte16da072011-10-10 06:18:57 +00004521 // Check that the corresponding member of the field is accessible,
4522 // unique, and non-deleted. We don't do this if it has an explicit
4523 // initialization when default-constructing.
4524 if (CSM != CXXDestructor &&
4525 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4526 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004527 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004528 false);
4529 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004530 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004531
4532 CXXMethodDecl *FieldMember = SMOR->getMethod();
4533 if (IsConstructor) {
4534 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4535 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4536 PDiag()) != AR_accessible)
4537 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004538
4539 // For a move operation, the corresponding operation must actually
4540 // be a move operation (and not a copy selected by overload
4541 // resolution) unless we are working on a trivially copyable class.
4542 if (IsMove && !FieldCtor->isMoveConstructor() &&
4543 !FieldRecord->isTriviallyCopyable())
4544 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004545 }
4546
4547 // We need the corresponding member of a union to be trivial so that
4548 // we can safely copy them all simultaneously.
4549 // FIXME: Note that performing the check here (where we rely on the lack
4550 // of an in-class initializer) is technically ill-formed. However, this
4551 // seems most obviously to be a bug in the standard.
4552 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004553 return true;
4554 }
Sean Hunte16da072011-10-10 06:18:57 +00004555 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4556 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4557 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004558 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004559 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004560 }
4561
Sean Hunte16da072011-10-10 06:18:57 +00004562 // We can't have all const members in a union when default-constructing,
4563 // or else they're all nonsensical garbage values that can't be changed.
4564 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004565 return true;
4566
4567 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004568}
4569
Sean Hunt7f410192011-05-14 05:23:24 +00004570bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4571 CXXRecordDecl *RD = MD->getParent();
4572 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004573 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004574 return false;
4575
Sean Hunt71a682f2011-05-18 03:41:58 +00004576 SourceLocation Loc = MD->getLocation();
4577
Sean Hunt7f410192011-05-14 05:23:24 +00004578 // Do access control from the constructor
4579 ContextRAII MethodContext(*this, MD);
4580
4581 bool Union = RD->isUnion();
4582
Sean Hunt661c67a2011-06-21 23:42:56 +00004583 unsigned ArgQuals =
4584 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4585 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004586
4587 // We do this because we should never actually use an anonymous
4588 // union's constructor.
4589 if (Union && RD->isAnonymousStructOrUnion())
4590 return false;
4591
Sean Hunt7f410192011-05-14 05:23:24 +00004592 // FIXME: We should put some diagnostic logic right into this function.
4593
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004594 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004595 // A defaulted [copy] assignment operator for class X is defined as deleted
4596 // if X has:
4597
4598 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4599 BE = RD->bases_end();
4600 BI != BE; ++BI) {
4601 // We'll handle this one later
4602 if (BI->isVirtual())
4603 continue;
4604
4605 QualType BaseType = BI->getType();
4606 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4607 assert(BaseDecl && "base isn't a CXXRecordDecl");
4608
4609 // -- a [direct base class] B that cannot be [copied] because overload
4610 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004611 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004612 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004613 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4614 0);
4615 if (!CopyOper || CopyOper->isDeleted())
4616 return true;
4617 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004618 return true;
4619 }
4620
4621 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4622 BE = RD->vbases_end();
4623 BI != BE; ++BI) {
4624 QualType BaseType = BI->getType();
4625 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4626 assert(BaseDecl && "base isn't a CXXRecordDecl");
4627
Sean Hunt7f410192011-05-14 05:23:24 +00004628 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004629 // resolution, as applied to B's [copy] assignment operator, results in
4630 // an ambiguity or a function that is deleted or inaccessible from the
4631 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004632 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4633 0);
4634 if (!CopyOper || CopyOper->isDeleted())
4635 return true;
4636 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004637 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004638 }
4639
4640 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4641 FE = RD->field_end();
4642 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004643 if (FI->isUnnamedBitfield())
4644 continue;
4645
Sean Hunt7f410192011-05-14 05:23:24 +00004646 QualType FieldType = Context.getBaseElementType(FI->getType());
4647
4648 // -- a non-static data member of reference type
4649 if (FieldType->isReferenceType())
4650 return true;
4651
4652 // -- a non-static data member of const non-class type (or array thereof)
4653 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4654 return true;
4655
4656 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4657
4658 if (FieldRecord) {
4659 // This is an anonymous union
4660 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4661 // Anonymous unions inside unions do not variant members create
4662 if (!Union) {
4663 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4664 UE = FieldRecord->field_end();
4665 UI != UE; ++UI) {
4666 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4667 CXXRecordDecl *UnionFieldRecord =
4668 UnionFieldType->getAsCXXRecordDecl();
4669
4670 // -- a variant member with a non-trivial [copy] assignment operator
4671 // and X is a union-like class
4672 if (UnionFieldRecord &&
4673 !UnionFieldRecord->hasTrivialCopyAssignment())
4674 return true;
4675 }
4676 }
4677
4678 // Don't try to initalize an anonymous union
4679 continue;
4680 // -- a variant member with a non-trivial [copy] assignment operator
4681 // and X is a union-like class
4682 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4683 return true;
4684 }
Sean Hunt7f410192011-05-14 05:23:24 +00004685
Sean Hunt661c67a2011-06-21 23:42:56 +00004686 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4687 false, 0);
4688 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004689 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004690 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004691 return true;
4692 }
4693 }
4694
4695 return false;
4696}
4697
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004698bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4699 CXXRecordDecl *RD = MD->getParent();
4700 assert(!RD->isDependentType() && "do deletion after instantiation");
4701 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4702 return false;
4703
4704 SourceLocation Loc = MD->getLocation();
4705
4706 // Do access control from the constructor
4707 ContextRAII MethodContext(*this, MD);
4708
4709 bool Union = RD->isUnion();
4710
4711 // We do this because we should never actually use an anonymous
4712 // union's constructor.
4713 if (Union && RD->isAnonymousStructOrUnion())
4714 return false;
4715
4716 // C++0x [class.copy]/20
4717 // A defaulted [move] assignment operator for class X is defined as deleted
4718 // if X has:
4719
4720 // -- for the move constructor, [...] any direct or indirect virtual base
4721 // class.
4722 if (RD->getNumVBases() != 0)
4723 return true;
4724
4725 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4726 BE = RD->bases_end();
4727 BI != BE; ++BI) {
4728
4729 QualType BaseType = BI->getType();
4730 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4731 assert(BaseDecl && "base isn't a CXXRecordDecl");
4732
4733 // -- a [direct base class] B that cannot be [moved] because overload
4734 // resolution, as applied to B's [move] assignment operator, results in
4735 // an ambiguity or a function that is deleted or inaccessible from the
4736 // assignment operator
4737 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4738 if (!MoveOper || MoveOper->isDeleted())
4739 return true;
4740 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4741 return true;
4742
4743 // -- for the move assignment operator, a [direct base class] with a type
4744 // that does not have a move assignment operator and is not trivially
4745 // copyable.
4746 if (!MoveOper->isMoveAssignmentOperator() &&
4747 !BaseDecl->isTriviallyCopyable())
4748 return true;
4749 }
4750
4751 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4752 FE = RD->field_end();
4753 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004754 if (FI->isUnnamedBitfield())
4755 continue;
4756
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004757 QualType FieldType = Context.getBaseElementType(FI->getType());
4758
4759 // -- a non-static data member of reference type
4760 if (FieldType->isReferenceType())
4761 return true;
4762
4763 // -- a non-static data member of const non-class type (or array thereof)
4764 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4765 return true;
4766
4767 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4768
4769 if (FieldRecord) {
4770 // This is an anonymous union
4771 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4772 // Anonymous unions inside unions do not variant members create
4773 if (!Union) {
4774 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4775 UE = FieldRecord->field_end();
4776 UI != UE; ++UI) {
4777 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4778 CXXRecordDecl *UnionFieldRecord =
4779 UnionFieldType->getAsCXXRecordDecl();
4780
4781 // -- a variant member with a non-trivial [move] assignment operator
4782 // and X is a union-like class
4783 if (UnionFieldRecord &&
4784 !UnionFieldRecord->hasTrivialMoveAssignment())
4785 return true;
4786 }
4787 }
4788
4789 // Don't try to initalize an anonymous union
4790 continue;
4791 // -- a variant member with a non-trivial [move] assignment operator
4792 // and X is a union-like class
4793 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4794 return true;
4795 }
4796
4797 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4798 if (!MoveOper || MoveOper->isDeleted())
4799 return true;
4800 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4801 return true;
4802
4803 // -- for the move assignment operator, a [non-static data member] with a
4804 // type that does not have a move assignment operator and is not
4805 // trivially copyable.
4806 if (!MoveOper->isMoveAssignmentOperator() &&
4807 !FieldRecord->isTriviallyCopyable())
4808 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004809 }
Sean Hunt7f410192011-05-14 05:23:24 +00004810 }
4811
4812 return false;
4813}
4814
Sean Huntcb45a0f2011-05-12 22:46:25 +00004815bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4816 CXXRecordDecl *RD = DD->getParent();
4817 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004818 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004819 return false;
4820
Sean Hunt71a682f2011-05-18 03:41:58 +00004821 SourceLocation Loc = DD->getLocation();
4822
Sean Huntcb45a0f2011-05-12 22:46:25 +00004823 // Do access control from the destructor
4824 ContextRAII CtorContext(*this, DD);
4825
4826 bool Union = RD->isUnion();
4827
Sean Hunt49634cf2011-05-13 06:10:58 +00004828 // We do this because we should never actually use an anonymous
4829 // union's destructor.
4830 if (Union && RD->isAnonymousStructOrUnion())
4831 return false;
4832
Sean Huntcb45a0f2011-05-12 22:46:25 +00004833 // C++0x [class.dtor]p5
4834 // A defaulted destructor for a class X is defined as deleted if:
4835 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4836 BE = RD->bases_end();
4837 BI != BE; ++BI) {
4838 // We'll handle this one later
4839 if (BI->isVirtual())
4840 continue;
4841
4842 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4843 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4844 assert(BaseDtor && "base has no destructor");
4845
4846 // -- any direct or virtual base class has a deleted destructor or
4847 // a destructor that is inaccessible from the defaulted destructor
4848 if (BaseDtor->isDeleted())
4849 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004850 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004851 AR_accessible)
4852 return true;
4853 }
4854
4855 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4856 BE = RD->vbases_end();
4857 BI != BE; ++BI) {
4858 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4859 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4860 assert(BaseDtor && "base has no destructor");
4861
4862 // -- any direct or virtual base class has a deleted destructor or
4863 // a destructor that is inaccessible from the defaulted destructor
4864 if (BaseDtor->isDeleted())
4865 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004866 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004867 AR_accessible)
4868 return true;
4869 }
4870
4871 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4872 FE = RD->field_end();
4873 FI != FE; ++FI) {
4874 QualType FieldType = Context.getBaseElementType(FI->getType());
4875 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4876 if (FieldRecord) {
4877 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4878 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4879 UE = FieldRecord->field_end();
4880 UI != UE; ++UI) {
4881 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4882 CXXRecordDecl *UnionFieldRecord =
4883 UnionFieldType->getAsCXXRecordDecl();
4884
4885 // -- X is a union-like class that has a variant member with a non-
4886 // trivial destructor.
4887 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4888 return true;
4889 }
4890 // Technically we are supposed to do this next check unconditionally.
4891 // But that makes absolutely no sense.
4892 } else {
4893 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4894
4895 // -- any of the non-static data members has class type M (or array
4896 // thereof) and M has a deleted destructor or a destructor that is
4897 // inaccessible from the defaulted destructor
4898 if (FieldDtor->isDeleted())
4899 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004900 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004901 AR_accessible)
4902 return true;
4903
4904 // -- X is a union-like class that has a variant member with a non-
4905 // trivial destructor.
4906 if (Union && !FieldDtor->isTrivial())
4907 return true;
4908 }
4909 }
4910 }
4911
4912 if (DD->isVirtual()) {
4913 FunctionDecl *OperatorDelete = 0;
4914 DeclarationName Name =
4915 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004916 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004917 false))
4918 return true;
4919 }
4920
4921
4922 return false;
4923}
4924
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004925/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004926namespace {
4927 struct FindHiddenVirtualMethodData {
4928 Sema *S;
4929 CXXMethodDecl *Method;
4930 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004931 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004932 };
4933}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004934
4935/// \brief Member lookup function that determines whether a given C++
4936/// method overloads virtual methods in a base class without overriding any,
4937/// to be used with CXXRecordDecl::lookupInBases().
4938static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4939 CXXBasePath &Path,
4940 void *UserData) {
4941 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4942
4943 FindHiddenVirtualMethodData &Data
4944 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4945
4946 DeclarationName Name = Data.Method->getDeclName();
4947 assert(Name.getNameKind() == DeclarationName::Identifier);
4948
4949 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004950 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004951 for (Path.Decls = BaseRecord->lookup(Name);
4952 Path.Decls.first != Path.Decls.second;
4953 ++Path.Decls.first) {
4954 NamedDecl *D = *Path.Decls.first;
4955 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004956 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004957 foundSameNameMethod = true;
4958 // Interested only in hidden virtual methods.
4959 if (!MD->isVirtual())
4960 continue;
4961 // If the method we are checking overrides a method from its base
4962 // don't warn about the other overloaded methods.
4963 if (!Data.S->IsOverload(Data.Method, MD, false))
4964 return true;
4965 // Collect the overload only if its hidden.
4966 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4967 overloadedMethods.push_back(MD);
4968 }
4969 }
4970
4971 if (foundSameNameMethod)
4972 Data.OverloadedMethods.append(overloadedMethods.begin(),
4973 overloadedMethods.end());
4974 return foundSameNameMethod;
4975}
4976
4977/// \brief See if a method overloads virtual methods in a base class without
4978/// overriding any.
4979void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4980 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004981 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004982 return;
4983 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4984 return;
4985
4986 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4987 /*bool RecordPaths=*/false,
4988 /*bool DetectVirtual=*/false);
4989 FindHiddenVirtualMethodData Data;
4990 Data.Method = MD;
4991 Data.S = this;
4992
4993 // Keep the base methods that were overriden or introduced in the subclass
4994 // by 'using' in a set. A base method not in this set is hidden.
4995 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4996 res.first != res.second; ++res.first) {
4997 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4998 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4999 E = MD->end_overridden_methods();
5000 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005001 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005002 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5003 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005004 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005005 }
5006
5007 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5008 !Data.OverloadedMethods.empty()) {
5009 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5010 << MD << (Data.OverloadedMethods.size() > 1);
5011
5012 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5013 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5014 Diag(overloadedMD->getLocation(),
5015 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5016 }
5017 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005018}
5019
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005020void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005021 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005022 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005023 SourceLocation RBrac,
5024 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005025 if (!TagDecl)
5026 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005027
Douglas Gregor42af25f2009-05-11 19:58:34 +00005028 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005029
David Blaikie77b6de02011-09-22 02:58:26 +00005030 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005031 // strict aliasing violation!
5032 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005033 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005034
Douglas Gregor23c94db2010-07-02 17:43:08 +00005035 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005036 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005037}
5038
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005039/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5040/// special functions, such as the default constructor, copy
5041/// constructor, or destructor, to the given C++ class (C++
5042/// [special]p1). This routine can only be executed just before the
5043/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005044void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005045 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005046 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005047
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005048 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005049 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005050
Richard Smithb701d3d2011-12-24 21:56:24 +00005051 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5052 ++ASTContext::NumImplicitMoveConstructors;
5053
Douglas Gregora376d102010-07-02 21:50:04 +00005054 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5055 ++ASTContext::NumImplicitCopyAssignmentOperators;
5056
5057 // If we have a dynamic class, then the copy assignment operator may be
5058 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5059 // it shows up in the right place in the vtable and that we diagnose
5060 // problems with the implicit exception specification.
5061 if (ClassDecl->isDynamicClass())
5062 DeclareImplicitCopyAssignment(ClassDecl);
5063 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005064
Richard Smithb701d3d2011-12-24 21:56:24 +00005065 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5066 ++ASTContext::NumImplicitMoveAssignmentOperators;
5067
5068 // Likewise for the move assignment operator.
5069 if (ClassDecl->isDynamicClass())
5070 DeclareImplicitMoveAssignment(ClassDecl);
5071 }
5072
Douglas Gregor4923aa22010-07-02 20:37:36 +00005073 if (!ClassDecl->hasUserDeclaredDestructor()) {
5074 ++ASTContext::NumImplicitDestructors;
5075
5076 // If we have a dynamic class, then the destructor may be virtual, so we
5077 // have to declare the destructor immediately. This ensures that, e.g., it
5078 // shows up in the right place in the vtable and that we diagnose problems
5079 // with the implicit exception specification.
5080 if (ClassDecl->isDynamicClass())
5081 DeclareImplicitDestructor(ClassDecl);
5082 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005083}
5084
Francois Pichet8387e2a2011-04-22 22:18:13 +00005085void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5086 if (!D)
5087 return;
5088
5089 int NumParamList = D->getNumTemplateParameterLists();
5090 for (int i = 0; i < NumParamList; i++) {
5091 TemplateParameterList* Params = D->getTemplateParameterList(i);
5092 for (TemplateParameterList::iterator Param = Params->begin(),
5093 ParamEnd = Params->end();
5094 Param != ParamEnd; ++Param) {
5095 NamedDecl *Named = cast<NamedDecl>(*Param);
5096 if (Named->getDeclName()) {
5097 S->AddDecl(Named);
5098 IdResolver.AddDecl(Named);
5099 }
5100 }
5101 }
5102}
5103
John McCalld226f652010-08-21 09:40:31 +00005104void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005105 if (!D)
5106 return;
5107
5108 TemplateParameterList *Params = 0;
5109 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5110 Params = Template->getTemplateParameters();
5111 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5112 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5113 Params = PartialSpec->getTemplateParameters();
5114 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005115 return;
5116
Douglas Gregor6569d682009-05-27 23:11:45 +00005117 for (TemplateParameterList::iterator Param = Params->begin(),
5118 ParamEnd = Params->end();
5119 Param != ParamEnd; ++Param) {
5120 NamedDecl *Named = cast<NamedDecl>(*Param);
5121 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005122 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005123 IdResolver.AddDecl(Named);
5124 }
5125 }
5126}
5127
John McCalld226f652010-08-21 09:40:31 +00005128void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005129 if (!RecordD) return;
5130 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005131 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005132 PushDeclContext(S, Record);
5133}
5134
John McCalld226f652010-08-21 09:40:31 +00005135void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005136 if (!RecordD) return;
5137 PopDeclContext();
5138}
5139
Douglas Gregor72b505b2008-12-16 21:30:33 +00005140/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5141/// parsing a top-level (non-nested) C++ class, and we are now
5142/// parsing those parts of the given Method declaration that could
5143/// not be parsed earlier (C++ [class.mem]p2), such as default
5144/// arguments. This action should enter the scope of the given
5145/// Method declaration as if we had just parsed the qualified method
5146/// name. However, it should not bring the parameters into scope;
5147/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005148void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005149}
5150
5151/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5152/// C++ method declaration. We're (re-)introducing the given
5153/// function parameter into scope for use in parsing later parts of
5154/// the method declaration. For example, we could see an
5155/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005156void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005157 if (!ParamD)
5158 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005159
John McCalld226f652010-08-21 09:40:31 +00005160 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005161
5162 // If this parameter has an unparsed default argument, clear it out
5163 // to make way for the parsed default argument.
5164 if (Param->hasUnparsedDefaultArg())
5165 Param->setDefaultArg(0);
5166
John McCalld226f652010-08-21 09:40:31 +00005167 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005168 if (Param->getDeclName())
5169 IdResolver.AddDecl(Param);
5170}
5171
5172/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5173/// processing the delayed method declaration for Method. The method
5174/// declaration is now considered finished. There may be a separate
5175/// ActOnStartOfFunctionDef action later (not necessarily
5176/// immediately!) for this method, if it was also defined inside the
5177/// class body.
John McCalld226f652010-08-21 09:40:31 +00005178void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005179 if (!MethodD)
5180 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005181
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005182 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005183
John McCalld226f652010-08-21 09:40:31 +00005184 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005185
5186 // Now that we have our default arguments, check the constructor
5187 // again. It could produce additional diagnostics or affect whether
5188 // the class has implicitly-declared destructors, among other
5189 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005190 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5191 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005192
5193 // Check the default arguments, which we may have added.
5194 if (!Method->isInvalidDecl())
5195 CheckCXXDefaultArguments(Method);
5196}
5197
Douglas Gregor42a552f2008-11-05 20:51:48 +00005198/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005199/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005200/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005201/// emit diagnostics and set the invalid bit to true. In any case, the type
5202/// will be updated to reflect a well-formed type for the constructor and
5203/// returned.
5204QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005205 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005206 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005207
5208 // C++ [class.ctor]p3:
5209 // A constructor shall not be virtual (10.3) or static (9.4). A
5210 // constructor can be invoked for a const, volatile or const
5211 // volatile object. A constructor shall not be declared const,
5212 // volatile, or const volatile (9.3.2).
5213 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005214 if (!D.isInvalidType())
5215 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5216 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5217 << SourceRange(D.getIdentifierLoc());
5218 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005219 }
John McCalld931b082010-08-26 03:08:43 +00005220 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005221 if (!D.isInvalidType())
5222 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5223 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5224 << SourceRange(D.getIdentifierLoc());
5225 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005226 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005227 }
Mike Stump1eb44332009-09-09 15:08:12 +00005228
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005229 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005230 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005231 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005232 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5233 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005234 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005235 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5236 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005237 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005238 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5239 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005240 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005241 }
Mike Stump1eb44332009-09-09 15:08:12 +00005242
Douglas Gregorc938c162011-01-26 05:01:58 +00005243 // C++0x [class.ctor]p4:
5244 // A constructor shall not be declared with a ref-qualifier.
5245 if (FTI.hasRefQualifier()) {
5246 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5247 << FTI.RefQualifierIsLValueRef
5248 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5249 D.setInvalidType();
5250 }
5251
Douglas Gregor42a552f2008-11-05 20:51:48 +00005252 // Rebuild the function type "R" without any type qualifiers (in
5253 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005254 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005255 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005256 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5257 return R;
5258
5259 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5260 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005261 EPI.RefQualifier = RQ_None;
5262
Chris Lattner65401802009-04-25 08:28:21 +00005263 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005264 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005265}
5266
Douglas Gregor72b505b2008-12-16 21:30:33 +00005267/// CheckConstructor - Checks a fully-formed constructor for
5268/// well-formedness, issuing any diagnostics required. Returns true if
5269/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005270void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005271 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005272 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5273 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005274 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005275
5276 // C++ [class.copy]p3:
5277 // A declaration of a constructor for a class X is ill-formed if
5278 // its first parameter is of type (optionally cv-qualified) X and
5279 // either there are no other parameters or else all other
5280 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005281 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005282 ((Constructor->getNumParams() == 1) ||
5283 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005284 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5285 Constructor->getTemplateSpecializationKind()
5286 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005287 QualType ParamType = Constructor->getParamDecl(0)->getType();
5288 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5289 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005290 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005291 const char *ConstRef
5292 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5293 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005294 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005295 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005296
5297 // FIXME: Rather that making the constructor invalid, we should endeavor
5298 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005299 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005300 }
5301 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005302}
5303
John McCall15442822010-08-04 01:04:25 +00005304/// CheckDestructor - Checks a fully-formed destructor definition for
5305/// well-formedness, issuing any diagnostics required. Returns true
5306/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005307bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005308 CXXRecordDecl *RD = Destructor->getParent();
5309
5310 if (Destructor->isVirtual()) {
5311 SourceLocation Loc;
5312
5313 if (!Destructor->isImplicit())
5314 Loc = Destructor->getLocation();
5315 else
5316 Loc = RD->getLocation();
5317
5318 // If we have a virtual destructor, look up the deallocation function
5319 FunctionDecl *OperatorDelete = 0;
5320 DeclarationName Name =
5321 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005322 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005323 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005324
Eli Friedman5f2987c2012-02-02 03:46:19 +00005325 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005326
5327 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005328 }
Anders Carlsson37909802009-11-30 21:24:50 +00005329
5330 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005331}
5332
Mike Stump1eb44332009-09-09 15:08:12 +00005333static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005334FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5335 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5336 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005337 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005338}
5339
Douglas Gregor42a552f2008-11-05 20:51:48 +00005340/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5341/// the well-formednes of the destructor declarator @p D with type @p
5342/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005343/// emit diagnostics and set the declarator to invalid. Even if this happens,
5344/// will be updated to reflect a well-formed type for the destructor and
5345/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005346QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005347 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005348 // C++ [class.dtor]p1:
5349 // [...] A typedef-name that names a class is a class-name
5350 // (7.1.3); however, a typedef-name that names a class shall not
5351 // be used as the identifier in the declarator for a destructor
5352 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005353 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005354 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005355 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005356 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005357 else if (const TemplateSpecializationType *TST =
5358 DeclaratorType->getAs<TemplateSpecializationType>())
5359 if (TST->isTypeAlias())
5360 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5361 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005362
5363 // C++ [class.dtor]p2:
5364 // A destructor is used to destroy objects of its class type. A
5365 // destructor takes no parameters, and no return type can be
5366 // specified for it (not even void). The address of a destructor
5367 // shall not be taken. A destructor shall not be static. A
5368 // destructor can be invoked for a const, volatile or const
5369 // volatile object. A destructor shall not be declared const,
5370 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005371 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005372 if (!D.isInvalidType())
5373 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5374 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005375 << SourceRange(D.getIdentifierLoc())
5376 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5377
John McCalld931b082010-08-26 03:08:43 +00005378 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005379 }
Chris Lattner65401802009-04-25 08:28:21 +00005380 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005381 // Destructors don't have return types, but the parser will
5382 // happily parse something like:
5383 //
5384 // class X {
5385 // float ~X();
5386 // };
5387 //
5388 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005389 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5390 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5391 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005392 }
Mike Stump1eb44332009-09-09 15:08:12 +00005393
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005394 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005395 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005396 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005397 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5398 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005399 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005400 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5401 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005402 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005403 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5404 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005405 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005406 }
5407
Douglas Gregorc938c162011-01-26 05:01:58 +00005408 // C++0x [class.dtor]p2:
5409 // A destructor shall not be declared with a ref-qualifier.
5410 if (FTI.hasRefQualifier()) {
5411 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5412 << FTI.RefQualifierIsLValueRef
5413 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5414 D.setInvalidType();
5415 }
5416
Douglas Gregor42a552f2008-11-05 20:51:48 +00005417 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005418 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005419 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5420
5421 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005422 FTI.freeArgs();
5423 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005424 }
5425
Mike Stump1eb44332009-09-09 15:08:12 +00005426 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005427 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005428 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005429 D.setInvalidType();
5430 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005431
5432 // Rebuild the function type "R" without any type qualifiers or
5433 // parameters (in case any of the errors above fired) and with
5434 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005435 // types.
John McCalle23cf432010-12-14 08:05:40 +00005436 if (!D.isInvalidType())
5437 return R;
5438
Douglas Gregord92ec472010-07-01 05:10:53 +00005439 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005440 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5441 EPI.Variadic = false;
5442 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005443 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005444 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005445}
5446
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005447/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5448/// well-formednes of the conversion function declarator @p D with
5449/// type @p R. If there are any errors in the declarator, this routine
5450/// will emit diagnostics and return true. Otherwise, it will return
5451/// false. Either way, the type @p R will be updated to reflect a
5452/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005453void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005454 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005455 // C++ [class.conv.fct]p1:
5456 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005457 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005458 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005459 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005460 if (!D.isInvalidType())
5461 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5462 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5463 << SourceRange(D.getIdentifierLoc());
5464 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005465 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005466 }
John McCalla3f81372010-04-13 00:04:31 +00005467
5468 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5469
Chris Lattner6e475012009-04-25 08:35:12 +00005470 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005471 // Conversion functions don't have return types, but the parser will
5472 // happily parse something like:
5473 //
5474 // class X {
5475 // float operator bool();
5476 // };
5477 //
5478 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005479 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5480 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5481 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005482 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005483 }
5484
John McCalla3f81372010-04-13 00:04:31 +00005485 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5486
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005487 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005488 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005489 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5490
5491 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005492 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005493 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005494 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005495 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005496 D.setInvalidType();
5497 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005498
John McCalla3f81372010-04-13 00:04:31 +00005499 // Diagnose "&operator bool()" and other such nonsense. This
5500 // is actually a gcc extension which we don't support.
5501 if (Proto->getResultType() != ConvType) {
5502 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5503 << Proto->getResultType();
5504 D.setInvalidType();
5505 ConvType = Proto->getResultType();
5506 }
5507
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005508 // C++ [class.conv.fct]p4:
5509 // The conversion-type-id shall not represent a function type nor
5510 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005511 if (ConvType->isArrayType()) {
5512 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5513 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005514 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005515 } else if (ConvType->isFunctionType()) {
5516 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5517 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005518 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005519 }
5520
5521 // Rebuild the function type "R" without any parameters (in case any
5522 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005523 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005524 if (D.isInvalidType())
5525 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005526
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005527 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005528 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005529 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005530 getLangOptions().CPlusPlus0x ?
5531 diag::warn_cxx98_compat_explicit_conversion_functions :
5532 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005533 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005534}
5535
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005536/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5537/// the declaration of the given C++ conversion function. This routine
5538/// is responsible for recording the conversion function in the C++
5539/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005540Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005541 assert(Conversion && "Expected to receive a conversion function declaration");
5542
Douglas Gregor9d350972008-12-12 08:25:50 +00005543 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005544
5545 // Make sure we aren't redeclaring the conversion function.
5546 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005547
5548 // C++ [class.conv.fct]p1:
5549 // [...] A conversion function is never used to convert a
5550 // (possibly cv-qualified) object to the (possibly cv-qualified)
5551 // same object type (or a reference to it), to a (possibly
5552 // cv-qualified) base class of that type (or a reference to it),
5553 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005554 // FIXME: Suppress this warning if the conversion function ends up being a
5555 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005556 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005557 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005558 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005559 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005560 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5561 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005562 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005563 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005564 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5565 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005566 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005567 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005568 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005569 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005570 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005571 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005572 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005573 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005574 }
5575
Douglas Gregore80622f2010-09-29 04:25:11 +00005576 if (FunctionTemplateDecl *ConversionTemplate
5577 = Conversion->getDescribedFunctionTemplate())
5578 return ConversionTemplate;
5579
John McCalld226f652010-08-21 09:40:31 +00005580 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005581}
5582
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005583//===----------------------------------------------------------------------===//
5584// Namespace Handling
5585//===----------------------------------------------------------------------===//
5586
John McCallea318642010-08-26 09:15:37 +00005587
5588
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005589/// ActOnStartNamespaceDef - This is called at the start of a namespace
5590/// definition.
John McCalld226f652010-08-21 09:40:31 +00005591Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005592 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005593 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005594 SourceLocation IdentLoc,
5595 IdentifierInfo *II,
5596 SourceLocation LBrace,
5597 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005598 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5599 // For anonymous namespace, take the location of the left brace.
5600 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005601 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005602 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005603 bool IsStd = false;
5604 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005605 Scope *DeclRegionScope = NamespcScope->getParent();
5606
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005607 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005608 if (II) {
5609 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005610 // The identifier in an original-namespace-definition shall not
5611 // have been previously defined in the declarative region in
5612 // which the original-namespace-definition appears. The
5613 // identifier in an original-namespace-definition is the name of
5614 // the namespace. Subsequently in that declarative region, it is
5615 // treated as an original-namespace-name.
5616 //
5617 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005618 // look through using directives, just look for any ordinary names.
5619
5620 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005621 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5622 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005623 NamedDecl *PrevDecl = 0;
5624 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005625 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005626 R.first != R.second; ++R.first) {
5627 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5628 PrevDecl = *R.first;
5629 break;
5630 }
5631 }
5632
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005633 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5634
5635 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005636 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005637 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005638 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005639 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005640 // The user probably just forgot the 'inline', so suggest that it
5641 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005642 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005643 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5644 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005645 Diag(Loc, diag::err_inline_namespace_mismatch)
5646 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005647 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005648 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5649
5650 IsInline = PrevNS->isInline();
5651 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005652 } else if (PrevDecl) {
5653 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005654 Diag(Loc, diag::err_redefinition_different_kind)
5655 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005656 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005657 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005658 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005659 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005660 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005661 // This is the first "real" definition of the namespace "std", so update
5662 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005663 PrevNS = getStdNamespace();
5664 IsStd = true;
5665 AddToKnown = !IsInline;
5666 } else {
5667 // We've seen this namespace for the first time.
5668 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005669 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005670 } else {
John McCall9aeed322009-10-01 00:25:31 +00005671 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005672
5673 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005674 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005675 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005676 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005677 } else {
5678 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005679 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005680 }
5681
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005682 if (PrevNS && IsInline != PrevNS->isInline()) {
5683 // inline-ness must match
5684 Diag(Loc, diag::err_inline_namespace_mismatch)
5685 << IsInline;
5686 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005687
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005688 // Recover by ignoring the new namespace's inline status.
5689 IsInline = PrevNS->isInline();
5690 }
5691 }
5692
5693 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5694 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005695 if (IsInvalid)
5696 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005697
5698 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005699
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005700 // FIXME: Should we be merging attributes?
5701 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005702 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005703
5704 if (IsStd)
5705 StdNamespace = Namespc;
5706 if (AddToKnown)
5707 KnownNamespaces[Namespc] = false;
5708
5709 if (II) {
5710 PushOnScopeChains(Namespc, DeclRegionScope);
5711 } else {
5712 // Link the anonymous namespace into its parent.
5713 DeclContext *Parent = CurContext->getRedeclContext();
5714 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5715 TU->setAnonymousNamespace(Namespc);
5716 } else {
5717 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005718 }
John McCall9aeed322009-10-01 00:25:31 +00005719
Douglas Gregora4181472010-03-24 00:46:35 +00005720 CurContext->addDecl(Namespc);
5721
John McCall9aeed322009-10-01 00:25:31 +00005722 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5723 // behaves as if it were replaced by
5724 // namespace unique { /* empty body */ }
5725 // using namespace unique;
5726 // namespace unique { namespace-body }
5727 // where all occurrences of 'unique' in a translation unit are
5728 // replaced by the same identifier and this identifier differs
5729 // from all other identifiers in the entire program.
5730
5731 // We just create the namespace with an empty name and then add an
5732 // implicit using declaration, just like the standard suggests.
5733 //
5734 // CodeGen enforces the "universally unique" aspect by giving all
5735 // declarations semantically contained within an anonymous
5736 // namespace internal linkage.
5737
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005738 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005739 UsingDirectiveDecl* UD
5740 = UsingDirectiveDecl::Create(Context, CurContext,
5741 /* 'using' */ LBrace,
5742 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005743 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005744 /* identifier */ SourceLocation(),
5745 Namespc,
5746 /* Ancestor */ CurContext);
5747 UD->setImplicit();
5748 CurContext->addDecl(UD);
5749 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005750 }
5751
5752 // Although we could have an invalid decl (i.e. the namespace name is a
5753 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005754 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5755 // for the namespace has the declarations that showed up in that particular
5756 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005757 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005758 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005759}
5760
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005761/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5762/// is a namespace alias, returns the namespace it points to.
5763static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5764 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5765 return AD->getNamespace();
5766 return dyn_cast_or_null<NamespaceDecl>(D);
5767}
5768
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005769/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5770/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005771void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005772 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5773 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005774 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005775 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005776 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005777 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005778}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005779
John McCall384aff82010-08-25 07:42:41 +00005780CXXRecordDecl *Sema::getStdBadAlloc() const {
5781 return cast_or_null<CXXRecordDecl>(
5782 StdBadAlloc.get(Context.getExternalSource()));
5783}
5784
5785NamespaceDecl *Sema::getStdNamespace() const {
5786 return cast_or_null<NamespaceDecl>(
5787 StdNamespace.get(Context.getExternalSource()));
5788}
5789
Douglas Gregor66992202010-06-29 17:53:46 +00005790/// \brief Retrieve the special "std" namespace, which may require us to
5791/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005792NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005793 if (!StdNamespace) {
5794 // The "std" namespace has not yet been defined, so build one implicitly.
5795 StdNamespace = NamespaceDecl::Create(Context,
5796 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005797 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005798 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005799 &PP.getIdentifierTable().get("std"),
5800 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005801 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005802 }
5803
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005804 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005805}
5806
Sebastian Redl395e04d2012-01-17 22:49:33 +00005807bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5808 assert(getLangOptions().CPlusPlus &&
5809 "Looking for std::initializer_list outside of C++.");
5810
5811 // We're looking for implicit instantiations of
5812 // template <typename E> class std::initializer_list.
5813
5814 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5815 return false;
5816
Sebastian Redl84760e32012-01-17 22:49:58 +00005817 ClassTemplateDecl *Template = 0;
5818 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005819
Sebastian Redl84760e32012-01-17 22:49:58 +00005820 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005821
Sebastian Redl84760e32012-01-17 22:49:58 +00005822 ClassTemplateSpecializationDecl *Specialization =
5823 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5824 if (!Specialization)
5825 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005826
Sebastian Redl84760e32012-01-17 22:49:58 +00005827 Template = Specialization->getSpecializedTemplate();
5828 Arguments = Specialization->getTemplateArgs().data();
5829 } else if (const TemplateSpecializationType *TST =
5830 Ty->getAs<TemplateSpecializationType>()) {
5831 Template = dyn_cast_or_null<ClassTemplateDecl>(
5832 TST->getTemplateName().getAsTemplateDecl());
5833 Arguments = TST->getArgs();
5834 }
5835 if (!Template)
5836 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005837
5838 if (!StdInitializerList) {
5839 // Haven't recognized std::initializer_list yet, maybe this is it.
5840 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5841 if (TemplateClass->getIdentifier() !=
5842 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005843 !getStdNamespace()->InEnclosingNamespaceSetOf(
5844 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005845 return false;
5846 // This is a template called std::initializer_list, but is it the right
5847 // template?
5848 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005849 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005850 return false;
5851 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5852 return false;
5853
5854 // It's the right template.
5855 StdInitializerList = Template;
5856 }
5857
5858 if (Template != StdInitializerList)
5859 return false;
5860
5861 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005862 if (Element)
5863 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005864 return true;
5865}
5866
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005867static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5868 NamespaceDecl *Std = S.getStdNamespace();
5869 if (!Std) {
5870 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5871 return 0;
5872 }
5873
5874 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5875 Loc, Sema::LookupOrdinaryName);
5876 if (!S.LookupQualifiedName(Result, Std)) {
5877 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5878 return 0;
5879 }
5880 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5881 if (!Template) {
5882 Result.suppressDiagnostics();
5883 // We found something weird. Complain about the first thing we found.
5884 NamedDecl *Found = *Result.begin();
5885 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5886 return 0;
5887 }
5888
5889 // We found some template called std::initializer_list. Now verify that it's
5890 // correct.
5891 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005892 if (Params->getMinRequiredArguments() != 1 ||
5893 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005894 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5895 return 0;
5896 }
5897
5898 return Template;
5899}
5900
5901QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5902 if (!StdInitializerList) {
5903 StdInitializerList = LookupStdInitializerList(*this, Loc);
5904 if (!StdInitializerList)
5905 return QualType();
5906 }
5907
5908 TemplateArgumentListInfo Args(Loc, Loc);
5909 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5910 Context.getTrivialTypeSourceInfo(Element,
5911 Loc)));
5912 return Context.getCanonicalType(
5913 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5914}
5915
Sebastian Redl98d36062012-01-17 22:50:14 +00005916bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5917 // C++ [dcl.init.list]p2:
5918 // A constructor is an initializer-list constructor if its first parameter
5919 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5920 // std::initializer_list<E> for some type E, and either there are no other
5921 // parameters or else all other parameters have default arguments.
5922 if (Ctor->getNumParams() < 1 ||
5923 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5924 return false;
5925
5926 QualType ArgType = Ctor->getParamDecl(0)->getType();
5927 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5928 ArgType = RT->getPointeeType().getUnqualifiedType();
5929
5930 return isStdInitializerList(ArgType, 0);
5931}
5932
Douglas Gregor9172aa62011-03-26 22:25:30 +00005933/// \brief Determine whether a using statement is in a context where it will be
5934/// apply in all contexts.
5935static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5936 switch (CurContext->getDeclKind()) {
5937 case Decl::TranslationUnit:
5938 return true;
5939 case Decl::LinkageSpec:
5940 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5941 default:
5942 return false;
5943 }
5944}
5945
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005946namespace {
5947
5948// Callback to only accept typo corrections that are namespaces.
5949class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5950 public:
5951 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5952 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5953 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5954 }
5955 return false;
5956 }
5957};
5958
5959}
5960
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005961static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5962 CXXScopeSpec &SS,
5963 SourceLocation IdentLoc,
5964 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005965 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005966 R.clear();
5967 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005968 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005969 Validator)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005970 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5971 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5972 if (DeclContext *DC = S.computeDeclContext(SS, false))
5973 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5974 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5975 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5976 else
5977 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5978 << Ident << CorrectedQuotedStr
5979 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005980
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005981 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5982 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005983
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005984 Ident = Corrected.getCorrectionAsIdentifierInfo();
5985 R.addDecl(Corrected.getCorrectionDecl());
5986 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005987 }
5988 return false;
5989}
5990
John McCalld226f652010-08-21 09:40:31 +00005991Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005992 SourceLocation UsingLoc,
5993 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005994 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005995 SourceLocation IdentLoc,
5996 IdentifierInfo *NamespcName,
5997 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005998 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5999 assert(NamespcName && "Invalid NamespcName.");
6000 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006001
6002 // This can only happen along a recovery path.
6003 while (S->getFlags() & Scope::TemplateParamScope)
6004 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006005 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006006
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006007 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006008 NestedNameSpecifier *Qualifier = 0;
6009 if (SS.isSet())
6010 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6011
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006012 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006013 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6014 LookupParsedName(R, S, &SS);
6015 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006016 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006017
Douglas Gregor66992202010-06-29 17:53:46 +00006018 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006019 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006020 // Allow "using namespace std;" or "using namespace ::std;" even if
6021 // "std" hasn't been defined yet, for GCC compatibility.
6022 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6023 NamespcName->isStr("std")) {
6024 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006025 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006026 R.resolveKind();
6027 }
6028 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006029 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006030 }
6031
John McCallf36e02d2009-10-09 21:13:30 +00006032 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006033 NamedDecl *Named = R.getFoundDecl();
6034 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6035 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006036 // C++ [namespace.udir]p1:
6037 // A using-directive specifies that the names in the nominated
6038 // namespace can be used in the scope in which the
6039 // using-directive appears after the using-directive. During
6040 // unqualified name lookup (3.4.1), the names appear as if they
6041 // were declared in the nearest enclosing namespace which
6042 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006043 // namespace. [Note: in this context, "contains" means "contains
6044 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006045
6046 // Find enclosing context containing both using-directive and
6047 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006048 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006049 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6050 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6051 CommonAncestor = CommonAncestor->getParent();
6052
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006053 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006054 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006055 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006056
Douglas Gregor9172aa62011-03-26 22:25:30 +00006057 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006058 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006059 Diag(IdentLoc, diag::warn_using_directive_in_header);
6060 }
6061
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006062 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006063 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006064 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006065 }
6066
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006067 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006068 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006069}
6070
6071void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6072 // If scope has associated entity, then using directive is at namespace
6073 // or translation unit scope. We add UsingDirectiveDecls, into
6074 // it's lookup structure.
6075 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006076 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006077 else
6078 // Otherwise it is block-sope. using-directives will affect lookup
6079 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00006080 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006081}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006082
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006083
John McCalld226f652010-08-21 09:40:31 +00006084Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006085 AccessSpecifier AS,
6086 bool HasUsingKeyword,
6087 SourceLocation UsingLoc,
6088 CXXScopeSpec &SS,
6089 UnqualifiedId &Name,
6090 AttributeList *AttrList,
6091 bool IsTypeName,
6092 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006093 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006094
Douglas Gregor12c118a2009-11-04 16:30:06 +00006095 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006096 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006097 case UnqualifiedId::IK_Identifier:
6098 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006099 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006100 case UnqualifiedId::IK_ConversionFunctionId:
6101 break;
6102
6103 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006104 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00006105 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00006106 Diag(Name.getSourceRange().getBegin(),
6107 getLangOptions().CPlusPlus0x ?
6108 diag::warn_cxx98_compat_using_decl_constructor :
6109 diag::err_using_decl_constructor)
6110 << SS.getRange();
6111
John McCall604e7f12009-12-08 07:46:18 +00006112 if (getLangOptions().CPlusPlus0x) break;
6113
John McCalld226f652010-08-21 09:40:31 +00006114 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006115
6116 case UnqualifiedId::IK_DestructorName:
6117 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6118 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006119 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006120
6121 case UnqualifiedId::IK_TemplateId:
6122 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6123 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006124 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006125 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006126
6127 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6128 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006129 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006130 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006131
John McCall60fa3cf2009-12-11 02:10:03 +00006132 // Warn about using declarations.
6133 // TODO: store that the declaration was written without 'using' and
6134 // talk about access decls instead of using decls in the
6135 // diagnostics.
6136 if (!HasUsingKeyword) {
6137 UsingLoc = Name.getSourceRange().getBegin();
6138
6139 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006140 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006141 }
6142
Douglas Gregor56c04582010-12-16 00:46:58 +00006143 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6144 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6145 return 0;
6146
John McCall9488ea12009-11-17 05:59:44 +00006147 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006148 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006149 /* IsInstantiation */ false,
6150 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006151 if (UD)
6152 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006153
John McCalld226f652010-08-21 09:40:31 +00006154 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006155}
6156
Douglas Gregor09acc982010-07-07 23:08:52 +00006157/// \brief Determine whether a using declaration considers the given
6158/// declarations as "equivalent", e.g., if they are redeclarations of
6159/// the same entity or are both typedefs of the same type.
6160static bool
6161IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6162 bool &SuppressRedeclaration) {
6163 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6164 SuppressRedeclaration = false;
6165 return true;
6166 }
6167
Richard Smith162e1c12011-04-15 14:24:37 +00006168 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6169 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006170 SuppressRedeclaration = true;
6171 return Context.hasSameType(TD1->getUnderlyingType(),
6172 TD2->getUnderlyingType());
6173 }
6174
6175 return false;
6176}
6177
6178
John McCall9f54ad42009-12-10 09:41:52 +00006179/// Determines whether to create a using shadow decl for a particular
6180/// decl, given the set of decls existing prior to this using lookup.
6181bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6182 const LookupResult &Previous) {
6183 // Diagnose finding a decl which is not from a base class of the
6184 // current class. We do this now because there are cases where this
6185 // function will silently decide not to build a shadow decl, which
6186 // will pre-empt further diagnostics.
6187 //
6188 // We don't need to do this in C++0x because we do the check once on
6189 // the qualifier.
6190 //
6191 // FIXME: diagnose the following if we care enough:
6192 // struct A { int foo; };
6193 // struct B : A { using A::foo; };
6194 // template <class T> struct C : A {};
6195 // template <class T> struct D : C<T> { using B::foo; } // <---
6196 // This is invalid (during instantiation) in C++03 because B::foo
6197 // resolves to the using decl in B, which is not a base class of D<T>.
6198 // We can't diagnose it immediately because C<T> is an unknown
6199 // specialization. The UsingShadowDecl in D<T> then points directly
6200 // to A::foo, which will look well-formed when we instantiate.
6201 // The right solution is to not collapse the shadow-decl chain.
6202 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6203 DeclContext *OrigDC = Orig->getDeclContext();
6204
6205 // Handle enums and anonymous structs.
6206 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6207 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6208 while (OrigRec->isAnonymousStructOrUnion())
6209 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6210
6211 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6212 if (OrigDC == CurContext) {
6213 Diag(Using->getLocation(),
6214 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006215 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006216 Diag(Orig->getLocation(), diag::note_using_decl_target);
6217 return true;
6218 }
6219
Douglas Gregordc355712011-02-25 00:36:19 +00006220 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006221 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006222 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006223 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006224 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006225 Diag(Orig->getLocation(), diag::note_using_decl_target);
6226 return true;
6227 }
6228 }
6229
6230 if (Previous.empty()) return false;
6231
6232 NamedDecl *Target = Orig;
6233 if (isa<UsingShadowDecl>(Target))
6234 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6235
John McCalld7533ec2009-12-11 02:33:26 +00006236 // If the target happens to be one of the previous declarations, we
6237 // don't have a conflict.
6238 //
6239 // FIXME: but we might be increasing its access, in which case we
6240 // should redeclare it.
6241 NamedDecl *NonTag = 0, *Tag = 0;
6242 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6243 I != E; ++I) {
6244 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006245 bool Result;
6246 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6247 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006248
6249 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6250 }
6251
John McCall9f54ad42009-12-10 09:41:52 +00006252 if (Target->isFunctionOrFunctionTemplate()) {
6253 FunctionDecl *FD;
6254 if (isa<FunctionTemplateDecl>(Target))
6255 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6256 else
6257 FD = cast<FunctionDecl>(Target);
6258
6259 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006260 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006261 case Ovl_Overload:
6262 return false;
6263
6264 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006265 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006266 break;
6267
6268 // We found a decl with the exact signature.
6269 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006270 // If we're in a record, we want to hide the target, so we
6271 // return true (without a diagnostic) to tell the caller not to
6272 // build a shadow decl.
6273 if (CurContext->isRecord())
6274 return true;
6275
6276 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006277 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006278 break;
6279 }
6280
6281 Diag(Target->getLocation(), diag::note_using_decl_target);
6282 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6283 return true;
6284 }
6285
6286 // Target is not a function.
6287
John McCall9f54ad42009-12-10 09:41:52 +00006288 if (isa<TagDecl>(Target)) {
6289 // No conflict between a tag and a non-tag.
6290 if (!Tag) return false;
6291
John McCall41ce66f2009-12-10 19:51:03 +00006292 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006293 Diag(Target->getLocation(), diag::note_using_decl_target);
6294 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6295 return true;
6296 }
6297
6298 // No conflict between a tag and a non-tag.
6299 if (!NonTag) return false;
6300
John McCall41ce66f2009-12-10 19:51:03 +00006301 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006302 Diag(Target->getLocation(), diag::note_using_decl_target);
6303 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6304 return true;
6305}
6306
John McCall9488ea12009-11-17 05:59:44 +00006307/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006308UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006309 UsingDecl *UD,
6310 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006311
6312 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006313 NamedDecl *Target = Orig;
6314 if (isa<UsingShadowDecl>(Target)) {
6315 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6316 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006317 }
6318
6319 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006320 = UsingShadowDecl::Create(Context, CurContext,
6321 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006322 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006323
6324 Shadow->setAccess(UD->getAccess());
6325 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6326 Shadow->setInvalidDecl();
6327
John McCall9488ea12009-11-17 05:59:44 +00006328 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006329 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006330 else
John McCall604e7f12009-12-08 07:46:18 +00006331 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006332
John McCall604e7f12009-12-08 07:46:18 +00006333
John McCall9f54ad42009-12-10 09:41:52 +00006334 return Shadow;
6335}
John McCall604e7f12009-12-08 07:46:18 +00006336
John McCall9f54ad42009-12-10 09:41:52 +00006337/// Hides a using shadow declaration. This is required by the current
6338/// using-decl implementation when a resolvable using declaration in a
6339/// class is followed by a declaration which would hide or override
6340/// one or more of the using decl's targets; for example:
6341///
6342/// struct Base { void foo(int); };
6343/// struct Derived : Base {
6344/// using Base::foo;
6345/// void foo(int);
6346/// };
6347///
6348/// The governing language is C++03 [namespace.udecl]p12:
6349///
6350/// When a using-declaration brings names from a base class into a
6351/// derived class scope, member functions in the derived class
6352/// override and/or hide member functions with the same name and
6353/// parameter types in a base class (rather than conflicting).
6354///
6355/// There are two ways to implement this:
6356/// (1) optimistically create shadow decls when they're not hidden
6357/// by existing declarations, or
6358/// (2) don't create any shadow decls (or at least don't make them
6359/// visible) until we've fully parsed/instantiated the class.
6360/// The problem with (1) is that we might have to retroactively remove
6361/// a shadow decl, which requires several O(n) operations because the
6362/// decl structures are (very reasonably) not designed for removal.
6363/// (2) avoids this but is very fiddly and phase-dependent.
6364void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006365 if (Shadow->getDeclName().getNameKind() ==
6366 DeclarationName::CXXConversionFunctionName)
6367 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6368
John McCall9f54ad42009-12-10 09:41:52 +00006369 // Remove it from the DeclContext...
6370 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006371
John McCall9f54ad42009-12-10 09:41:52 +00006372 // ...and the scope, if applicable...
6373 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006374 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006375 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006376 }
6377
John McCall9f54ad42009-12-10 09:41:52 +00006378 // ...and the using decl.
6379 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6380
6381 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006382 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006383}
6384
John McCall7ba107a2009-11-18 02:36:19 +00006385/// Builds a using declaration.
6386///
6387/// \param IsInstantiation - Whether this call arises from an
6388/// instantiation of an unresolved using declaration. We treat
6389/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006390NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6391 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006392 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006393 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006394 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006395 bool IsInstantiation,
6396 bool IsTypeName,
6397 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006398 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006399 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006400 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006401
Anders Carlsson550b14b2009-08-28 05:49:21 +00006402 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006403
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006404 if (SS.isEmpty()) {
6405 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006406 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006407 }
Mike Stump1eb44332009-09-09 15:08:12 +00006408
John McCall9f54ad42009-12-10 09:41:52 +00006409 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006410 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006411 ForRedeclaration);
6412 Previous.setHideTags(false);
6413 if (S) {
6414 LookupName(Previous, S);
6415
6416 // It is really dumb that we have to do this.
6417 LookupResult::Filter F = Previous.makeFilter();
6418 while (F.hasNext()) {
6419 NamedDecl *D = F.next();
6420 if (!isDeclInScope(D, CurContext, S))
6421 F.erase();
6422 }
6423 F.done();
6424 } else {
6425 assert(IsInstantiation && "no scope in non-instantiation");
6426 assert(CurContext->isRecord() && "scope not record in instantiation");
6427 LookupQualifiedName(Previous, CurContext);
6428 }
6429
John McCall9f54ad42009-12-10 09:41:52 +00006430 // Check for invalid redeclarations.
6431 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6432 return 0;
6433
6434 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006435 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6436 return 0;
6437
John McCallaf8e6ed2009-11-12 03:15:40 +00006438 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006439 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006440 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006441 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006442 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006443 // FIXME: not all declaration name kinds are legal here
6444 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6445 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006446 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006447 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006448 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006449 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6450 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006451 }
John McCalled976492009-12-04 22:46:56 +00006452 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006453 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6454 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006455 }
John McCalled976492009-12-04 22:46:56 +00006456 D->setAccess(AS);
6457 CurContext->addDecl(D);
6458
6459 if (!LookupContext) return D;
6460 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006461
John McCall77bb1aa2010-05-01 00:40:08 +00006462 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006463 UD->setInvalidDecl();
6464 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006465 }
6466
Sebastian Redlf677ea32011-02-05 19:23:19 +00006467 // Constructor inheriting using decls get special treatment.
6468 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006469 if (CheckInheritedConstructorUsingDecl(UD))
6470 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006471 return UD;
6472 }
6473
6474 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006475
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006476 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006477
John McCall604e7f12009-12-08 07:46:18 +00006478 // Unlike most lookups, we don't always want to hide tag
6479 // declarations: tag names are visible through the using declaration
6480 // even if hidden by ordinary names, *except* in a dependent context
6481 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006482 if (!IsInstantiation)
6483 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006484
John McCalla24dc2e2009-11-17 02:14:36 +00006485 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006486
John McCallf36e02d2009-10-09 21:13:30 +00006487 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006488 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006489 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006490 UD->setInvalidDecl();
6491 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006492 }
6493
John McCalled976492009-12-04 22:46:56 +00006494 if (R.isAmbiguous()) {
6495 UD->setInvalidDecl();
6496 return UD;
6497 }
Mike Stump1eb44332009-09-09 15:08:12 +00006498
John McCall7ba107a2009-11-18 02:36:19 +00006499 if (IsTypeName) {
6500 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006501 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006502 Diag(IdentLoc, diag::err_using_typename_non_type);
6503 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6504 Diag((*I)->getUnderlyingDecl()->getLocation(),
6505 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006506 UD->setInvalidDecl();
6507 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006508 }
6509 } else {
6510 // If we asked for a non-typename and we got a type, error out,
6511 // but only if this is an instantiation of an unresolved using
6512 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006513 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006514 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6515 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006516 UD->setInvalidDecl();
6517 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006518 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006519 }
6520
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006521 // C++0x N2914 [namespace.udecl]p6:
6522 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006523 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006524 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6525 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006526 UD->setInvalidDecl();
6527 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006528 }
Mike Stump1eb44332009-09-09 15:08:12 +00006529
John McCall9f54ad42009-12-10 09:41:52 +00006530 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6531 if (!CheckUsingShadowDecl(UD, *I, Previous))
6532 BuildUsingShadowDecl(S, UD, *I);
6533 }
John McCall9488ea12009-11-17 05:59:44 +00006534
6535 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006536}
6537
Sebastian Redlf677ea32011-02-05 19:23:19 +00006538/// Additional checks for a using declaration referring to a constructor name.
6539bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6540 if (UD->isTypeName()) {
6541 // FIXME: Cannot specify typename when specifying constructor
6542 return true;
6543 }
6544
Douglas Gregordc355712011-02-25 00:36:19 +00006545 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006546 assert(SourceType &&
6547 "Using decl naming constructor doesn't have type in scope spec.");
6548 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6549
6550 // Check whether the named type is a direct base class.
6551 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6552 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6553 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6554 BaseIt != BaseE; ++BaseIt) {
6555 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6556 if (CanonicalSourceType == BaseType)
6557 break;
6558 }
6559
6560 if (BaseIt == BaseE) {
6561 // Did not find SourceType in the bases.
6562 Diag(UD->getUsingLocation(),
6563 diag::err_using_decl_constructor_not_in_direct_base)
6564 << UD->getNameInfo().getSourceRange()
6565 << QualType(SourceType, 0) << TargetClass;
6566 return true;
6567 }
6568
6569 BaseIt->setInheritConstructors();
6570
6571 return false;
6572}
6573
John McCall9f54ad42009-12-10 09:41:52 +00006574/// Checks that the given using declaration is not an invalid
6575/// redeclaration. Note that this is checking only for the using decl
6576/// itself, not for any ill-formedness among the UsingShadowDecls.
6577bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6578 bool isTypeName,
6579 const CXXScopeSpec &SS,
6580 SourceLocation NameLoc,
6581 const LookupResult &Prev) {
6582 // C++03 [namespace.udecl]p8:
6583 // C++0x [namespace.udecl]p10:
6584 // A using-declaration is a declaration and can therefore be used
6585 // repeatedly where (and only where) multiple declarations are
6586 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006587 //
John McCall8a726212010-11-29 18:01:58 +00006588 // That's in non-member contexts.
6589 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006590 return false;
6591
6592 NestedNameSpecifier *Qual
6593 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6594
6595 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6596 NamedDecl *D = *I;
6597
6598 bool DTypename;
6599 NestedNameSpecifier *DQual;
6600 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6601 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006602 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006603 } else if (UnresolvedUsingValueDecl *UD
6604 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6605 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006606 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006607 } else if (UnresolvedUsingTypenameDecl *UD
6608 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6609 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006610 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006611 } else continue;
6612
6613 // using decls differ if one says 'typename' and the other doesn't.
6614 // FIXME: non-dependent using decls?
6615 if (isTypeName != DTypename) continue;
6616
6617 // using decls differ if they name different scopes (but note that
6618 // template instantiation can cause this check to trigger when it
6619 // didn't before instantiation).
6620 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6621 Context.getCanonicalNestedNameSpecifier(DQual))
6622 continue;
6623
6624 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006625 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006626 return true;
6627 }
6628
6629 return false;
6630}
6631
John McCall604e7f12009-12-08 07:46:18 +00006632
John McCalled976492009-12-04 22:46:56 +00006633/// Checks that the given nested-name qualifier used in a using decl
6634/// in the current context is appropriately related to the current
6635/// scope. If an error is found, diagnoses it and returns true.
6636bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6637 const CXXScopeSpec &SS,
6638 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006639 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006640
John McCall604e7f12009-12-08 07:46:18 +00006641 if (!CurContext->isRecord()) {
6642 // C++03 [namespace.udecl]p3:
6643 // C++0x [namespace.udecl]p8:
6644 // A using-declaration for a class member shall be a member-declaration.
6645
6646 // If we weren't able to compute a valid scope, it must be a
6647 // dependent class scope.
6648 if (!NamedContext || NamedContext->isRecord()) {
6649 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6650 << SS.getRange();
6651 return true;
6652 }
6653
6654 // Otherwise, everything is known to be fine.
6655 return false;
6656 }
6657
6658 // The current scope is a record.
6659
6660 // If the named context is dependent, we can't decide much.
6661 if (!NamedContext) {
6662 // FIXME: in C++0x, we can diagnose if we can prove that the
6663 // nested-name-specifier does not refer to a base class, which is
6664 // still possible in some cases.
6665
6666 // Otherwise we have to conservatively report that things might be
6667 // okay.
6668 return false;
6669 }
6670
6671 if (!NamedContext->isRecord()) {
6672 // Ideally this would point at the last name in the specifier,
6673 // but we don't have that level of source info.
6674 Diag(SS.getRange().getBegin(),
6675 diag::err_using_decl_nested_name_specifier_is_not_class)
6676 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6677 return true;
6678 }
6679
Douglas Gregor6fb07292010-12-21 07:41:49 +00006680 if (!NamedContext->isDependentContext() &&
6681 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6682 return true;
6683
John McCall604e7f12009-12-08 07:46:18 +00006684 if (getLangOptions().CPlusPlus0x) {
6685 // C++0x [namespace.udecl]p3:
6686 // In a using-declaration used as a member-declaration, the
6687 // nested-name-specifier shall name a base class of the class
6688 // being defined.
6689
6690 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6691 cast<CXXRecordDecl>(NamedContext))) {
6692 if (CurContext == NamedContext) {
6693 Diag(NameLoc,
6694 diag::err_using_decl_nested_name_specifier_is_current_class)
6695 << SS.getRange();
6696 return true;
6697 }
6698
6699 Diag(SS.getRange().getBegin(),
6700 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6701 << (NestedNameSpecifier*) SS.getScopeRep()
6702 << cast<CXXRecordDecl>(CurContext)
6703 << SS.getRange();
6704 return true;
6705 }
6706
6707 return false;
6708 }
6709
6710 // C++03 [namespace.udecl]p4:
6711 // A using-declaration used as a member-declaration shall refer
6712 // to a member of a base class of the class being defined [etc.].
6713
6714 // Salient point: SS doesn't have to name a base class as long as
6715 // lookup only finds members from base classes. Therefore we can
6716 // diagnose here only if we can prove that that can't happen,
6717 // i.e. if the class hierarchies provably don't intersect.
6718
6719 // TODO: it would be nice if "definitely valid" results were cached
6720 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6721 // need to be repeated.
6722
6723 struct UserData {
6724 llvm::DenseSet<const CXXRecordDecl*> Bases;
6725
6726 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6727 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6728 Data->Bases.insert(Base);
6729 return true;
6730 }
6731
6732 bool hasDependentBases(const CXXRecordDecl *Class) {
6733 return !Class->forallBases(collect, this);
6734 }
6735
6736 /// Returns true if the base is dependent or is one of the
6737 /// accumulated base classes.
6738 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6739 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6740 return !Data->Bases.count(Base);
6741 }
6742
6743 bool mightShareBases(const CXXRecordDecl *Class) {
6744 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6745 }
6746 };
6747
6748 UserData Data;
6749
6750 // Returns false if we find a dependent base.
6751 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6752 return false;
6753
6754 // Returns false if the class has a dependent base or if it or one
6755 // of its bases is present in the base set of the current context.
6756 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6757 return false;
6758
6759 Diag(SS.getRange().getBegin(),
6760 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6761 << (NestedNameSpecifier*) SS.getScopeRep()
6762 << cast<CXXRecordDecl>(CurContext)
6763 << SS.getRange();
6764
6765 return true;
John McCalled976492009-12-04 22:46:56 +00006766}
6767
Richard Smith162e1c12011-04-15 14:24:37 +00006768Decl *Sema::ActOnAliasDeclaration(Scope *S,
6769 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006770 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006771 SourceLocation UsingLoc,
6772 UnqualifiedId &Name,
6773 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006774 // Skip up to the relevant declaration scope.
6775 while (S->getFlags() & Scope::TemplateParamScope)
6776 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006777 assert((S->getFlags() & Scope::DeclScope) &&
6778 "got alias-declaration outside of declaration scope");
6779
6780 if (Type.isInvalid())
6781 return 0;
6782
6783 bool Invalid = false;
6784 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6785 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006786 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006787
6788 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6789 return 0;
6790
6791 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006792 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006793 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006794 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6795 TInfo->getTypeLoc().getBeginLoc());
6796 }
Richard Smith162e1c12011-04-15 14:24:37 +00006797
6798 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6799 LookupName(Previous, S);
6800
6801 // Warn about shadowing the name of a template parameter.
6802 if (Previous.isSingleResult() &&
6803 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006804 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006805 Previous.clear();
6806 }
6807
6808 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6809 "name in alias declaration must be an identifier");
6810 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6811 Name.StartLocation,
6812 Name.Identifier, TInfo);
6813
6814 NewTD->setAccess(AS);
6815
6816 if (Invalid)
6817 NewTD->setInvalidDecl();
6818
Richard Smith3e4c6c42011-05-05 21:57:07 +00006819 CheckTypedefForVariablyModifiedType(S, NewTD);
6820 Invalid |= NewTD->isInvalidDecl();
6821
Richard Smith162e1c12011-04-15 14:24:37 +00006822 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006823
6824 NamedDecl *NewND;
6825 if (TemplateParamLists.size()) {
6826 TypeAliasTemplateDecl *OldDecl = 0;
6827 TemplateParameterList *OldTemplateParams = 0;
6828
6829 if (TemplateParamLists.size() != 1) {
6830 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6831 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6832 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6833 }
6834 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6835
6836 // Only consider previous declarations in the same scope.
6837 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6838 /*ExplicitInstantiationOrSpecialization*/false);
6839 if (!Previous.empty()) {
6840 Redeclaration = true;
6841
6842 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6843 if (!OldDecl && !Invalid) {
6844 Diag(UsingLoc, diag::err_redefinition_different_kind)
6845 << Name.Identifier;
6846
6847 NamedDecl *OldD = Previous.getRepresentativeDecl();
6848 if (OldD->getLocation().isValid())
6849 Diag(OldD->getLocation(), diag::note_previous_definition);
6850
6851 Invalid = true;
6852 }
6853
6854 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6855 if (TemplateParameterListsAreEqual(TemplateParams,
6856 OldDecl->getTemplateParameters(),
6857 /*Complain=*/true,
6858 TPL_TemplateMatch))
6859 OldTemplateParams = OldDecl->getTemplateParameters();
6860 else
6861 Invalid = true;
6862
6863 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6864 if (!Invalid &&
6865 !Context.hasSameType(OldTD->getUnderlyingType(),
6866 NewTD->getUnderlyingType())) {
6867 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6868 // but we can't reasonably accept it.
6869 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6870 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6871 if (OldTD->getLocation().isValid())
6872 Diag(OldTD->getLocation(), diag::note_previous_definition);
6873 Invalid = true;
6874 }
6875 }
6876 }
6877
6878 // Merge any previous default template arguments into our parameters,
6879 // and check the parameter list.
6880 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6881 TPC_TypeAliasTemplate))
6882 return 0;
6883
6884 TypeAliasTemplateDecl *NewDecl =
6885 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6886 Name.Identifier, TemplateParams,
6887 NewTD);
6888
6889 NewDecl->setAccess(AS);
6890
6891 if (Invalid)
6892 NewDecl->setInvalidDecl();
6893 else if (OldDecl)
6894 NewDecl->setPreviousDeclaration(OldDecl);
6895
6896 NewND = NewDecl;
6897 } else {
6898 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6899 NewND = NewTD;
6900 }
Richard Smith162e1c12011-04-15 14:24:37 +00006901
6902 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006903 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006904
Richard Smith3e4c6c42011-05-05 21:57:07 +00006905 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006906}
6907
John McCalld226f652010-08-21 09:40:31 +00006908Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006909 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006910 SourceLocation AliasLoc,
6911 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006912 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006913 SourceLocation IdentLoc,
6914 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006915
Anders Carlsson81c85c42009-03-28 23:53:49 +00006916 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006917 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6918 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006919
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006920 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006921 NamedDecl *PrevDecl
6922 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6923 ForRedeclaration);
6924 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6925 PrevDecl = 0;
6926
6927 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006928 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006929 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006930 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006931 // FIXME: At some point, we'll want to create the (redundant)
6932 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006933 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006934 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006935 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006936 }
Mike Stump1eb44332009-09-09 15:08:12 +00006937
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006938 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6939 diag::err_redefinition_different_kind;
6940 Diag(AliasLoc, DiagID) << Alias;
6941 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006942 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006943 }
6944
John McCalla24dc2e2009-11-17 02:14:36 +00006945 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006946 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006947
John McCallf36e02d2009-10-09 21:13:30 +00006948 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006949 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006950 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006951 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006952 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006953 }
Mike Stump1eb44332009-09-09 15:08:12 +00006954
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006955 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006956 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006957 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006958 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006959
John McCall3dbd3d52010-02-16 06:53:13 +00006960 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006961 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006962}
6963
Douglas Gregor39957dc2010-05-01 15:04:51 +00006964namespace {
6965 /// \brief Scoped object used to handle the state changes required in Sema
6966 /// to implicitly define the body of a C++ member function;
6967 class ImplicitlyDefinedFunctionScope {
6968 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006969 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006970
6971 public:
6972 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006973 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006974 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006975 S.PushFunctionScope();
6976 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6977 }
6978
6979 ~ImplicitlyDefinedFunctionScope() {
6980 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006981 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006982 }
6983 };
6984}
6985
Sean Hunt001cad92011-05-10 00:49:42 +00006986Sema::ImplicitExceptionSpecification
6987Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006988 // C++ [except.spec]p14:
6989 // An implicitly declared special member function (Clause 12) shall have an
6990 // exception-specification. [...]
6991 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006992 if (ClassDecl->isInvalidDecl())
6993 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006994
Sebastian Redl60618fa2011-03-12 11:50:43 +00006995 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006996 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6997 BEnd = ClassDecl->bases_end();
6998 B != BEnd; ++B) {
6999 if (B->isVirtual()) // Handled below.
7000 continue;
7001
Douglas Gregor18274032010-07-03 00:47:00 +00007002 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7003 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007004 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7005 // If this is a deleted function, add it anyway. This might be conformant
7006 // with the standard. This might not. I'm not sure. It might not matter.
7007 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007008 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007009 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007010 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007011
7012 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007013 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7014 BEnd = ClassDecl->vbases_end();
7015 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007016 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7017 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007018 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7019 // If this is a deleted function, add it anyway. This might be conformant
7020 // with the standard. This might not. I'm not sure. It might not matter.
7021 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007022 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007023 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007024 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007025
7026 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007027 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7028 FEnd = ClassDecl->field_end();
7029 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007030 if (F->hasInClassInitializer()) {
7031 if (Expr *E = F->getInClassInitializer())
7032 ExceptSpec.CalledExpr(E);
7033 else if (!F->isInvalidDecl())
7034 ExceptSpec.SetDelayed();
7035 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007036 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007037 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7038 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7039 // If this is a deleted function, add it anyway. This might be conformant
7040 // with the standard. This might not. I'm not sure. It might not matter.
7041 // In particular, the problem is that this function never gets called. It
7042 // might just be ill-formed because this function attempts to refer to
7043 // a deleted function here.
7044 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007045 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007046 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007047 }
John McCalle23cf432010-12-14 08:05:40 +00007048
Sean Hunt001cad92011-05-10 00:49:42 +00007049 return ExceptSpec;
7050}
7051
7052CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7053 CXXRecordDecl *ClassDecl) {
7054 // C++ [class.ctor]p5:
7055 // A default constructor for a class X is a constructor of class X
7056 // that can be called without an argument. If there is no
7057 // user-declared constructor for class X, a default constructor is
7058 // implicitly declared. An implicitly-declared default constructor
7059 // is an inline public member of its class.
7060 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7061 "Should not build implicit default constructor!");
7062
7063 ImplicitExceptionSpecification Spec =
7064 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7065 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00007066
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007067 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007068 CanQualType ClassType
7069 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007070 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007071 DeclarationName Name
7072 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007073 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007074 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7075 Context, ClassDecl, ClassLoc, NameInfo,
7076 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7077 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7078 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7079 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007080 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007081 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007082 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00007083 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00007084
7085 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007086 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7087
Douglas Gregor23c94db2010-07-02 17:43:08 +00007088 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007089 PushOnScopeChains(DefaultCon, S, false);
7090 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007091
Sean Hunte16da072011-10-10 06:18:57 +00007092 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007093 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00007094
Douglas Gregor32df23e2010-07-01 22:02:46 +00007095 return DefaultCon;
7096}
7097
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007098void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7099 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007100 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007101 !Constructor->doesThisDeclarationHaveABody() &&
7102 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007103 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007104
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007105 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007106 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007107
Douglas Gregor39957dc2010-05-01 15:04:51 +00007108 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007109 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007110 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007111 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007112 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007113 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007114 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007115 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007116 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007117
7118 SourceLocation Loc = Constructor->getLocation();
7119 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7120
7121 Constructor->setUsed();
7122 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007123
7124 if (ASTMutationListener *L = getASTMutationListener()) {
7125 L->CompletedImplicitDefinition(Constructor);
7126 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007127}
7128
Richard Smith7a614d82011-06-11 17:19:42 +00007129/// Get any existing defaulted default constructor for the given class. Do not
7130/// implicitly define one if it does not exist.
7131static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7132 CXXRecordDecl *D) {
7133 ASTContext &Context = Self.Context;
7134 QualType ClassType = Context.getTypeDeclType(D);
7135 DeclarationName ConstructorName
7136 = Context.DeclarationNames.getCXXConstructorName(
7137 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7138
7139 DeclContext::lookup_const_iterator Con, ConEnd;
7140 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7141 Con != ConEnd; ++Con) {
7142 // A function template cannot be defaulted.
7143 if (isa<FunctionTemplateDecl>(*Con))
7144 continue;
7145
7146 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7147 if (Constructor->isDefaultConstructor())
7148 return Constructor->isDefaulted() ? Constructor : 0;
7149 }
7150 return 0;
7151}
7152
7153void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7154 if (!D) return;
7155 AdjustDeclIfTemplate(D);
7156
7157 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7158 CXXConstructorDecl *CtorDecl
7159 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7160
7161 if (!CtorDecl) return;
7162
7163 // Compute the exception specification for the default constructor.
7164 const FunctionProtoType *CtorTy =
7165 CtorDecl->getType()->castAs<FunctionProtoType>();
7166 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7167 ImplicitExceptionSpecification Spec =
7168 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7169 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7170 assert(EPI.ExceptionSpecType != EST_Delayed);
7171
7172 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7173 }
7174
7175 // If the default constructor is explicitly defaulted, checking the exception
7176 // specification is deferred until now.
7177 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7178 !ClassDecl->isDependentType())
7179 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7180}
7181
Sebastian Redlf677ea32011-02-05 19:23:19 +00007182void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7183 // We start with an initial pass over the base classes to collect those that
7184 // inherit constructors from. If there are none, we can forgo all further
7185 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007186 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007187 BasesVector BasesToInheritFrom;
7188 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7189 BaseE = ClassDecl->bases_end();
7190 BaseIt != BaseE; ++BaseIt) {
7191 if (BaseIt->getInheritConstructors()) {
7192 QualType Base = BaseIt->getType();
7193 if (Base->isDependentType()) {
7194 // If we inherit constructors from anything that is dependent, just
7195 // abort processing altogether. We'll get another chance for the
7196 // instantiations.
7197 return;
7198 }
7199 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7200 }
7201 }
7202 if (BasesToInheritFrom.empty())
7203 return;
7204
7205 // Now collect the constructors that we already have in the current class.
7206 // Those take precedence over inherited constructors.
7207 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7208 // unless there is a user-declared constructor with the same signature in
7209 // the class where the using-declaration appears.
7210 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7211 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7212 CtorE = ClassDecl->ctor_end();
7213 CtorIt != CtorE; ++CtorIt) {
7214 ExistingConstructors.insert(
7215 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7216 }
7217
7218 Scope *S = getScopeForContext(ClassDecl);
7219 DeclarationName CreatedCtorName =
7220 Context.DeclarationNames.getCXXConstructorName(
7221 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7222
7223 // Now comes the true work.
7224 // First, we keep a map from constructor types to the base that introduced
7225 // them. Needed for finding conflicting constructors. We also keep the
7226 // actually inserted declarations in there, for pretty diagnostics.
7227 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7228 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7229 ConstructorToSourceMap InheritedConstructors;
7230 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7231 BaseE = BasesToInheritFrom.end();
7232 BaseIt != BaseE; ++BaseIt) {
7233 const RecordType *Base = *BaseIt;
7234 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7235 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7236 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7237 CtorE = BaseDecl->ctor_end();
7238 CtorIt != CtorE; ++CtorIt) {
7239 // Find the using declaration for inheriting this base's constructors.
7240 DeclarationName Name =
7241 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7242 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7243 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7244 SourceLocation UsingLoc = UD ? UD->getLocation() :
7245 ClassDecl->getLocation();
7246
7247 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7248 // from the class X named in the using-declaration consists of actual
7249 // constructors and notional constructors that result from the
7250 // transformation of defaulted parameters as follows:
7251 // - all non-template default constructors of X, and
7252 // - for each non-template constructor of X that has at least one
7253 // parameter with a default argument, the set of constructors that
7254 // results from omitting any ellipsis parameter specification and
7255 // successively omitting parameters with a default argument from the
7256 // end of the parameter-type-list.
7257 CXXConstructorDecl *BaseCtor = *CtorIt;
7258 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7259 const FunctionProtoType *BaseCtorType =
7260 BaseCtor->getType()->getAs<FunctionProtoType>();
7261
7262 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7263 maxParams = BaseCtor->getNumParams();
7264 params <= maxParams; ++params) {
7265 // Skip default constructors. They're never inherited.
7266 if (params == 0)
7267 continue;
7268 // Skip copy and move constructors for the same reason.
7269 if (CanBeCopyOrMove && params == 1)
7270 continue;
7271
7272 // Build up a function type for this particular constructor.
7273 // FIXME: The working paper does not consider that the exception spec
7274 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007275 // source. This code doesn't yet, either. When it does, this code will
7276 // need to be delayed until after exception specifications and in-class
7277 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007278 const Type *NewCtorType;
7279 if (params == maxParams)
7280 NewCtorType = BaseCtorType;
7281 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007282 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007283 for (unsigned i = 0; i < params; ++i) {
7284 Args.push_back(BaseCtorType->getArgType(i));
7285 }
7286 FunctionProtoType::ExtProtoInfo ExtInfo =
7287 BaseCtorType->getExtProtoInfo();
7288 ExtInfo.Variadic = false;
7289 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7290 Args.data(), params, ExtInfo)
7291 .getTypePtr();
7292 }
7293 const Type *CanonicalNewCtorType =
7294 Context.getCanonicalType(NewCtorType);
7295
7296 // Now that we have the type, first check if the class already has a
7297 // constructor with this signature.
7298 if (ExistingConstructors.count(CanonicalNewCtorType))
7299 continue;
7300
7301 // Then we check if we have already declared an inherited constructor
7302 // with this signature.
7303 std::pair<ConstructorToSourceMap::iterator, bool> result =
7304 InheritedConstructors.insert(std::make_pair(
7305 CanonicalNewCtorType,
7306 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7307 if (!result.second) {
7308 // Already in the map. If it came from a different class, that's an
7309 // error. Not if it's from the same.
7310 CanQualType PreviousBase = result.first->second.first;
7311 if (CanonicalBase != PreviousBase) {
7312 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7313 const CXXConstructorDecl *PrevBaseCtor =
7314 PrevCtor->getInheritedConstructor();
7315 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7316
7317 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7318 Diag(BaseCtor->getLocation(),
7319 diag::note_using_decl_constructor_conflict_current_ctor);
7320 Diag(PrevBaseCtor->getLocation(),
7321 diag::note_using_decl_constructor_conflict_previous_ctor);
7322 Diag(PrevCtor->getLocation(),
7323 diag::note_using_decl_constructor_conflict_previous_using);
7324 }
7325 continue;
7326 }
7327
7328 // OK, we're there, now add the constructor.
7329 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007330 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007331 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7332 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007333 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7334 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007335 /*ImplicitlyDeclared=*/true,
7336 // FIXME: Due to a defect in the standard, we treat inherited
7337 // constructors as constexpr even if that makes them ill-formed.
7338 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007339 NewCtor->setAccess(BaseCtor->getAccess());
7340
7341 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007342 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007343 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007344 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7345 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007346 /*IdentifierInfo=*/0,
7347 BaseCtorType->getArgType(i),
7348 /*TInfo=*/0, SC_None,
7349 SC_None, /*DefaultArg=*/0));
7350 }
David Blaikie4278c652011-09-21 18:16:56 +00007351 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007352 NewCtor->setInheritedConstructor(BaseCtor);
7353
7354 PushOnScopeChains(NewCtor, S, false);
7355 ClassDecl->addDecl(NewCtor);
7356 result.first->second.second = NewCtor;
7357 }
7358 }
7359 }
7360}
7361
Sean Huntcb45a0f2011-05-12 22:46:25 +00007362Sema::ImplicitExceptionSpecification
7363Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007364 // C++ [except.spec]p14:
7365 // An implicitly declared special member function (Clause 12) shall have
7366 // an exception-specification.
7367 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007368 if (ClassDecl->isInvalidDecl())
7369 return ExceptSpec;
7370
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007371 // Direct base-class destructors.
7372 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7373 BEnd = ClassDecl->bases_end();
7374 B != BEnd; ++B) {
7375 if (B->isVirtual()) // Handled below.
7376 continue;
7377
7378 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7379 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007380 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007381 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007382
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007383 // Virtual base-class destructors.
7384 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7385 BEnd = ClassDecl->vbases_end();
7386 B != BEnd; ++B) {
7387 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7388 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007389 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007390 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007391
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007392 // Field destructors.
7393 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7394 FEnd = ClassDecl->field_end();
7395 F != FEnd; ++F) {
7396 if (const RecordType *RecordTy
7397 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7398 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007399 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007400 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007401
Sean Huntcb45a0f2011-05-12 22:46:25 +00007402 return ExceptSpec;
7403}
7404
7405CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7406 // C++ [class.dtor]p2:
7407 // If a class has no user-declared destructor, a destructor is
7408 // declared implicitly. An implicitly-declared destructor is an
7409 // inline public member of its class.
7410
7411 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007412 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007413 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7414
Douglas Gregor4923aa22010-07-02 20:37:36 +00007415 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007416 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007417
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007418 CanQualType ClassType
7419 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007420 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007421 DeclarationName Name
7422 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007423 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007424 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007425 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7426 /*isInline=*/true,
7427 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007428 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007429 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007430 Destructor->setImplicit();
7431 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007432
7433 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007434 ++ASTContext::NumImplicitDestructorsDeclared;
7435
7436 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007437 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007438 PushOnScopeChains(Destructor, S, false);
7439 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007440
7441 // This could be uniqued if it ever proves significant.
7442 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007443
7444 if (ShouldDeleteDestructor(Destructor))
7445 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007446
7447 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007448
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007449 return Destructor;
7450}
7451
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007452void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007453 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007454 assert((Destructor->isDefaulted() &&
7455 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007456 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007457 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007458 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007459
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007460 if (Destructor->isInvalidDecl())
7461 return;
7462
Douglas Gregor39957dc2010-05-01 15:04:51 +00007463 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007464
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007465 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007466 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7467 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007468
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007469 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007470 Diag(CurrentLocation, diag::note_member_synthesized_at)
7471 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7472
7473 Destructor->setInvalidDecl();
7474 return;
7475 }
7476
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007477 SourceLocation Loc = Destructor->getLocation();
7478 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007479 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007480 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007481 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007482
7483 if (ASTMutationListener *L = getASTMutationListener()) {
7484 L->CompletedImplicitDefinition(Destructor);
7485 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007486}
7487
Sebastian Redl0ee33912011-05-19 05:13:44 +00007488void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7489 CXXDestructorDecl *destructor) {
7490 // C++11 [class.dtor]p3:
7491 // A declaration of a destructor that does not have an exception-
7492 // specification is implicitly considered to have the same exception-
7493 // specification as an implicit declaration.
7494 const FunctionProtoType *dtorType = destructor->getType()->
7495 getAs<FunctionProtoType>();
7496 if (dtorType->hasExceptionSpec())
7497 return;
7498
7499 ImplicitExceptionSpecification exceptSpec =
7500 ComputeDefaultedDtorExceptionSpec(classDecl);
7501
Chandler Carruth3f224b22011-09-20 04:55:26 +00007502 // Replace the destructor's type, building off the existing one. Fortunately,
7503 // the only thing of interest in the destructor type is its extended info.
7504 // The return and arguments are fixed.
7505 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007506 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7507 epi.NumExceptions = exceptSpec.size();
7508 epi.Exceptions = exceptSpec.data();
7509 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7510
7511 destructor->setType(ty);
7512
7513 // FIXME: If the destructor has a body that could throw, and the newly created
7514 // spec doesn't allow exceptions, we should emit a warning, because this
7515 // change in behavior can break conforming C++03 programs at runtime.
7516 // However, we don't have a body yet, so it needs to be done somewhere else.
7517}
7518
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007519/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007520/// \c To.
7521///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007522/// This routine is used to copy/move the members of a class with an
7523/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007524/// copied are arrays, this routine builds for loops to copy them.
7525///
7526/// \param S The Sema object used for type-checking.
7527///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007528/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007529///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007530/// \param T The type of the expressions being copied/moved. Both expressions
7531/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007532///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007533/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007534///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007535/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007536///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007537/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007538/// Otherwise, it's a non-static member subobject.
7539///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007540/// \param Copying Whether we're copying or moving.
7541///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007542/// \param Depth Internal parameter recording the depth of the recursion.
7543///
7544/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007545static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007546BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007547 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007548 bool CopyingBaseSubobject, bool Copying,
7549 unsigned Depth = 0) {
7550 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007551 // Each subobject is assigned in the manner appropriate to its type:
7552 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007553 // - if the subobject is of class type, as if by a call to operator= with
7554 // the subobject as the object expression and the corresponding
7555 // subobject of x as a single function argument (as if by explicit
7556 // qualification; that is, ignoring any possible virtual overriding
7557 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007558 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7559 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7560
7561 // Look for operator=.
7562 DeclarationName Name
7563 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7564 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7565 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7566
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007567 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007568 LookupResult::Filter F = OpLookup.makeFilter();
7569 while (F.hasNext()) {
7570 NamedDecl *D = F.next();
7571 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007572 if (Copying ? Method->isCopyAssignmentOperator() :
7573 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007574 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007575
Douglas Gregor06a9f362010-05-01 20:49:11 +00007576 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007577 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007578 F.done();
7579
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007580 // Suppress the protected check (C++ [class.protected]) for each of the
7581 // assignment operators we found. This strange dance is required when
7582 // we're assigning via a base classes's copy-assignment operator. To
7583 // ensure that we're getting the right base class subobject (without
7584 // ambiguities), we need to cast "this" to that subobject type; to
7585 // ensure that we don't go through the virtual call mechanism, we need
7586 // to qualify the operator= name with the base class (see below). However,
7587 // this means that if the base class has a protected copy assignment
7588 // operator, the protected member access check will fail. So, we
7589 // rewrite "protected" access to "public" access in this case, since we
7590 // know by construction that we're calling from a derived class.
7591 if (CopyingBaseSubobject) {
7592 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7593 L != LEnd; ++L) {
7594 if (L.getAccess() == AS_protected)
7595 L.setAccess(AS_public);
7596 }
7597 }
7598
Douglas Gregor06a9f362010-05-01 20:49:11 +00007599 // Create the nested-name-specifier that will be used to qualify the
7600 // reference to operator=; this is required to suppress the virtual
7601 // call mechanism.
7602 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007603 SS.MakeTrivial(S.Context,
7604 NestedNameSpecifier::Create(S.Context, 0, false,
7605 T.getTypePtr()),
7606 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007607
7608 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007609 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007610 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007611 /*TemplateKWLoc=*/SourceLocation(),
7612 /*FirstQualifierInScope=*/0,
7613 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007614 /*TemplateArgs=*/0,
7615 /*SuppressQualifierCheck=*/true);
7616 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007617 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007618
7619 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007620
John McCall60d7b3a2010-08-24 06:29:42 +00007621 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007622 OpEqualRef.takeAs<Expr>(),
7623 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007624 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007625 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007626
7627 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007628 }
John McCallb0207482010-03-16 06:11:48 +00007629
Douglas Gregor06a9f362010-05-01 20:49:11 +00007630 // - if the subobject is of scalar type, the built-in assignment
7631 // operator is used.
7632 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7633 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007634 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007635 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007636 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007637
7638 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007639 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007640
7641 // - if the subobject is an array, each element is assigned, in the
7642 // manner appropriate to the element type;
7643
7644 // Construct a loop over the array bounds, e.g.,
7645 //
7646 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7647 //
7648 // that will copy each of the array elements.
7649 QualType SizeType = S.Context.getSizeType();
7650
7651 // Create the iteration variable.
7652 IdentifierInfo *IterationVarName = 0;
7653 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007654 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007655 llvm::raw_svector_ostream OS(Str);
7656 OS << "__i" << Depth;
7657 IterationVarName = &S.Context.Idents.get(OS.str());
7658 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007659 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007660 IterationVarName, SizeType,
7661 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007662 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007663
7664 // Initialize the iteration variable to zero.
7665 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007666 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007667
7668 // Create a reference to the iteration variable; we'll use this several
7669 // times throughout.
7670 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007671 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007672 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007673 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7674 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7675
Douglas Gregor06a9f362010-05-01 20:49:11 +00007676 // Create the DeclStmt that holds the iteration variable.
7677 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7678
7679 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007680 llvm::APInt Upper
7681 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007682 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007683 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007684 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7685 BO_NE, S.Context.BoolTy,
7686 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007687
7688 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007689 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007690 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7691 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007692
7693 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007694 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007695 IterationVarRefRVal,
7696 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007697 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007698 IterationVarRefRVal,
7699 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007700 if (!Copying) // Cast to rvalue
7701 From = CastForMoving(S, From);
7702
7703 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007704 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7705 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007706 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007707 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007708 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007709
7710 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007711 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007712 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007713 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007714 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007715}
7716
Sean Hunt30de05c2011-05-14 05:23:20 +00007717std::pair<Sema::ImplicitExceptionSpecification, bool>
7718Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7719 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007720 if (ClassDecl->isInvalidDecl())
7721 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7722
Douglas Gregord3c35902010-07-01 16:36:15 +00007723 // C++ [class.copy]p10:
7724 // If the class definition does not explicitly declare a copy
7725 // assignment operator, one is declared implicitly.
7726 // The implicitly-defined copy assignment operator for a class X
7727 // will have the form
7728 //
7729 // X& X::operator=(const X&)
7730 //
7731 // if
7732 bool HasConstCopyAssignment = true;
7733
7734 // -- each direct base class B of X has a copy assignment operator
7735 // whose parameter is of type const B&, const volatile B& or B,
7736 // and
7737 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7738 BaseEnd = ClassDecl->bases_end();
7739 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007740 // We'll handle this below
7741 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7742 continue;
7743
Douglas Gregord3c35902010-07-01 16:36:15 +00007744 assert(!Base->getType()->isDependentType() &&
7745 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007746 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7747 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7748 &HasConstCopyAssignment);
7749 }
7750
Richard Smithebaf0e62011-10-18 20:49:44 +00007751 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007752 if (LangOpts.CPlusPlus0x) {
7753 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7754 BaseEnd = ClassDecl->vbases_end();
7755 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7756 assert(!Base->getType()->isDependentType() &&
7757 "Cannot generate implicit members for class with dependent bases.");
7758 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7759 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7760 &HasConstCopyAssignment);
7761 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007762 }
7763
7764 // -- for all the nonstatic data members of X that are of a class
7765 // type M (or array thereof), each such class type has a copy
7766 // assignment operator whose parameter is of type const M&,
7767 // const volatile M& or M.
7768 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7769 FieldEnd = ClassDecl->field_end();
7770 HasConstCopyAssignment && Field != FieldEnd;
7771 ++Field) {
7772 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007773 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7774 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7775 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007776 }
7777 }
7778
7779 // Otherwise, the implicitly declared copy assignment operator will
7780 // have the form
7781 //
7782 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007783
Douglas Gregorb87786f2010-07-01 17:48:08 +00007784 // C++ [except.spec]p14:
7785 // An implicitly declared special member function (Clause 12) shall have an
7786 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007787
7788 // It is unspecified whether or not an implicit copy assignment operator
7789 // attempts to deduplicate calls to assignment operators of virtual bases are
7790 // made. As such, this exception specification is effectively unspecified.
7791 // Based on a similar decision made for constness in C++0x, we're erring on
7792 // the side of assuming such calls to be made regardless of whether they
7793 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007794 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007795 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007796 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7797 BaseEnd = ClassDecl->bases_end();
7798 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007799 if (Base->isVirtual())
7800 continue;
7801
Douglas Gregora376d102010-07-02 21:50:04 +00007802 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007803 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007804 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7805 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007806 ExceptSpec.CalledDecl(CopyAssign);
7807 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007808
7809 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7810 BaseEnd = ClassDecl->vbases_end();
7811 Base != BaseEnd; ++Base) {
7812 CXXRecordDecl *BaseClassDecl
7813 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7814 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7815 ArgQuals, false, 0))
7816 ExceptSpec.CalledDecl(CopyAssign);
7817 }
7818
Douglas Gregorb87786f2010-07-01 17:48:08 +00007819 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7820 FieldEnd = ClassDecl->field_end();
7821 Field != FieldEnd;
7822 ++Field) {
7823 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007824 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7825 if (CXXMethodDecl *CopyAssign =
7826 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7827 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007828 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007829 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007830
Sean Hunt30de05c2011-05-14 05:23:20 +00007831 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7832}
7833
7834CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7835 // Note: The following rules are largely analoguous to the copy
7836 // constructor rules. Note that virtual bases are not taken into account
7837 // for determining the argument type of the operator. Note also that
7838 // operators taking an object instead of a reference are allowed.
7839
7840 ImplicitExceptionSpecification Spec(Context);
7841 bool Const;
7842 llvm::tie(Spec, Const) =
7843 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7844
7845 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7846 QualType RetType = Context.getLValueReferenceType(ArgType);
7847 if (Const)
7848 ArgType = ArgType.withConst();
7849 ArgType = Context.getLValueReferenceType(ArgType);
7850
Douglas Gregord3c35902010-07-01 16:36:15 +00007851 // An implicitly-declared copy assignment operator is an inline public
7852 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007853 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007854 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007855 SourceLocation ClassLoc = ClassDecl->getLocation();
7856 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007857 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007858 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007859 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007860 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007861 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007862 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007863 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007864 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007865 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007866 CopyAssignment->setImplicit();
7867 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007868
7869 // Add the parameter to the operator.
7870 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007871 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007872 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007873 SC_None,
7874 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007875 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007876
Douglas Gregora376d102010-07-02 21:50:04 +00007877 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007878 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007879
Douglas Gregor23c94db2010-07-02 17:43:08 +00007880 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007881 PushOnScopeChains(CopyAssignment, S, false);
7882 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007883
Nico Weberafcc96a2012-01-23 03:19:29 +00007884 // C++0x [class.copy]p19:
7885 // .... If the class definition does not explicitly declare a copy
7886 // assignment operator, there is no user-declared move constructor, and
7887 // there is no user-declared move assignment operator, a copy assignment
7888 // operator is implicitly declared as defaulted.
7889 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber28976602012-01-23 04:01:33 +00007890 !getLangOptions().MicrosoftMode) ||
7891 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Hunt1ccbc542011-06-22 01:05:13 +00007892 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007893 CopyAssignment->setDeletedAsWritten();
7894
Douglas Gregord3c35902010-07-01 16:36:15 +00007895 AddOverriddenMethods(ClassDecl, CopyAssignment);
7896 return CopyAssignment;
7897}
7898
Douglas Gregor06a9f362010-05-01 20:49:11 +00007899void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7900 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007901 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007902 CopyAssignOperator->isOverloadedOperator() &&
7903 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007904 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007905 "DefineImplicitCopyAssignment called for wrong function");
7906
7907 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7908
7909 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7910 CopyAssignOperator->setInvalidDecl();
7911 return;
7912 }
7913
7914 CopyAssignOperator->setUsed();
7915
7916 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007917 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007918
7919 // C++0x [class.copy]p30:
7920 // The implicitly-defined or explicitly-defaulted copy assignment operator
7921 // for a non-union class X performs memberwise copy assignment of its
7922 // subobjects. The direct base classes of X are assigned first, in the
7923 // order of their declaration in the base-specifier-list, and then the
7924 // immediate non-static data members of X are assigned, in the order in
7925 // which they were declared in the class definition.
7926
7927 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007928 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007929
7930 // The parameter for the "other" object, which we are copying from.
7931 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7932 Qualifiers OtherQuals = Other->getType().getQualifiers();
7933 QualType OtherRefType = Other->getType();
7934 if (const LValueReferenceType *OtherRef
7935 = OtherRefType->getAs<LValueReferenceType>()) {
7936 OtherRefType = OtherRef->getPointeeType();
7937 OtherQuals = OtherRefType.getQualifiers();
7938 }
7939
7940 // Our location for everything implicitly-generated.
7941 SourceLocation Loc = CopyAssignOperator->getLocation();
7942
7943 // Construct a reference to the "other" object. We'll be using this
7944 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007945 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007946 assert(OtherRef && "Reference to parameter cannot fail!");
7947
7948 // Construct the "this" pointer. We'll be using this throughout the generated
7949 // ASTs.
7950 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7951 assert(This && "Reference to this cannot fail!");
7952
7953 // Assign base classes.
7954 bool Invalid = false;
7955 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7956 E = ClassDecl->bases_end(); Base != E; ++Base) {
7957 // Form the assignment:
7958 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7959 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007960 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007961 Invalid = true;
7962 continue;
7963 }
7964
John McCallf871d0c2010-08-07 06:22:56 +00007965 CXXCastPath BasePath;
7966 BasePath.push_back(Base);
7967
Douglas Gregor06a9f362010-05-01 20:49:11 +00007968 // Construct the "from" expression, which is an implicit cast to the
7969 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007970 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007971 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7972 CK_UncheckedDerivedToBase,
7973 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007974
7975 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007976 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007977
7978 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007979 To = ImpCastExprToType(To.take(),
7980 Context.getCVRQualifiedType(BaseType,
7981 CopyAssignOperator->getTypeQualifiers()),
7982 CK_UncheckedDerivedToBase,
7983 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007984
7985 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007986 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007987 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007988 /*CopyingBaseSubobject=*/true,
7989 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007990 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007991 Diag(CurrentLocation, diag::note_member_synthesized_at)
7992 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7993 CopyAssignOperator->setInvalidDecl();
7994 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007995 }
7996
7997 // Success! Record the copy.
7998 Statements.push_back(Copy.takeAs<Expr>());
7999 }
8000
8001 // \brief Reference to the __builtin_memcpy function.
8002 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008003 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008004 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008005
8006 // Assign non-static members.
8007 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8008 FieldEnd = ClassDecl->field_end();
8009 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008010 if (Field->isUnnamedBitfield())
8011 continue;
8012
Douglas Gregor06a9f362010-05-01 20:49:11 +00008013 // Check for members of reference type; we can't copy those.
8014 if (Field->getType()->isReferenceType()) {
8015 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8016 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8017 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008018 Diag(CurrentLocation, diag::note_member_synthesized_at)
8019 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008020 Invalid = true;
8021 continue;
8022 }
8023
8024 // Check for members of const-qualified, non-class type.
8025 QualType BaseType = Context.getBaseElementType(Field->getType());
8026 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8027 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8028 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8029 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008030 Diag(CurrentLocation, diag::note_member_synthesized_at)
8031 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008032 Invalid = true;
8033 continue;
8034 }
John McCallb77115d2011-06-17 00:18:42 +00008035
8036 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008037 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8038 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008039
8040 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008041 if (FieldType->isIncompleteArrayType()) {
8042 assert(ClassDecl->hasFlexibleArrayMember() &&
8043 "Incomplete array type is not valid");
8044 continue;
8045 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008046
8047 // Build references to the field in the object we're copying from and to.
8048 CXXScopeSpec SS; // Intentionally empty
8049 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8050 LookupMemberName);
8051 MemberLookup.addDecl(*Field);
8052 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008053 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008054 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008055 SS, SourceLocation(), 0,
8056 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008057 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008058 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008059 SS, SourceLocation(), 0,
8060 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008061 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8062 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8063
8064 // If the field should be copied with __builtin_memcpy rather than via
8065 // explicit assignments, do so. This optimization only applies for arrays
8066 // of scalars and arrays of class type with trivial copy-assignment
8067 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00008068 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008069 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008070 // Compute the size of the memory buffer to be copied.
8071 QualType SizeType = Context.getSizeType();
8072 llvm::APInt Size(Context.getTypeSize(SizeType),
8073 Context.getTypeSizeInChars(BaseType).getQuantity());
8074 for (const ConstantArrayType *Array
8075 = Context.getAsConstantArrayType(FieldType);
8076 Array;
8077 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00008078 llvm::APInt ArraySize
8079 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008080 Size *= ArraySize;
8081 }
8082
8083 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00008084 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8085 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008086
8087 bool NeedsCollectableMemCpy =
8088 (BaseType->isRecordType() &&
8089 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8090
8091 if (NeedsCollectableMemCpy) {
8092 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008093 // Create a reference to the __builtin_objc_memmove_collectable function.
8094 LookupResult R(*this,
8095 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008096 Loc, LookupOrdinaryName);
8097 LookupName(R, TUScope, true);
8098
8099 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8100 if (!CollectableMemCpy) {
8101 // Something went horribly wrong earlier, and we will have
8102 // complained about it.
8103 Invalid = true;
8104 continue;
8105 }
8106
8107 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8108 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008109 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008110 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8111 }
8112 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008113 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008114 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008115 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8116 LookupOrdinaryName);
8117 LookupName(R, TUScope, true);
8118
8119 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8120 if (!BuiltinMemCpy) {
8121 // Something went horribly wrong earlier, and we will have complained
8122 // about it.
8123 Invalid = true;
8124 continue;
8125 }
8126
8127 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8128 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008129 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008130 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8131 }
8132
John McCallca0408f2010-08-23 06:44:23 +00008133 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008134 CallArgs.push_back(To.takeAs<Expr>());
8135 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008136 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00008137 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008138 if (NeedsCollectableMemCpy)
8139 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008140 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008141 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008142 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008143 else
8144 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008145 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008146 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008147 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008148
Douglas Gregor06a9f362010-05-01 20:49:11 +00008149 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8150 Statements.push_back(Call.takeAs<Expr>());
8151 continue;
8152 }
8153
8154 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00008155 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008156 To.get(), From.get(),
8157 /*CopyingBaseSubobject=*/false,
8158 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008159 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008160 Diag(CurrentLocation, diag::note_member_synthesized_at)
8161 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8162 CopyAssignOperator->setInvalidDecl();
8163 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008164 }
8165
8166 // Success! Record the copy.
8167 Statements.push_back(Copy.takeAs<Stmt>());
8168 }
8169
8170 if (!Invalid) {
8171 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008172 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008173
John McCall60d7b3a2010-08-24 06:29:42 +00008174 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008175 if (Return.isInvalid())
8176 Invalid = true;
8177 else {
8178 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008179
8180 if (Trap.hasErrorOccurred()) {
8181 Diag(CurrentLocation, diag::note_member_synthesized_at)
8182 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8183 Invalid = true;
8184 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008185 }
8186 }
8187
8188 if (Invalid) {
8189 CopyAssignOperator->setInvalidDecl();
8190 return;
8191 }
8192
John McCall60d7b3a2010-08-24 06:29:42 +00008193 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008194 /*isStmtExpr=*/false);
8195 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8196 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008197
8198 if (ASTMutationListener *L = getASTMutationListener()) {
8199 L->CompletedImplicitDefinition(CopyAssignOperator);
8200 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008201}
8202
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008203Sema::ImplicitExceptionSpecification
8204Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8205 ImplicitExceptionSpecification ExceptSpec(Context);
8206
8207 if (ClassDecl->isInvalidDecl())
8208 return ExceptSpec;
8209
8210 // C++0x [except.spec]p14:
8211 // An implicitly declared special member function (Clause 12) shall have an
8212 // exception-specification. [...]
8213
8214 // It is unspecified whether or not an implicit move assignment operator
8215 // attempts to deduplicate calls to assignment operators of virtual bases are
8216 // made. As such, this exception specification is effectively unspecified.
8217 // Based on a similar decision made for constness in C++0x, we're erring on
8218 // the side of assuming such calls to be made regardless of whether they
8219 // actually happen.
8220 // Note that a move constructor is not implicitly declared when there are
8221 // virtual bases, but it can still be user-declared and explicitly defaulted.
8222 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8223 BaseEnd = ClassDecl->bases_end();
8224 Base != BaseEnd; ++Base) {
8225 if (Base->isVirtual())
8226 continue;
8227
8228 CXXRecordDecl *BaseClassDecl
8229 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8230 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8231 false, 0))
8232 ExceptSpec.CalledDecl(MoveAssign);
8233 }
8234
8235 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8236 BaseEnd = ClassDecl->vbases_end();
8237 Base != BaseEnd; ++Base) {
8238 CXXRecordDecl *BaseClassDecl
8239 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8240 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8241 false, 0))
8242 ExceptSpec.CalledDecl(MoveAssign);
8243 }
8244
8245 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8246 FieldEnd = ClassDecl->field_end();
8247 Field != FieldEnd;
8248 ++Field) {
8249 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8250 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8251 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8252 false, 0))
8253 ExceptSpec.CalledDecl(MoveAssign);
8254 }
8255 }
8256
8257 return ExceptSpec;
8258}
8259
8260CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8261 // Note: The following rules are largely analoguous to the move
8262 // constructor rules.
8263
8264 ImplicitExceptionSpecification Spec(
8265 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8266
8267 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8268 QualType RetType = Context.getLValueReferenceType(ArgType);
8269 ArgType = Context.getRValueReferenceType(ArgType);
8270
8271 // An implicitly-declared move assignment operator is an inline public
8272 // member of its class.
8273 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8274 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8275 SourceLocation ClassLoc = ClassDecl->getLocation();
8276 DeclarationNameInfo NameInfo(Name, ClassLoc);
8277 CXXMethodDecl *MoveAssignment
8278 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8279 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8280 /*TInfo=*/0, /*isStatic=*/false,
8281 /*StorageClassAsWritten=*/SC_None,
8282 /*isInline=*/true,
8283 /*isConstexpr=*/false,
8284 SourceLocation());
8285 MoveAssignment->setAccess(AS_public);
8286 MoveAssignment->setDefaulted();
8287 MoveAssignment->setImplicit();
8288 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8289
8290 // Add the parameter to the operator.
8291 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8292 ClassLoc, ClassLoc, /*Id=*/0,
8293 ArgType, /*TInfo=*/0,
8294 SC_None,
8295 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008296 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008297
8298 // Note that we have added this copy-assignment operator.
8299 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8300
8301 // C++0x [class.copy]p9:
8302 // If the definition of a class X does not explicitly declare a move
8303 // assignment operator, one will be implicitly declared as defaulted if and
8304 // only if:
8305 // [...]
8306 // - the move assignment operator would not be implicitly defined as
8307 // deleted.
8308 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8309 // Cache this result so that we don't try to generate this over and over
8310 // on every lookup, leaking memory and wasting time.
8311 ClassDecl->setFailedImplicitMoveAssignment();
8312 return 0;
8313 }
8314
8315 if (Scope *S = getScopeForContext(ClassDecl))
8316 PushOnScopeChains(MoveAssignment, S, false);
8317 ClassDecl->addDecl(MoveAssignment);
8318
8319 AddOverriddenMethods(ClassDecl, MoveAssignment);
8320 return MoveAssignment;
8321}
8322
8323void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8324 CXXMethodDecl *MoveAssignOperator) {
8325 assert((MoveAssignOperator->isDefaulted() &&
8326 MoveAssignOperator->isOverloadedOperator() &&
8327 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8328 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8329 "DefineImplicitMoveAssignment called for wrong function");
8330
8331 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8332
8333 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8334 MoveAssignOperator->setInvalidDecl();
8335 return;
8336 }
8337
8338 MoveAssignOperator->setUsed();
8339
8340 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8341 DiagnosticErrorTrap Trap(Diags);
8342
8343 // C++0x [class.copy]p28:
8344 // The implicitly-defined or move assignment operator for a non-union class
8345 // X performs memberwise move assignment of its subobjects. The direct base
8346 // classes of X are assigned first, in the order of their declaration in the
8347 // base-specifier-list, and then the immediate non-static data members of X
8348 // are assigned, in the order in which they were declared in the class
8349 // definition.
8350
8351 // The statements that form the synthesized function body.
8352 ASTOwningVector<Stmt*> Statements(*this);
8353
8354 // The parameter for the "other" object, which we are move from.
8355 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8356 QualType OtherRefType = Other->getType()->
8357 getAs<RValueReferenceType>()->getPointeeType();
8358 assert(OtherRefType.getQualifiers() == 0 &&
8359 "Bad argument type of defaulted move assignment");
8360
8361 // Our location for everything implicitly-generated.
8362 SourceLocation Loc = MoveAssignOperator->getLocation();
8363
8364 // Construct a reference to the "other" object. We'll be using this
8365 // throughout the generated ASTs.
8366 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8367 assert(OtherRef && "Reference to parameter cannot fail!");
8368 // Cast to rvalue.
8369 OtherRef = CastForMoving(*this, OtherRef);
8370
8371 // Construct the "this" pointer. We'll be using this throughout the generated
8372 // ASTs.
8373 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8374 assert(This && "Reference to this cannot fail!");
8375
8376 // Assign base classes.
8377 bool Invalid = false;
8378 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8379 E = ClassDecl->bases_end(); Base != E; ++Base) {
8380 // Form the assignment:
8381 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8382 QualType BaseType = Base->getType().getUnqualifiedType();
8383 if (!BaseType->isRecordType()) {
8384 Invalid = true;
8385 continue;
8386 }
8387
8388 CXXCastPath BasePath;
8389 BasePath.push_back(Base);
8390
8391 // Construct the "from" expression, which is an implicit cast to the
8392 // appropriately-qualified base type.
8393 Expr *From = OtherRef;
8394 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008395 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008396
8397 // Dereference "this".
8398 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8399
8400 // Implicitly cast "this" to the appropriately-qualified base type.
8401 To = ImpCastExprToType(To.take(),
8402 Context.getCVRQualifiedType(BaseType,
8403 MoveAssignOperator->getTypeQualifiers()),
8404 CK_UncheckedDerivedToBase,
8405 VK_LValue, &BasePath);
8406
8407 // Build the move.
8408 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8409 To.get(), From,
8410 /*CopyingBaseSubobject=*/true,
8411 /*Copying=*/false);
8412 if (Move.isInvalid()) {
8413 Diag(CurrentLocation, diag::note_member_synthesized_at)
8414 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8415 MoveAssignOperator->setInvalidDecl();
8416 return;
8417 }
8418
8419 // Success! Record the move.
8420 Statements.push_back(Move.takeAs<Expr>());
8421 }
8422
8423 // \brief Reference to the __builtin_memcpy function.
8424 Expr *BuiltinMemCpyRef = 0;
8425 // \brief Reference to the __builtin_objc_memmove_collectable function.
8426 Expr *CollectableMemCpyRef = 0;
8427
8428 // Assign non-static members.
8429 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8430 FieldEnd = ClassDecl->field_end();
8431 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008432 if (Field->isUnnamedBitfield())
8433 continue;
8434
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008435 // Check for members of reference type; we can't move those.
8436 if (Field->getType()->isReferenceType()) {
8437 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8438 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8439 Diag(Field->getLocation(), diag::note_declared_at);
8440 Diag(CurrentLocation, diag::note_member_synthesized_at)
8441 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8442 Invalid = true;
8443 continue;
8444 }
8445
8446 // Check for members of const-qualified, non-class type.
8447 QualType BaseType = Context.getBaseElementType(Field->getType());
8448 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8449 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8450 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8451 Diag(Field->getLocation(), diag::note_declared_at);
8452 Diag(CurrentLocation, diag::note_member_synthesized_at)
8453 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8454 Invalid = true;
8455 continue;
8456 }
8457
8458 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008459 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8460 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008461
8462 QualType FieldType = Field->getType().getNonReferenceType();
8463 if (FieldType->isIncompleteArrayType()) {
8464 assert(ClassDecl->hasFlexibleArrayMember() &&
8465 "Incomplete array type is not valid");
8466 continue;
8467 }
8468
8469 // Build references to the field in the object we're copying from and to.
8470 CXXScopeSpec SS; // Intentionally empty
8471 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8472 LookupMemberName);
8473 MemberLookup.addDecl(*Field);
8474 MemberLookup.resolveKind();
8475 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8476 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008477 SS, SourceLocation(), 0,
8478 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008479 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8480 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008481 SS, SourceLocation(), 0,
8482 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008483 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8484 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8485
8486 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8487 "Member reference with rvalue base must be rvalue except for reference "
8488 "members, which aren't allowed for move assignment.");
8489
8490 // If the field should be copied with __builtin_memcpy rather than via
8491 // explicit assignments, do so. This optimization only applies for arrays
8492 // of scalars and arrays of class type with trivial move-assignment
8493 // operators.
8494 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8495 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8496 // Compute the size of the memory buffer to be copied.
8497 QualType SizeType = Context.getSizeType();
8498 llvm::APInt Size(Context.getTypeSize(SizeType),
8499 Context.getTypeSizeInChars(BaseType).getQuantity());
8500 for (const ConstantArrayType *Array
8501 = Context.getAsConstantArrayType(FieldType);
8502 Array;
8503 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8504 llvm::APInt ArraySize
8505 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8506 Size *= ArraySize;
8507 }
8508
Douglas Gregor45d3d712011-09-01 02:09:07 +00008509 // Take the address of the field references for "from" and "to". We
8510 // directly construct UnaryOperators here because semantic analysis
8511 // does not permit us to take the address of an xvalue.
8512 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8513 Context.getPointerType(From.get()->getType()),
8514 VK_RValue, OK_Ordinary, Loc);
8515 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8516 Context.getPointerType(To.get()->getType()),
8517 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008518
8519 bool NeedsCollectableMemCpy =
8520 (BaseType->isRecordType() &&
8521 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8522
8523 if (NeedsCollectableMemCpy) {
8524 if (!CollectableMemCpyRef) {
8525 // Create a reference to the __builtin_objc_memmove_collectable function.
8526 LookupResult R(*this,
8527 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8528 Loc, LookupOrdinaryName);
8529 LookupName(R, TUScope, true);
8530
8531 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8532 if (!CollectableMemCpy) {
8533 // Something went horribly wrong earlier, and we will have
8534 // complained about it.
8535 Invalid = true;
8536 continue;
8537 }
8538
8539 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8540 CollectableMemCpy->getType(),
8541 VK_LValue, Loc, 0).take();
8542 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8543 }
8544 }
8545 // Create a reference to the __builtin_memcpy builtin function.
8546 else if (!BuiltinMemCpyRef) {
8547 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8548 LookupOrdinaryName);
8549 LookupName(R, TUScope, true);
8550
8551 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8552 if (!BuiltinMemCpy) {
8553 // Something went horribly wrong earlier, and we will have complained
8554 // about it.
8555 Invalid = true;
8556 continue;
8557 }
8558
8559 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8560 BuiltinMemCpy->getType(),
8561 VK_LValue, Loc, 0).take();
8562 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8563 }
8564
8565 ASTOwningVector<Expr*> CallArgs(*this);
8566 CallArgs.push_back(To.takeAs<Expr>());
8567 CallArgs.push_back(From.takeAs<Expr>());
8568 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8569 ExprResult Call = ExprError();
8570 if (NeedsCollectableMemCpy)
8571 Call = ActOnCallExpr(/*Scope=*/0,
8572 CollectableMemCpyRef,
8573 Loc, move_arg(CallArgs),
8574 Loc);
8575 else
8576 Call = ActOnCallExpr(/*Scope=*/0,
8577 BuiltinMemCpyRef,
8578 Loc, move_arg(CallArgs),
8579 Loc);
8580
8581 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8582 Statements.push_back(Call.takeAs<Expr>());
8583 continue;
8584 }
8585
8586 // Build the move of this field.
8587 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8588 To.get(), From.get(),
8589 /*CopyingBaseSubobject=*/false,
8590 /*Copying=*/false);
8591 if (Move.isInvalid()) {
8592 Diag(CurrentLocation, diag::note_member_synthesized_at)
8593 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8594 MoveAssignOperator->setInvalidDecl();
8595 return;
8596 }
8597
8598 // Success! Record the copy.
8599 Statements.push_back(Move.takeAs<Stmt>());
8600 }
8601
8602 if (!Invalid) {
8603 // Add a "return *this;"
8604 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8605
8606 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8607 if (Return.isInvalid())
8608 Invalid = true;
8609 else {
8610 Statements.push_back(Return.takeAs<Stmt>());
8611
8612 if (Trap.hasErrorOccurred()) {
8613 Diag(CurrentLocation, diag::note_member_synthesized_at)
8614 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8615 Invalid = true;
8616 }
8617 }
8618 }
8619
8620 if (Invalid) {
8621 MoveAssignOperator->setInvalidDecl();
8622 return;
8623 }
8624
8625 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8626 /*isStmtExpr=*/false);
8627 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8628 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8629
8630 if (ASTMutationListener *L = getASTMutationListener()) {
8631 L->CompletedImplicitDefinition(MoveAssignOperator);
8632 }
8633}
8634
Sean Hunt49634cf2011-05-13 06:10:58 +00008635std::pair<Sema::ImplicitExceptionSpecification, bool>
8636Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008637 if (ClassDecl->isInvalidDecl())
8638 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8639
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008640 // C++ [class.copy]p5:
8641 // The implicitly-declared copy constructor for a class X will
8642 // have the form
8643 //
8644 // X::X(const X&)
8645 //
8646 // if
Sean Huntc530d172011-06-10 04:44:37 +00008647 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008648 bool HasConstCopyConstructor = true;
8649
8650 // -- each direct or virtual base class B of X has a copy
8651 // constructor whose first parameter is of type const B& or
8652 // const volatile B&, and
8653 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8654 BaseEnd = ClassDecl->bases_end();
8655 HasConstCopyConstructor && Base != BaseEnd;
8656 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008657 // Virtual bases are handled below.
8658 if (Base->isVirtual())
8659 continue;
8660
Douglas Gregor22584312010-07-02 23:41:54 +00008661 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008662 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008663 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8664 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008665 }
8666
8667 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8668 BaseEnd = ClassDecl->vbases_end();
8669 HasConstCopyConstructor && Base != BaseEnd;
8670 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008671 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008672 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008673 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8674 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008675 }
8676
8677 // -- for all the nonstatic data members of X that are of a
8678 // class type M (or array thereof), each such class type
8679 // has a copy constructor whose first parameter is of type
8680 // const M& or const volatile M&.
8681 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8682 FieldEnd = ClassDecl->field_end();
8683 HasConstCopyConstructor && Field != FieldEnd;
8684 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008685 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008686 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008687 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8688 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008689 }
8690 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008691 // Otherwise, the implicitly declared copy constructor will have
8692 // the form
8693 //
8694 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008695
Douglas Gregor0d405db2010-07-01 20:59:04 +00008696 // C++ [except.spec]p14:
8697 // An implicitly declared special member function (Clause 12) shall have an
8698 // exception-specification. [...]
8699 ImplicitExceptionSpecification ExceptSpec(Context);
8700 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8701 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8702 BaseEnd = ClassDecl->bases_end();
8703 Base != BaseEnd;
8704 ++Base) {
8705 // Virtual bases are handled below.
8706 if (Base->isVirtual())
8707 continue;
8708
Douglas Gregor22584312010-07-02 23:41:54 +00008709 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008710 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008711 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008712 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008713 ExceptSpec.CalledDecl(CopyConstructor);
8714 }
8715 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8716 BaseEnd = ClassDecl->vbases_end();
8717 Base != BaseEnd;
8718 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008719 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008720 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008721 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008722 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008723 ExceptSpec.CalledDecl(CopyConstructor);
8724 }
8725 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8726 FieldEnd = ClassDecl->field_end();
8727 Field != FieldEnd;
8728 ++Field) {
8729 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008730 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8731 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008732 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008733 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008734 }
8735 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008736
Sean Hunt49634cf2011-05-13 06:10:58 +00008737 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8738}
8739
8740CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8741 CXXRecordDecl *ClassDecl) {
8742 // C++ [class.copy]p4:
8743 // If the class definition does not explicitly declare a copy
8744 // constructor, one is declared implicitly.
8745
8746 ImplicitExceptionSpecification Spec(Context);
8747 bool Const;
8748 llvm::tie(Spec, Const) =
8749 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8750
8751 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8752 QualType ArgType = ClassType;
8753 if (Const)
8754 ArgType = ArgType.withConst();
8755 ArgType = Context.getLValueReferenceType(ArgType);
8756
8757 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8758
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008759 DeclarationName Name
8760 = Context.DeclarationNames.getCXXConstructorName(
8761 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008762 SourceLocation ClassLoc = ClassDecl->getLocation();
8763 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008764
8765 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008766 // member of its class.
8767 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8768 Context, ClassDecl, ClassLoc, NameInfo,
8769 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8770 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8771 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8772 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008773 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008774 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008775 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008776
Douglas Gregor22584312010-07-02 23:41:54 +00008777 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008778 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8779
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008780 // Add the parameter to the constructor.
8781 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008782 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008783 /*IdentifierInfo=*/0,
8784 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008785 SC_None,
8786 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008787 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008788
Douglas Gregor23c94db2010-07-02 17:43:08 +00008789 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008790 PushOnScopeChains(CopyConstructor, S, false);
8791 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008792
Nico Weberafcc96a2012-01-23 03:19:29 +00008793 // C++11 [class.copy]p8:
8794 // ... If the class definition does not explicitly declare a copy
8795 // constructor, there is no user-declared move constructor, and there is no
8796 // user-declared move assignment operator, a copy constructor is implicitly
8797 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008798 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008799 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber28976602012-01-23 04:01:33 +00008800 !getLangOptions().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008801 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008802 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008803
8804 return CopyConstructor;
8805}
8806
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008807void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008808 CXXConstructorDecl *CopyConstructor) {
8809 assert((CopyConstructor->isDefaulted() &&
8810 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008811 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008812 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008813
Anders Carlsson63010a72010-04-23 16:24:12 +00008814 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008815 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008816
Douglas Gregor39957dc2010-05-01 15:04:51 +00008817 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008818 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008819
Sean Huntcbb67482011-01-08 20:30:50 +00008820 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008821 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008822 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008823 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008824 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008825 } else {
8826 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8827 CopyConstructor->getLocation(),
8828 MultiStmtArg(*this, 0, 0),
8829 /*isStmtExpr=*/false)
8830 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008831 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008832 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008833
8834 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008835 if (ASTMutationListener *L = getASTMutationListener()) {
8836 L->CompletedImplicitDefinition(CopyConstructor);
8837 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008838}
8839
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008840Sema::ImplicitExceptionSpecification
8841Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8842 // C++ [except.spec]p14:
8843 // An implicitly declared special member function (Clause 12) shall have an
8844 // exception-specification. [...]
8845 ImplicitExceptionSpecification ExceptSpec(Context);
8846 if (ClassDecl->isInvalidDecl())
8847 return ExceptSpec;
8848
8849 // Direct base-class constructors.
8850 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8851 BEnd = ClassDecl->bases_end();
8852 B != BEnd; ++B) {
8853 if (B->isVirtual()) // Handled below.
8854 continue;
8855
8856 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8857 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8858 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8859 // If this is a deleted function, add it anyway. This might be conformant
8860 // with the standard. This might not. I'm not sure. It might not matter.
8861 if (Constructor)
8862 ExceptSpec.CalledDecl(Constructor);
8863 }
8864 }
8865
8866 // Virtual base-class constructors.
8867 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8868 BEnd = ClassDecl->vbases_end();
8869 B != BEnd; ++B) {
8870 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8871 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8872 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8873 // If this is a deleted function, add it anyway. This might be conformant
8874 // with the standard. This might not. I'm not sure. It might not matter.
8875 if (Constructor)
8876 ExceptSpec.CalledDecl(Constructor);
8877 }
8878 }
8879
8880 // Field constructors.
8881 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8882 FEnd = ClassDecl->field_end();
8883 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008884 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008885 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8886 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8887 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8888 // If this is a deleted function, add it anyway. This might be conformant
8889 // with the standard. This might not. I'm not sure. It might not matter.
8890 // In particular, the problem is that this function never gets called. It
8891 // might just be ill-formed because this function attempts to refer to
8892 // a deleted function here.
8893 if (Constructor)
8894 ExceptSpec.CalledDecl(Constructor);
8895 }
8896 }
8897
8898 return ExceptSpec;
8899}
8900
8901CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8902 CXXRecordDecl *ClassDecl) {
8903 ImplicitExceptionSpecification Spec(
8904 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8905
8906 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8907 QualType ArgType = Context.getRValueReferenceType(ClassType);
8908
8909 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8910
8911 DeclarationName Name
8912 = Context.DeclarationNames.getCXXConstructorName(
8913 Context.getCanonicalType(ClassType));
8914 SourceLocation ClassLoc = ClassDecl->getLocation();
8915 DeclarationNameInfo NameInfo(Name, ClassLoc);
8916
8917 // C++0x [class.copy]p11:
8918 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008919 // member of its class.
8920 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8921 Context, ClassDecl, ClassLoc, NameInfo,
8922 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8923 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8924 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8925 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008926 MoveConstructor->setAccess(AS_public);
8927 MoveConstructor->setDefaulted();
8928 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008929
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008930 // Add the parameter to the constructor.
8931 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8932 ClassLoc, ClassLoc,
8933 /*IdentifierInfo=*/0,
8934 ArgType, /*TInfo=*/0,
8935 SC_None,
8936 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008937 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008938
8939 // C++0x [class.copy]p9:
8940 // If the definition of a class X does not explicitly declare a move
8941 // constructor, one will be implicitly declared as defaulted if and only if:
8942 // [...]
8943 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008944 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008945 // Cache this result so that we don't try to generate this over and over
8946 // on every lookup, leaking memory and wasting time.
8947 ClassDecl->setFailedImplicitMoveConstructor();
8948 return 0;
8949 }
8950
8951 // Note that we have declared this constructor.
8952 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8953
8954 if (Scope *S = getScopeForContext(ClassDecl))
8955 PushOnScopeChains(MoveConstructor, S, false);
8956 ClassDecl->addDecl(MoveConstructor);
8957
8958 return MoveConstructor;
8959}
8960
8961void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8962 CXXConstructorDecl *MoveConstructor) {
8963 assert((MoveConstructor->isDefaulted() &&
8964 MoveConstructor->isMoveConstructor() &&
8965 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8966 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8967
8968 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8969 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8970
8971 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8972 DiagnosticErrorTrap Trap(Diags);
8973
8974 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8975 Trap.hasErrorOccurred()) {
8976 Diag(CurrentLocation, diag::note_member_synthesized_at)
8977 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8978 MoveConstructor->setInvalidDecl();
8979 } else {
8980 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8981 MoveConstructor->getLocation(),
8982 MultiStmtArg(*this, 0, 0),
8983 /*isStmtExpr=*/false)
8984 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008985 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008986 }
8987
8988 MoveConstructor->setUsed();
8989
8990 if (ASTMutationListener *L = getASTMutationListener()) {
8991 L->CompletedImplicitDefinition(MoveConstructor);
8992 }
8993}
8994
John McCall60d7b3a2010-08-24 06:29:42 +00008995ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008996Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008997 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008998 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008999 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009000 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009001 unsigned ConstructKind,
9002 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009003 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009004
Douglas Gregor2f599792010-04-02 18:24:57 +00009005 // C++0x [class.copy]p34:
9006 // When certain criteria are met, an implementation is allowed to
9007 // omit the copy/move construction of a class object, even if the
9008 // copy/move constructor and/or destructor for the object have
9009 // side effects. [...]
9010 // - when a temporary class object that has not been bound to a
9011 // reference (12.2) would be copied/moved to a class object
9012 // with the same cv-unqualified type, the copy/move operation
9013 // can be omitted by constructing the temporary object
9014 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009015 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00009016 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009017 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009018 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009019 }
Mike Stump1eb44332009-09-09 15:08:12 +00009020
9021 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009022 Elidable, move(ExprArgs), HadMultipleCandidates,
9023 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009024}
9025
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009026/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9027/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009028ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009029Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9030 CXXConstructorDecl *Constructor, bool Elidable,
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 Carlssonf47511a2009-09-07 22:23:31 +00009036 unsigned NumExprs = ExprArgs.size();
9037 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009038
Nick Lewycky909a70d2011-03-25 01:44:32 +00009039 for (specific_attr_iterator<NonNullAttr>
9040 i = Constructor->specific_attr_begin<NonNullAttr>(),
9041 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9042 const NonNullAttr *NonNull = *i;
9043 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9044 }
9045
Eli Friedman5f2987c2012-02-02 03:46:19 +00009046 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009047 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009048 Constructor, Elidable, Exprs, NumExprs,
9049 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009050 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9051 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009052}
9053
Mike Stump1eb44332009-09-09 15:08:12 +00009054bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009055 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009056 MultiExprArg Exprs,
9057 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009058 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009059 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009060 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009061 move(Exprs), HadMultipleCandidates, false,
9062 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009063 if (TempResult.isInvalid())
9064 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009065
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009066 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009067 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009068 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009069 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009070 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009071
Anders Carlssonfe2de492009-08-25 05:18:00 +00009072 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009073}
9074
John McCall68c6c9a2010-02-02 09:10:11 +00009075void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009076 if (VD->isInvalidDecl()) return;
9077
John McCall68c6c9a2010-02-02 09:10:11 +00009078 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009079 if (ClassDecl->isInvalidDecl()) return;
9080 if (ClassDecl->hasTrivialDestructor()) return;
9081 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009082
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009083 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009084 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009085 CheckDestructorAccess(VD->getLocation(), Destructor,
9086 PDiag(diag::err_access_dtor_var)
9087 << VD->getDeclName()
9088 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009089
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009090 if (!VD->hasGlobalStorage()) return;
9091
9092 // Emit warning for non-trivial dtor in global scope (a real global,
9093 // class-static, function-static).
9094 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9095
9096 // TODO: this should be re-enabled for static locals by !CXAAtExit
9097 if (!VD->isStaticLocal())
9098 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009099}
9100
Mike Stump1eb44332009-09-09 15:08:12 +00009101/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009102/// ActOnDeclarator, when a C++ direct initializer is present.
9103/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00009104void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00009105 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009106 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00009107 SourceLocation RParenLoc,
9108 bool TypeMayContainAuto) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009109 // If there is no declaration, there was an error parsing it. Just ignore
9110 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00009111 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009112 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009113
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009114 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9115 if (!VDecl) {
9116 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9117 RealDecl->setInvalidDecl();
9118 return;
9119 }
9120
Eli Friedman6aeaa602012-01-05 22:34:08 +00009121 // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith34b41d92011-02-20 03:19:35 +00009122 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Eli Friedman6aeaa602012-01-05 22:34:08 +00009123 if (Exprs.size() == 0) {
9124 // It isn't possible to write this directly, but it is possible to
9125 // end up in this situation with "auto x(some_pack...);"
9126 Diag(LParenLoc, diag::err_auto_var_init_no_expression)
9127 << VDecl->getDeclName() << VDecl->getType()
9128 << VDecl->getSourceRange();
9129 RealDecl->setInvalidDecl();
9130 return;
9131 }
9132
Richard Smith34b41d92011-02-20 03:19:35 +00009133 if (Exprs.size() > 1) {
9134 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9135 diag::err_auto_var_init_multiple_expressions)
9136 << VDecl->getDeclName() << VDecl->getType()
9137 << VDecl->getSourceRange();
9138 RealDecl->setInvalidDecl();
9139 return;
9140 }
9141
9142 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00009143 TypeSourceInfo *DeducedType = 0;
Sebastian Redlb832f6d2012-01-23 22:09:39 +00009144 if (DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType) ==
9145 DAR_Failed)
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00009146 DiagnoseAutoDeductionFailure(VDecl, Init);
Richard Smitha085da82011-03-17 16:11:59 +00009147 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00009148 RealDecl->setInvalidDecl();
9149 return;
9150 }
Richard Smitha085da82011-03-17 16:11:59 +00009151 VDecl->setTypeSourceInfo(DeducedType);
9152 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00009153
John McCallf85e1932011-06-15 23:02:42 +00009154 // In ARC, infer lifetime.
9155 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9156 VDecl->setInvalidDecl();
9157
Richard Smith34b41d92011-02-20 03:19:35 +00009158 // If this is a redeclaration, check that the type we just deduced matches
9159 // the previously declared type.
Douglas Gregoref96ee02012-01-14 16:38:05 +00009160 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith34b41d92011-02-20 03:19:35 +00009161 MergeVarDeclTypes(VDecl, Old);
9162 }
9163
Douglas Gregor83ddad32009-08-26 21:14:46 +00009164 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009165 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009166 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9167 //
9168 // Clients that want to distinguish between the two forms, can check for
9169 // direct initializer using VarDecl::hasCXXDirectInitializer().
9170 // A major benefit is that clients that don't particularly care about which
9171 // exactly form was it (like the CodeGen) can handle both cases without
9172 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009173
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009174 // C++ 8.5p11:
9175 // The form of initialization (using parentheses or '=') is generally
9176 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009177 // class type.
9178
Douglas Gregor4dffad62010-02-11 22:55:30 +00009179 if (!VDecl->getType()->isDependentType() &&
Douglas Gregord24c3062011-10-10 16:05:18 +00009180 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor4dffad62010-02-11 22:55:30 +00009181 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00009182 diag::err_typecheck_decl_incomplete_type)) {
9183 VDecl->setInvalidDecl();
9184 return;
9185 }
9186
Douglas Gregor90f93822009-12-22 22:17:25 +00009187 // The variable can not have an abstract class type.
9188 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9189 diag::err_abstract_type_in_decl,
9190 AbstractVariableType))
9191 VDecl->setInvalidDecl();
9192
Sebastian Redl31310a22010-02-01 20:16:42 +00009193 const VarDecl *Def;
9194 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00009195 Diag(VDecl->getLocation(), diag::err_redefinition)
9196 << VDecl->getDeclName();
9197 Diag(Def->getLocation(), diag::note_previous_definition);
9198 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009199 return;
9200 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00009201
Douglas Gregor3a91abf2010-08-24 05:27:49 +00009202 // C++ [class.static.data]p4
9203 // If a static data member is of const integral or const
9204 // enumeration type, its declaration in the class definition can
9205 // specify a constant-initializer which shall be an integral
9206 // constant expression (5.19). In that case, the member can appear
9207 // in integral constant expressions. The member shall still be
9208 // defined in a namespace scope if it is used in the program and the
9209 // namespace scope definition shall not contain an initializer.
9210 //
9211 // We already performed a redefinition check above, but for static
9212 // data members we also need to check whether there was an in-class
9213 // declaration with an initializer.
9214 const VarDecl* PrevInit = 0;
9215 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9216 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9217 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9218 return;
9219 }
9220
Douglas Gregora31040f2010-12-16 01:31:22 +00009221 bool IsDependent = false;
9222 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9223 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9224 VDecl->setInvalidDecl();
9225 return;
9226 }
9227
9228 if (Exprs.get()[I]->isTypeDependent())
9229 IsDependent = true;
9230 }
9231
Douglas Gregor4dffad62010-02-11 22:55:30 +00009232 // If either the declaration has a dependent type or if any of the
9233 // expressions is type-dependent, we represent the initialization
9234 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00009235 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00009236 // Let clients know that initialization was done with a direct initializer.
9237 VDecl->setCXXDirectInitializer(true);
9238
9239 // Store the initialization expressions as a ParenListExpr.
9240 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00009241 VDecl->setInit(new (Context) ParenListExpr(
9242 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9243 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00009244 return;
9245 }
Douglas Gregor90f93822009-12-22 22:17:25 +00009246
9247 // Capture the variable that is being initialized and the style of
9248 // initialization.
9249 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9250
9251 // FIXME: Poor source location information.
9252 InitializationKind Kind
9253 = InitializationKind::CreateDirect(VDecl->getLocation(),
9254 LParenLoc, RParenLoc);
9255
Douglas Gregord24c3062011-10-10 16:05:18 +00009256 QualType T = VDecl->getType();
Douglas Gregor90f93822009-12-22 22:17:25 +00009257 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00009258 Exprs.get(), Exprs.size());
Douglas Gregord24c3062011-10-10 16:05:18 +00009259 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregor90f93822009-12-22 22:17:25 +00009260 if (Result.isInvalid()) {
9261 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009262 return;
Douglas Gregord24c3062011-10-10 16:05:18 +00009263 } else if (T != VDecl->getType()) {
9264 VDecl->setType(T);
9265 Result.get()->setType(T);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009266 }
John McCallb4eb64d2010-10-08 02:01:28 +00009267
Douglas Gregord24c3062011-10-10 16:05:18 +00009268
Richard Smithc6d990a2011-09-29 19:11:37 +00009269 Expr *Init = Result.get();
9270 CheckImplicitConversions(Init, LParenLoc);
Richard Smithc6d990a2011-09-29 19:11:37 +00009271
9272 Init = MaybeCreateExprWithCleanups(Init);
9273 VDecl->setInit(Init);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009274 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009275
John McCall2998d6b2011-01-19 11:48:09 +00009276 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009277}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00009278
Douglas Gregor39da0b82009-09-09 23:08:42 +00009279/// \brief Given a constructor and the set of arguments provided for the
9280/// constructor, convert the arguments and add any required default arguments
9281/// to form a proper call to this constructor.
9282///
9283/// \returns true if an error occurred, false otherwise.
9284bool
9285Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9286 MultiExprArg ArgsPtr,
9287 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009288 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009289 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9290 unsigned NumArgs = ArgsPtr.size();
9291 Expr **Args = (Expr **)ArgsPtr.get();
9292
9293 const FunctionProtoType *Proto
9294 = Constructor->getType()->getAs<FunctionProtoType>();
9295 assert(Proto && "Constructor without a prototype?");
9296 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009297
9298 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009299 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009300 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009301 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009302 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009303
9304 VariadicCallType CallType =
9305 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009306 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009307 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9308 Proto, 0, Args, NumArgs, AllArgs,
9309 CallType);
9310 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9311 ConvertedArgs.push_back(AllArgs[i]);
9312 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009313}
9314
Anders Carlsson20d45d22009-12-12 00:32:00 +00009315static inline bool
9316CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9317 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009318 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009319 if (isa<NamespaceDecl>(DC)) {
9320 return SemaRef.Diag(FnDecl->getLocation(),
9321 diag::err_operator_new_delete_declared_in_namespace)
9322 << FnDecl->getDeclName();
9323 }
9324
9325 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009326 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009327 return SemaRef.Diag(FnDecl->getLocation(),
9328 diag::err_operator_new_delete_declared_static)
9329 << FnDecl->getDeclName();
9330 }
9331
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009332 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009333}
9334
Anders Carlsson156c78e2009-12-13 17:53:43 +00009335static inline bool
9336CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9337 CanQualType ExpectedResultType,
9338 CanQualType ExpectedFirstParamType,
9339 unsigned DependentParamTypeDiag,
9340 unsigned InvalidParamTypeDiag) {
9341 QualType ResultType =
9342 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9343
9344 // Check that the result type is not dependent.
9345 if (ResultType->isDependentType())
9346 return SemaRef.Diag(FnDecl->getLocation(),
9347 diag::err_operator_new_delete_dependent_result_type)
9348 << FnDecl->getDeclName() << ExpectedResultType;
9349
9350 // Check that the result type is what we expect.
9351 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9352 return SemaRef.Diag(FnDecl->getLocation(),
9353 diag::err_operator_new_delete_invalid_result_type)
9354 << FnDecl->getDeclName() << ExpectedResultType;
9355
9356 // A function template must have at least 2 parameters.
9357 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9358 return SemaRef.Diag(FnDecl->getLocation(),
9359 diag::err_operator_new_delete_template_too_few_parameters)
9360 << FnDecl->getDeclName();
9361
9362 // The function decl must have at least 1 parameter.
9363 if (FnDecl->getNumParams() == 0)
9364 return SemaRef.Diag(FnDecl->getLocation(),
9365 diag::err_operator_new_delete_too_few_parameters)
9366 << FnDecl->getDeclName();
9367
9368 // Check the the first parameter type is not dependent.
9369 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9370 if (FirstParamType->isDependentType())
9371 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9372 << FnDecl->getDeclName() << ExpectedFirstParamType;
9373
9374 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009375 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009376 ExpectedFirstParamType)
9377 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9378 << FnDecl->getDeclName() << ExpectedFirstParamType;
9379
9380 return false;
9381}
9382
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009383static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009384CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009385 // C++ [basic.stc.dynamic.allocation]p1:
9386 // A program is ill-formed if an allocation function is declared in a
9387 // namespace scope other than global scope or declared static in global
9388 // scope.
9389 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9390 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009391
9392 CanQualType SizeTy =
9393 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9394
9395 // C++ [basic.stc.dynamic.allocation]p1:
9396 // The return type shall be void*. The first parameter shall have type
9397 // std::size_t.
9398 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9399 SizeTy,
9400 diag::err_operator_new_dependent_param_type,
9401 diag::err_operator_new_param_type))
9402 return true;
9403
9404 // C++ [basic.stc.dynamic.allocation]p1:
9405 // The first parameter shall not have an associated default argument.
9406 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009407 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009408 diag::err_operator_new_default_arg)
9409 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9410
9411 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009412}
9413
9414static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009415CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9416 // C++ [basic.stc.dynamic.deallocation]p1:
9417 // A program is ill-formed if deallocation functions are declared in a
9418 // namespace scope other than global scope or declared static in global
9419 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009420 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9421 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009422
9423 // C++ [basic.stc.dynamic.deallocation]p2:
9424 // Each deallocation function shall return void and its first parameter
9425 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009426 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9427 SemaRef.Context.VoidPtrTy,
9428 diag::err_operator_delete_dependent_param_type,
9429 diag::err_operator_delete_param_type))
9430 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009431
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009432 return false;
9433}
9434
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009435/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9436/// of this overloaded operator is well-formed. If so, returns false;
9437/// otherwise, emits appropriate diagnostics and returns true.
9438bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009439 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009440 "Expected an overloaded operator declaration");
9441
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009442 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9443
Mike Stump1eb44332009-09-09 15:08:12 +00009444 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009445 // The allocation and deallocation functions, operator new,
9446 // operator new[], operator delete and operator delete[], are
9447 // described completely in 3.7.3. The attributes and restrictions
9448 // found in the rest of this subclause do not apply to them unless
9449 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009450 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009451 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009452
Anders Carlssona3ccda52009-12-12 00:26:23 +00009453 if (Op == OO_New || Op == OO_Array_New)
9454 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009455
9456 // C++ [over.oper]p6:
9457 // An operator function shall either be a non-static member
9458 // function or be a non-member function and have at least one
9459 // parameter whose type is a class, a reference to a class, an
9460 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009461 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9462 if (MethodDecl->isStatic())
9463 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009464 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009465 } else {
9466 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009467 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9468 ParamEnd = FnDecl->param_end();
9469 Param != ParamEnd; ++Param) {
9470 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009471 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9472 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009473 ClassOrEnumParam = true;
9474 break;
9475 }
9476 }
9477
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009478 if (!ClassOrEnumParam)
9479 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009480 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009481 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009482 }
9483
9484 // C++ [over.oper]p8:
9485 // An operator function cannot have default arguments (8.3.6),
9486 // except where explicitly stated below.
9487 //
Mike Stump1eb44332009-09-09 15:08:12 +00009488 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009489 // (C++ [over.call]p1).
9490 if (Op != OO_Call) {
9491 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9492 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009493 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009494 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009495 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009496 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009497 }
9498 }
9499
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009500 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9501 { false, false, false }
9502#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9503 , { Unary, Binary, MemberOnly }
9504#include "clang/Basic/OperatorKinds.def"
9505 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009506
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009507 bool CanBeUnaryOperator = OperatorUses[Op][0];
9508 bool CanBeBinaryOperator = OperatorUses[Op][1];
9509 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009510
9511 // C++ [over.oper]p8:
9512 // [...] Operator functions cannot have more or fewer parameters
9513 // than the number required for the corresponding operator, as
9514 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009515 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009516 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009517 if (Op != OO_Call &&
9518 ((NumParams == 1 && !CanBeUnaryOperator) ||
9519 (NumParams == 2 && !CanBeBinaryOperator) ||
9520 (NumParams < 1) || (NumParams > 2))) {
9521 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009522 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009523 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009524 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009525 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009526 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009527 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009528 assert(CanBeBinaryOperator &&
9529 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009530 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009531 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009532
Chris Lattner416e46f2008-11-21 07:57:12 +00009533 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009534 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009535 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009536
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009537 // Overloaded operators other than operator() cannot be variadic.
9538 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009539 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009540 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009541 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009542 }
9543
9544 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009545 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9546 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009547 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009548 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009549 }
9550
9551 // C++ [over.inc]p1:
9552 // The user-defined function called operator++ implements the
9553 // prefix and postfix ++ operator. If this function is a member
9554 // function with no parameters, or a non-member function with one
9555 // parameter of class or enumeration type, it defines the prefix
9556 // increment operator ++ for objects of that type. If the function
9557 // is a member function with one parameter (which shall be of type
9558 // int) or a non-member function with two parameters (the second
9559 // of which shall be of type int), it defines the postfix
9560 // increment operator ++ for objects of that type.
9561 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9562 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9563 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009564 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009565 ParamIsInt = BT->getKind() == BuiltinType::Int;
9566
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009567 if (!ParamIsInt)
9568 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009569 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009570 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009571 }
9572
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009573 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009574}
Chris Lattner5a003a42008-12-17 07:09:26 +00009575
Sean Hunta6c058d2010-01-13 09:01:02 +00009576/// CheckLiteralOperatorDeclaration - Check whether the declaration
9577/// of this literal operator function is well-formed. If so, returns
9578/// false; otherwise, emits appropriate diagnostics and returns true.
9579bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9580 DeclContext *DC = FnDecl->getDeclContext();
9581 Decl::Kind Kind = DC->getDeclKind();
9582 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9583 Kind != Decl::LinkageSpec) {
9584 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9585 << FnDecl->getDeclName();
9586 return true;
9587 }
9588
9589 bool Valid = false;
9590
Sean Hunt216c2782010-04-07 23:11:06 +00009591 // template <char...> type operator "" name() is the only valid template
9592 // signature, and the only valid signature with no parameters.
9593 if (FnDecl->param_size() == 0) {
9594 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9595 // Must have only one template parameter
9596 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9597 if (Params->size() == 1) {
9598 NonTypeTemplateParmDecl *PmDecl =
9599 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009600
Sean Hunt216c2782010-04-07 23:11:06 +00009601 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009602 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9603 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9604 Valid = true;
9605 }
9606 }
9607 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009608 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009609 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9610
Sean Hunta6c058d2010-01-13 09:01:02 +00009611 QualType T = (*Param)->getType();
9612
Sean Hunt30019c02010-04-07 22:57:35 +00009613 // unsigned long long int, long double, and any character type are allowed
9614 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009615 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9616 Context.hasSameType(T, Context.LongDoubleTy) ||
9617 Context.hasSameType(T, Context.CharTy) ||
9618 Context.hasSameType(T, Context.WCharTy) ||
9619 Context.hasSameType(T, Context.Char16Ty) ||
9620 Context.hasSameType(T, Context.Char32Ty)) {
9621 if (++Param == FnDecl->param_end())
9622 Valid = true;
9623 goto FinishedParams;
9624 }
9625
Sean Hunt30019c02010-04-07 22:57:35 +00009626 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009627 const PointerType *PT = T->getAs<PointerType>();
9628 if (!PT)
9629 goto FinishedParams;
9630 T = PT->getPointeeType();
9631 if (!T.isConstQualified())
9632 goto FinishedParams;
9633 T = T.getUnqualifiedType();
9634
9635 // Move on to the second parameter;
9636 ++Param;
9637
9638 // If there is no second parameter, the first must be a const char *
9639 if (Param == FnDecl->param_end()) {
9640 if (Context.hasSameType(T, Context.CharTy))
9641 Valid = true;
9642 goto FinishedParams;
9643 }
9644
9645 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9646 // are allowed as the first parameter to a two-parameter function
9647 if (!(Context.hasSameType(T, Context.CharTy) ||
9648 Context.hasSameType(T, Context.WCharTy) ||
9649 Context.hasSameType(T, Context.Char16Ty) ||
9650 Context.hasSameType(T, Context.Char32Ty)))
9651 goto FinishedParams;
9652
9653 // The second and final parameter must be an std::size_t
9654 T = (*Param)->getType().getUnqualifiedType();
9655 if (Context.hasSameType(T, Context.getSizeType()) &&
9656 ++Param == FnDecl->param_end())
9657 Valid = true;
9658 }
9659
9660 // FIXME: This diagnostic is absolutely terrible.
9661FinishedParams:
9662 if (!Valid) {
9663 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9664 << FnDecl->getDeclName();
9665 return true;
9666 }
9667
Douglas Gregor1155c422011-08-30 22:40:35 +00009668 StringRef LiteralName
9669 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9670 if (LiteralName[0] != '_') {
9671 // C++0x [usrlit.suffix]p1:
9672 // Literal suffix identifiers that do not start with an underscore are
9673 // reserved for future standardization.
9674 bool IsHexFloat = true;
9675 if (LiteralName.size() > 1 &&
9676 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9677 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9678 if (!isdigit(LiteralName[I])) {
9679 IsHexFloat = false;
9680 break;
9681 }
9682 }
9683 }
9684
9685 if (IsHexFloat)
9686 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9687 << LiteralName;
9688 else
9689 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9690 }
9691
Sean Hunta6c058d2010-01-13 09:01:02 +00009692 return false;
9693}
9694
Douglas Gregor074149e2009-01-05 19:45:36 +00009695/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9696/// linkage specification, including the language and (if present)
9697/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9698/// the location of the language string literal, which is provided
9699/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9700/// the '{' brace. Otherwise, this linkage specification does not
9701/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009702Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9703 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009704 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009705 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009706 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009707 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009708 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009709 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009710 Language = LinkageSpecDecl::lang_cxx;
9711 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009712 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009713 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009714 }
Mike Stump1eb44332009-09-09 15:08:12 +00009715
Chris Lattnercc98eac2008-12-17 07:13:27 +00009716 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009717
Douglas Gregor074149e2009-01-05 19:45:36 +00009718 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009719 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009720 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009721 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009722 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009723}
9724
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009725/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009726/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9727/// valid, it's the position of the closing '}' brace in a linkage
9728/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009729Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009730 Decl *LinkageSpec,
9731 SourceLocation RBraceLoc) {
9732 if (LinkageSpec) {
9733 if (RBraceLoc.isValid()) {
9734 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9735 LSDecl->setRBraceLoc(RBraceLoc);
9736 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009737 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009738 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009739 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009740}
9741
Douglas Gregord308e622009-05-18 20:51:54 +00009742/// \brief Perform semantic analysis for the variable declaration that
9743/// occurs within a C++ catch clause, returning the newly-created
9744/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009745VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009746 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009747 SourceLocation StartLoc,
9748 SourceLocation Loc,
9749 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009750 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009751 QualType ExDeclType = TInfo->getType();
9752
Sebastian Redl4b07b292008-12-22 19:15:10 +00009753 // Arrays and functions decay.
9754 if (ExDeclType->isArrayType())
9755 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9756 else if (ExDeclType->isFunctionType())
9757 ExDeclType = Context.getPointerType(ExDeclType);
9758
9759 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9760 // The exception-declaration shall not denote a pointer or reference to an
9761 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009762 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009763 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009764 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009765 Invalid = true;
9766 }
Douglas Gregord308e622009-05-18 20:51:54 +00009767
Sebastian Redl4b07b292008-12-22 19:15:10 +00009768 QualType BaseType = ExDeclType;
9769 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009770 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009771 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009772 BaseType = Ptr->getPointeeType();
9773 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009774 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009775 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009776 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009777 BaseType = Ref->getPointeeType();
9778 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009779 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009780 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009781 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009782 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009783 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009784
Mike Stump1eb44332009-09-09 15:08:12 +00009785 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009786 RequireNonAbstractType(Loc, ExDeclType,
9787 diag::err_abstract_type_in_decl,
9788 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009789 Invalid = true;
9790
John McCall5a180392010-07-24 00:37:23 +00009791 // Only the non-fragile NeXT runtime currently supports C++ catches
9792 // of ObjC types, and no runtime supports catching ObjC types by value.
9793 if (!Invalid && getLangOptions().ObjC1) {
9794 QualType T = ExDeclType;
9795 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9796 T = RT->getPointeeType();
9797
9798 if (T->isObjCObjectType()) {
9799 Diag(Loc, diag::err_objc_object_catch);
9800 Invalid = true;
9801 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009802 if (!getLangOptions().ObjCNonFragileABI)
9803 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009804 }
9805 }
9806
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009807 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9808 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009809 ExDecl->setExceptionVariable(true);
9810
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009811 // In ARC, infer 'retaining' for variables of retainable type.
9812 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9813 Invalid = true;
9814
Douglas Gregorc41b8782011-07-06 18:14:43 +00009815 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009816 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009817 // C++ [except.handle]p16:
9818 // The object declared in an exception-declaration or, if the
9819 // exception-declaration does not specify a name, a temporary (12.2) is
9820 // copy-initialized (8.5) from the exception object. [...]
9821 // The object is destroyed when the handler exits, after the destruction
9822 // of any automatic objects initialized within the handler.
9823 //
9824 // We just pretend to initialize the object with itself, then make sure
9825 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009826 QualType initType = ExDeclType;
9827
9828 InitializedEntity entity =
9829 InitializedEntity::InitializeVariable(ExDecl);
9830 InitializationKind initKind =
9831 InitializationKind::CreateCopy(Loc, SourceLocation());
9832
9833 Expr *opaqueValue =
9834 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9835 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9836 ExprResult result = sequence.Perform(*this, entity, initKind,
9837 MultiExprArg(&opaqueValue, 1));
9838 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009839 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009840 else {
9841 // If the constructor used was non-trivial, set this as the
9842 // "initializer".
9843 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9844 if (!construct->getConstructor()->isTrivial()) {
9845 Expr *init = MaybeCreateExprWithCleanups(construct);
9846 ExDecl->setInit(init);
9847 }
9848
9849 // And make sure it's destructable.
9850 FinalizeVarWithDestructor(ExDecl, recordType);
9851 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009852 }
9853 }
9854
Douglas Gregord308e622009-05-18 20:51:54 +00009855 if (Invalid)
9856 ExDecl->setInvalidDecl();
9857
9858 return ExDecl;
9859}
9860
9861/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9862/// handler.
John McCalld226f652010-08-21 09:40:31 +00009863Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009864 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009865 bool Invalid = D.isInvalidType();
9866
9867 // Check for unexpanded parameter packs.
9868 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9869 UPPC_ExceptionType)) {
9870 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9871 D.getIdentifierLoc());
9872 Invalid = true;
9873 }
9874
Sebastian Redl4b07b292008-12-22 19:15:10 +00009875 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009876 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009877 LookupOrdinaryName,
9878 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009879 // The scope should be freshly made just for us. There is just no way
9880 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009881 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009882 if (PrevDecl->isTemplateParameter()) {
9883 // Maybe we will complain about the shadowed template parameter.
9884 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009885 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009886 }
9887 }
9888
Chris Lattnereaaebc72009-04-25 08:06:05 +00009889 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009890 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9891 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009892 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009893 }
9894
Douglas Gregor83cb9422010-09-09 17:09:21 +00009895 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009896 D.getSourceRange().getBegin(),
9897 D.getIdentifierLoc(),
9898 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009899 if (Invalid)
9900 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009901
Sebastian Redl4b07b292008-12-22 19:15:10 +00009902 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009903 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009904 PushOnScopeChains(ExDecl, S);
9905 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009906 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009907
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009908 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009909 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009910}
Anders Carlssonfb311762009-03-14 00:25:26 +00009911
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009912Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009913 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009914 Expr *AssertMessageExpr_,
9915 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009916 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009917
Anders Carlssonc3082412009-03-14 00:33:21 +00009918 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009919 // In a static_assert-declaration, the constant-expression shall be a
9920 // constant expression that can be contextually converted to bool.
9921 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9922 if (Converted.isInvalid())
9923 return 0;
9924
Richard Smithdaaefc52011-12-14 23:32:26 +00009925 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009926 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9927 PDiag(diag::err_static_assert_expression_is_not_constant),
9928 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009929 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009930
Richard Smithdaaefc52011-12-14 23:32:26 +00009931 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009932 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009933 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009934 }
Mike Stump1eb44332009-09-09 15:08:12 +00009935
Douglas Gregor399ad972010-12-15 23:55:21 +00009936 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9937 return 0;
9938
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009939 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9940 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009941
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009942 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009943 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009944}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009945
Douglas Gregor1d869352010-04-07 16:53:43 +00009946/// \brief Perform semantic analysis of the given friend type declaration.
9947///
9948/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009949FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9950 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009951 TypeSourceInfo *TSInfo) {
9952 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9953
9954 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009955 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009956
Richard Smith6b130222011-10-18 21:39:00 +00009957 // C++03 [class.friend]p2:
9958 // An elaborated-type-specifier shall be used in a friend declaration
9959 // for a class.*
9960 //
9961 // * The class-key of the elaborated-type-specifier is required.
9962 if (!ActiveTemplateInstantiations.empty()) {
9963 // Do not complain about the form of friend template types during
9964 // template instantiation; we will already have complained when the
9965 // template was declared.
9966 } else if (!T->isElaboratedTypeSpecifier()) {
9967 // If we evaluated the type to a record type, suggest putting
9968 // a tag in front.
9969 if (const RecordType *RT = T->getAs<RecordType>()) {
9970 RecordDecl *RD = RT->getDecl();
9971
9972 std::string InsertionText = std::string(" ") + RD->getKindName();
9973
9974 Diag(TypeRange.getBegin(),
9975 getLangOptions().CPlusPlus0x ?
9976 diag::warn_cxx98_compat_unelaborated_friend_type :
9977 diag::ext_unelaborated_friend_type)
9978 << (unsigned) RD->getTagKind()
9979 << T
9980 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9981 InsertionText);
9982 } else {
9983 Diag(FriendLoc,
9984 getLangOptions().CPlusPlus0x ?
9985 diag::warn_cxx98_compat_nonclass_type_friend :
9986 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009987 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009988 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009989 }
Richard Smith6b130222011-10-18 21:39:00 +00009990 } else if (T->getAs<EnumType>()) {
9991 Diag(FriendLoc,
9992 getLangOptions().CPlusPlus0x ?
9993 diag::warn_cxx98_compat_enum_friend :
9994 diag::ext_enum_friend)
9995 << T
9996 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009997 }
9998
Douglas Gregor06245bf2010-04-07 17:57:12 +00009999 // C++0x [class.friend]p3:
10000 // If the type specifier in a friend declaration designates a (possibly
10001 // cv-qualified) class type, that class is declared as a friend; otherwise,
10002 // the friend declaration is ignored.
10003
10004 // FIXME: C++0x has some syntactic restrictions on friend type declarations
10005 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +000010006
Abramo Bagnara0216df82011-10-29 20:52:52 +000010007 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010008}
10009
John McCall9a34edb2010-10-19 01:40:49 +000010010/// Handle a friend tag declaration where the scope specifier was
10011/// templated.
10012Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10013 unsigned TagSpec, SourceLocation TagLoc,
10014 CXXScopeSpec &SS,
10015 IdentifierInfo *Name, SourceLocation NameLoc,
10016 AttributeList *Attr,
10017 MultiTemplateParamsArg TempParamLists) {
10018 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10019
10020 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010021 bool Invalid = false;
10022
10023 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010024 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +000010025 TempParamLists.get(),
10026 TempParamLists.size(),
10027 /*friend*/ true,
10028 isExplicitSpecialization,
10029 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010030 if (TemplateParams->size() > 0) {
10031 // This is a declaration of a class template.
10032 if (Invalid)
10033 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010034
Eric Christopher4110e132011-07-21 05:34:24 +000010035 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10036 SS, Name, NameLoc, Attr,
10037 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010038 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010039 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010040 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010041 } else {
10042 // The "template<>" header is extraneous.
10043 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10044 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10045 isExplicitSpecialization = true;
10046 }
10047 }
10048
10049 if (Invalid) return 0;
10050
John McCall9a34edb2010-10-19 01:40:49 +000010051 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010052 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +000010053 if (TempParamLists.get()[I]->size()) {
10054 isAllExplicitSpecializations = false;
10055 break;
10056 }
10057 }
10058
10059 // FIXME: don't ignore attributes.
10060
10061 // If it's explicit specializations all the way down, just forget
10062 // about the template header and build an appropriate non-templated
10063 // friend. TODO: for source fidelity, remember the headers.
10064 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010065 if (SS.isEmpty()) {
10066 bool Owned = false;
10067 bool IsDependent = false;
10068 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10069 Attr, AS_public,
10070 /*ModulePrivateLoc=*/SourceLocation(),
10071 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010072 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010073 /*ScopedEnumUsesClassTag=*/false,
10074 /*UnderlyingType=*/TypeResult());
10075 }
10076
Douglas Gregor2494dd02011-03-01 01:34:45 +000010077 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010078 ElaboratedTypeKeyword Keyword
10079 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010080 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010081 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010082 if (T.isNull())
10083 return 0;
10084
10085 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10086 if (isa<DependentNameType>(T)) {
10087 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10088 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010089 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010090 TL.setNameLoc(NameLoc);
10091 } else {
10092 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
10093 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010094 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010095 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10096 }
10097
10098 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10099 TSI, FriendLoc);
10100 Friend->setAccess(AS_public);
10101 CurContext->addDecl(Friend);
10102 return Friend;
10103 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010104
10105 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10106
10107
John McCall9a34edb2010-10-19 01:40:49 +000010108
10109 // Handle the case of a templated-scope friend class. e.g.
10110 // template <class T> class A<T>::B;
10111 // FIXME: we don't support these right now.
10112 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10113 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10114 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10115 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10116 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010117 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010118 TL.setNameLoc(NameLoc);
10119
10120 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10121 TSI, FriendLoc);
10122 Friend->setAccess(AS_public);
10123 Friend->setUnsupportedFriend(true);
10124 CurContext->addDecl(Friend);
10125 return Friend;
10126}
10127
10128
John McCalldd4a3b02009-09-16 22:47:08 +000010129/// Handle a friend type declaration. This works in tandem with
10130/// ActOnTag.
10131///
10132/// Notes on friend class templates:
10133///
10134/// We generally treat friend class declarations as if they were
10135/// declaring a class. So, for example, the elaborated type specifier
10136/// in a friend declaration is required to obey the restrictions of a
10137/// class-head (i.e. no typedefs in the scope chain), template
10138/// parameters are required to match up with simple template-ids, &c.
10139/// However, unlike when declaring a template specialization, it's
10140/// okay to refer to a template specialization without an empty
10141/// template parameter declaration, e.g.
10142/// friend class A<T>::B<unsigned>;
10143/// We permit this as a special case; if there are any template
10144/// parameters present at all, require proper matching, i.e.
10145/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010146Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010147 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +000010148 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +000010149
10150 assert(DS.isFriendSpecified());
10151 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10152
John McCalldd4a3b02009-09-16 22:47:08 +000010153 // Try to convert the decl specifier to a type. This works for
10154 // friend templates because ActOnTag never produces a ClassTemplateDecl
10155 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010156 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010157 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10158 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010159 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010160 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010161
Douglas Gregor6ccab972010-12-16 01:14:37 +000010162 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10163 return 0;
10164
John McCalldd4a3b02009-09-16 22:47:08 +000010165 // This is definitely an error in C++98. It's probably meant to
10166 // be forbidden in C++0x, too, but the specification is just
10167 // poorly written.
10168 //
10169 // The problem is with declarations like the following:
10170 // template <T> friend A<T>::foo;
10171 // where deciding whether a class C is a friend or not now hinges
10172 // on whether there exists an instantiation of A that causes
10173 // 'foo' to equal C. There are restrictions on class-heads
10174 // (which we declare (by fiat) elaborated friend declarations to
10175 // be) that makes this tractable.
10176 //
10177 // FIXME: handle "template <> friend class A<T>;", which
10178 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010179 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010180 Diag(Loc, diag::err_tagless_friend_type_template)
10181 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010182 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010183 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010184
John McCall02cace72009-08-28 07:59:38 +000010185 // C++98 [class.friend]p1: A friend of a class is a function
10186 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010187 // This is fixed in DR77, which just barely didn't make the C++03
10188 // deadline. It's also a very silly restriction that seriously
10189 // affects inner classes and which nobody else seems to implement;
10190 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010191 //
10192 // But note that we could warn about it: it's always useless to
10193 // friend one of your own members (it's not, however, worthless to
10194 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010195
John McCalldd4a3b02009-09-16 22:47:08 +000010196 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010197 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010198 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010199 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010200 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010201 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010202 DS.getFriendSpecLoc());
10203 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010204 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010205
10206 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010207 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010208
John McCalldd4a3b02009-09-16 22:47:08 +000010209 D->setAccess(AS_public);
10210 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010211
John McCalld226f652010-08-21 09:40:31 +000010212 return D;
John McCall02cace72009-08-28 07:59:38 +000010213}
10214
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010215Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010216 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010217 const DeclSpec &DS = D.getDeclSpec();
10218
10219 assert(DS.isFriendSpecified());
10220 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10221
10222 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010223 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010224
10225 // C++ [class.friend]p1
10226 // A friend of a class is a function or class....
10227 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010228 // It *doesn't* see through dependent types, which is correct
10229 // according to [temp.arg.type]p3:
10230 // If a declaration acquires a function type through a
10231 // type dependent on a template-parameter and this causes
10232 // a declaration that does not use the syntactic form of a
10233 // function declarator to have a function type, the program
10234 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010235 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010236 Diag(Loc, diag::err_unexpected_friend);
10237
10238 // It might be worthwhile to try to recover by creating an
10239 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010240 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010241 }
10242
10243 // C++ [namespace.memdef]p3
10244 // - If a friend declaration in a non-local class first declares a
10245 // class or function, the friend class or function is a member
10246 // of the innermost enclosing namespace.
10247 // - The name of the friend is not found by simple name lookup
10248 // until a matching declaration is provided in that namespace
10249 // scope (either before or after the class declaration granting
10250 // friendship).
10251 // - If a friend function is called, its name may be found by the
10252 // name lookup that considers functions from namespaces and
10253 // classes associated with the types of the function arguments.
10254 // - When looking for a prior declaration of a class or a function
10255 // declared as a friend, scopes outside the innermost enclosing
10256 // namespace scope are not considered.
10257
John McCall337ec3d2010-10-12 23:13:28 +000010258 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010259 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10260 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010261 assert(Name);
10262
Douglas Gregor6ccab972010-12-16 01:14:37 +000010263 // Check for unexpanded parameter packs.
10264 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10265 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10266 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10267 return 0;
10268
John McCall67d1a672009-08-06 02:15:43 +000010269 // The context we found the declaration in, or in which we should
10270 // create the declaration.
10271 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010272 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010273 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010274 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010275
John McCall337ec3d2010-10-12 23:13:28 +000010276 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010277
John McCall337ec3d2010-10-12 23:13:28 +000010278 // There are four cases here.
10279 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010280 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010281 // there as appropriate.
10282 // Recover from invalid scope qualifiers as if they just weren't there.
10283 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010284 // C++0x [namespace.memdef]p3:
10285 // If the name in a friend declaration is neither qualified nor
10286 // a template-id and the declaration is a function or an
10287 // elaborated-type-specifier, the lookup to determine whether
10288 // the entity has been previously declared shall not consider
10289 // any scopes outside the innermost enclosing namespace.
10290 // C++0x [class.friend]p11:
10291 // If a friend declaration appears in a local class and the name
10292 // specified is an unqualified name, a prior declaration is
10293 // looked up without considering scopes that are outside the
10294 // innermost enclosing non-class scope. For a friend function
10295 // declaration, if there is no prior declaration, the program is
10296 // ill-formed.
10297 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010298 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010299
John McCall29ae6e52010-10-13 05:45:15 +000010300 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010301 DC = CurContext;
10302 while (true) {
10303 // Skip class contexts. If someone can cite chapter and verse
10304 // for this behavior, that would be nice --- it's what GCC and
10305 // EDG do, and it seems like a reasonable intent, but the spec
10306 // really only says that checks for unqualified existing
10307 // declarations should stop at the nearest enclosing namespace,
10308 // not that they should only consider the nearest enclosing
10309 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010310 while (DC->isRecord())
10311 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010312
John McCall68263142009-11-18 22:49:29 +000010313 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010314
10315 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010316 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010317 break;
John McCall29ae6e52010-10-13 05:45:15 +000010318
John McCall8a407372010-10-14 22:22:28 +000010319 if (isTemplateId) {
10320 if (isa<TranslationUnitDecl>(DC)) break;
10321 } else {
10322 if (DC->isFileContext()) break;
10323 }
John McCall67d1a672009-08-06 02:15:43 +000010324 DC = DC->getParent();
10325 }
10326
10327 // C++ [class.friend]p1: A friend of a class is a function or
10328 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010329 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010330 // Most C++ 98 compilers do seem to give an error here, so
10331 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010332 if (!Previous.empty() && DC->Equals(CurContext))
10333 Diag(DS.getFriendSpecLoc(),
10334 getLangOptions().CPlusPlus0x ?
10335 diag::warn_cxx98_compat_friend_is_member :
10336 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010337
John McCall380aaa42010-10-13 06:22:15 +000010338 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010339
Douglas Gregor883af832011-10-10 01:11:59 +000010340 // C++ [class.friend]p6:
10341 // A function can be defined in a friend declaration of a class if and
10342 // only if the class is a non-local class (9.8), the function name is
10343 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010344 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010345 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10346 }
10347
John McCall337ec3d2010-10-12 23:13:28 +000010348 // - There's a non-dependent scope specifier, in which case we
10349 // compute it and do a previous lookup there for a function
10350 // or function template.
10351 } else if (!SS.getScopeRep()->isDependent()) {
10352 DC = computeDeclContext(SS);
10353 if (!DC) return 0;
10354
10355 if (RequireCompleteDeclContext(SS, DC)) return 0;
10356
10357 LookupQualifiedName(Previous, DC);
10358
10359 // Ignore things found implicitly in the wrong scope.
10360 // TODO: better diagnostics for this case. Suggesting the right
10361 // qualified scope would be nice...
10362 LookupResult::Filter F = Previous.makeFilter();
10363 while (F.hasNext()) {
10364 NamedDecl *D = F.next();
10365 if (!DC->InEnclosingNamespaceSetOf(
10366 D->getDeclContext()->getRedeclContext()))
10367 F.erase();
10368 }
10369 F.done();
10370
10371 if (Previous.empty()) {
10372 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010373 Diag(Loc, diag::err_qualified_friend_not_found)
10374 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010375 return 0;
10376 }
10377
10378 // C++ [class.friend]p1: A friend of a class is a function or
10379 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010380 if (DC->Equals(CurContext))
10381 Diag(DS.getFriendSpecLoc(),
10382 getLangOptions().CPlusPlus0x ?
10383 diag::warn_cxx98_compat_friend_is_member :
10384 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010385
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010386 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010387 // C++ [class.friend]p6:
10388 // A function can be defined in a friend declaration of a class if and
10389 // only if the class is a non-local class (9.8), the function name is
10390 // unqualified, and the function has namespace scope.
10391 SemaDiagnosticBuilder DB
10392 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10393
10394 DB << SS.getScopeRep();
10395 if (DC->isFileContext())
10396 DB << FixItHint::CreateRemoval(SS.getRange());
10397 SS.clear();
10398 }
John McCall337ec3d2010-10-12 23:13:28 +000010399
10400 // - There's a scope specifier that does not match any template
10401 // parameter lists, in which case we use some arbitrary context,
10402 // create a method or method template, and wait for instantiation.
10403 // - There's a scope specifier that does match some template
10404 // parameter lists, which we don't handle right now.
10405 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010406 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010407 // C++ [class.friend]p6:
10408 // A function can be defined in a friend declaration of a class if and
10409 // only if the class is a non-local class (9.8), the function name is
10410 // unqualified, and the function has namespace scope.
10411 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10412 << SS.getScopeRep();
10413 }
10414
John McCall337ec3d2010-10-12 23:13:28 +000010415 DC = CurContext;
10416 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010417 }
Douglas Gregor883af832011-10-10 01:11:59 +000010418
John McCall29ae6e52010-10-13 05:45:15 +000010419 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010420 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010421 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10422 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10423 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010424 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010425 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10426 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010427 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010428 }
John McCall67d1a672009-08-06 02:15:43 +000010429 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010430
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010431 // FIXME: This is an egregious hack to cope with cases where the scope stack
10432 // does not contain the declaration context, i.e., in an out-of-line
10433 // definition of a class.
10434 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10435 if (!DCScope) {
10436 FakeDCScope.setEntity(DC);
10437 DCScope = &FakeDCScope;
10438 }
10439
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010440 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010441 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10442 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010443 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010444
Douglas Gregor182ddf02009-09-28 00:08:27 +000010445 assert(ND->getDeclContext() == DC);
10446 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010447
John McCallab88d972009-08-31 22:39:49 +000010448 // Add the function declaration to the appropriate lookup tables,
10449 // adjusting the redeclarations list as necessary. We don't
10450 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010451 //
John McCallab88d972009-08-31 22:39:49 +000010452 // Also update the scope-based lookup if the target context's
10453 // lookup context is in lexical scope.
10454 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010455 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010456 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010457 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010458 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010459 }
John McCall02cace72009-08-28 07:59:38 +000010460
10461 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010462 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010463 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010464 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010465 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010466
John McCall337ec3d2010-10-12 23:13:28 +000010467 if (ND->isInvalidDecl())
10468 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010469 else {
10470 FunctionDecl *FD;
10471 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10472 FD = FTD->getTemplatedDecl();
10473 else
10474 FD = cast<FunctionDecl>(ND);
10475
10476 // Mark templated-scope function declarations as unsupported.
10477 if (FD->getNumTemplateParameterLists())
10478 FrD->setUnsupportedFriend(true);
10479 }
John McCall337ec3d2010-10-12 23:13:28 +000010480
John McCalld226f652010-08-21 09:40:31 +000010481 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010482}
10483
John McCalld226f652010-08-21 09:40:31 +000010484void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10485 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010486
Sebastian Redl50de12f2009-03-24 22:27:57 +000010487 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10488 if (!Fn) {
10489 Diag(DelLoc, diag::err_deleted_non_function);
10490 return;
10491 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010492 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010493 Diag(DelLoc, diag::err_deleted_decl_not_first);
10494 Diag(Prev->getLocation(), diag::note_previous_declaration);
10495 // If the declaration wasn't the first, we delete the function anyway for
10496 // recovery.
10497 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010498 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010499}
Sebastian Redl13e88542009-04-27 21:33:24 +000010500
Sean Hunte4246a62011-05-12 06:15:49 +000010501void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10502 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10503
10504 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010505 if (MD->getParent()->isDependentType()) {
10506 MD->setDefaulted();
10507 MD->setExplicitlyDefaulted();
10508 return;
10509 }
10510
Sean Hunte4246a62011-05-12 06:15:49 +000010511 CXXSpecialMember Member = getSpecialMember(MD);
10512 if (Member == CXXInvalid) {
10513 Diag(DefaultLoc, diag::err_default_special_members);
10514 return;
10515 }
10516
10517 MD->setDefaulted();
10518 MD->setExplicitlyDefaulted();
10519
Sean Huntcd10dec2011-05-23 23:14:04 +000010520 // If this definition appears within the record, do the checking when
10521 // the record is complete.
10522 const FunctionDecl *Primary = MD;
10523 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10524 // Find the uninstantiated declaration that actually had the '= default'
10525 // on it.
10526 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10527
10528 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010529 return;
10530
10531 switch (Member) {
10532 case CXXDefaultConstructor: {
10533 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10534 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010535 if (!CD->isInvalidDecl())
10536 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10537 break;
10538 }
10539
10540 case CXXCopyConstructor: {
10541 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10542 CheckExplicitlyDefaultedCopyConstructor(CD);
10543 if (!CD->isInvalidDecl())
10544 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010545 break;
10546 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010547
Sean Hunt2b188082011-05-14 05:23:28 +000010548 case CXXCopyAssignment: {
10549 CheckExplicitlyDefaultedCopyAssignment(MD);
10550 if (!MD->isInvalidDecl())
10551 DefineImplicitCopyAssignment(DefaultLoc, MD);
10552 break;
10553 }
10554
Sean Huntcb45a0f2011-05-12 22:46:25 +000010555 case CXXDestructor: {
10556 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10557 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010558 if (!DD->isInvalidDecl())
10559 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010560 break;
10561 }
10562
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010563 case CXXMoveConstructor: {
10564 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10565 CheckExplicitlyDefaultedMoveConstructor(CD);
10566 if (!CD->isInvalidDecl())
10567 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010568 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010569 }
Sean Hunt82713172011-05-25 23:16:36 +000010570
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010571 case CXXMoveAssignment: {
10572 CheckExplicitlyDefaultedMoveAssignment(MD);
10573 if (!MD->isInvalidDecl())
10574 DefineImplicitMoveAssignment(DefaultLoc, MD);
10575 break;
10576 }
10577
10578 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010579 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010580 }
10581 } else {
10582 Diag(DefaultLoc, diag::err_default_special_members);
10583 }
10584}
10585
Sebastian Redl13e88542009-04-27 21:33:24 +000010586static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010587 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010588 Stmt *SubStmt = *CI;
10589 if (!SubStmt)
10590 continue;
10591 if (isa<ReturnStmt>(SubStmt))
10592 Self.Diag(SubStmt->getSourceRange().getBegin(),
10593 diag::err_return_in_constructor_handler);
10594 if (!isa<Expr>(SubStmt))
10595 SearchForReturnInStmt(Self, SubStmt);
10596 }
10597}
10598
10599void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10600 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10601 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10602 SearchForReturnInStmt(*this, Handler);
10603 }
10604}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010605
Mike Stump1eb44332009-09-09 15:08:12 +000010606bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010607 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010608 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10609 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010610
Chandler Carruth73857792010-02-15 11:53:20 +000010611 if (Context.hasSameType(NewTy, OldTy) ||
10612 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010613 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010614
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010615 // Check if the return types are covariant
10616 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010617
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010618 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010619 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10620 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010621 NewClassTy = NewPT->getPointeeType();
10622 OldClassTy = OldPT->getPointeeType();
10623 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010624 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10625 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10626 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10627 NewClassTy = NewRT->getPointeeType();
10628 OldClassTy = OldRT->getPointeeType();
10629 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010630 }
10631 }
Mike Stump1eb44332009-09-09 15:08:12 +000010632
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010633 // The return types aren't either both pointers or references to a class type.
10634 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010635 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010636 diag::err_different_return_type_for_overriding_virtual_function)
10637 << New->getDeclName() << NewTy << OldTy;
10638 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010639
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010640 return true;
10641 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010642
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010643 // C++ [class.virtual]p6:
10644 // If the return type of D::f differs from the return type of B::f, the
10645 // class type in the return type of D::f shall be complete at the point of
10646 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010647 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10648 if (!RT->isBeingDefined() &&
10649 RequireCompleteType(New->getLocation(), NewClassTy,
10650 PDiag(diag::err_covariant_return_incomplete)
10651 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010652 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010653 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010654
Douglas Gregora4923eb2009-11-16 21:35:15 +000010655 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010656 // Check if the new class derives from the old class.
10657 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10658 Diag(New->getLocation(),
10659 diag::err_covariant_return_not_derived)
10660 << New->getDeclName() << NewTy << OldTy;
10661 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10662 return true;
10663 }
Mike Stump1eb44332009-09-09 15:08:12 +000010664
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010665 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010666 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010667 diag::err_covariant_return_inaccessible_base,
10668 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10669 // FIXME: Should this point to the return type?
10670 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010671 // FIXME: this note won't trigger for delayed access control
10672 // diagnostics, and it's impossible to get an undelayed error
10673 // here from access control during the original parse because
10674 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010675 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10676 return true;
10677 }
10678 }
Mike Stump1eb44332009-09-09 15:08:12 +000010679
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010680 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010681 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010682 Diag(New->getLocation(),
10683 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010684 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010685 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10686 return true;
10687 };
Mike Stump1eb44332009-09-09 15:08:12 +000010688
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010689
10690 // The new class type must have the same or less qualifiers as the old type.
10691 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10692 Diag(New->getLocation(),
10693 diag::err_covariant_return_type_class_type_more_qualified)
10694 << New->getDeclName() << NewTy << OldTy;
10695 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10696 return true;
10697 };
Mike Stump1eb44332009-09-09 15:08:12 +000010698
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010699 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010700}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010701
Douglas Gregor4ba31362009-12-01 17:24:26 +000010702/// \brief Mark the given method pure.
10703///
10704/// \param Method the method to be marked pure.
10705///
10706/// \param InitRange the source range that covers the "0" initializer.
10707bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010708 SourceLocation EndLoc = InitRange.getEnd();
10709 if (EndLoc.isValid())
10710 Method->setRangeEnd(EndLoc);
10711
Douglas Gregor4ba31362009-12-01 17:24:26 +000010712 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10713 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010714 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010715 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010716
10717 if (!Method->isInvalidDecl())
10718 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10719 << Method->getDeclName() << InitRange;
10720 return true;
10721}
10722
John McCall731ad842009-12-19 09:28:58 +000010723/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10724/// an initializer for the out-of-line declaration 'Dcl'. The scope
10725/// is a fresh scope pushed for just this purpose.
10726///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010727/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10728/// static data member of class X, names should be looked up in the scope of
10729/// class X.
John McCalld226f652010-08-21 09:40:31 +000010730void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010731 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010732 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010733
John McCall731ad842009-12-19 09:28:58 +000010734 // We should only get called for declarations with scope specifiers, like:
10735 // int foo::bar;
10736 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010737 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010738}
10739
10740/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010741/// initializer for the out-of-line declaration 'D'.
10742void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010743 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010744 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010745
John McCall731ad842009-12-19 09:28:58 +000010746 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010747 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010748}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010749
10750/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10751/// C++ if/switch/while/for statement.
10752/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010753DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010754 // C++ 6.4p2:
10755 // The declarator shall not specify a function or an array.
10756 // The type-specifier-seq shall not contain typedef and shall not declare a
10757 // new class or enumeration.
10758 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10759 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010760
10761 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010762 if (!Dcl)
10763 return true;
10764
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010765 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10766 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010767 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010768 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010769 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010770
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010771 return Dcl;
10772}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010773
Douglas Gregordfe65432011-07-28 19:11:31 +000010774void Sema::LoadExternalVTableUses() {
10775 if (!ExternalSource)
10776 return;
10777
10778 SmallVector<ExternalVTableUse, 4> VTables;
10779 ExternalSource->ReadUsedVTables(VTables);
10780 SmallVector<VTableUse, 4> NewUses;
10781 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10782 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10783 = VTablesUsed.find(VTables[I].Record);
10784 // Even if a definition wasn't required before, it may be required now.
10785 if (Pos != VTablesUsed.end()) {
10786 if (!Pos->second && VTables[I].DefinitionRequired)
10787 Pos->second = true;
10788 continue;
10789 }
10790
10791 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10792 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10793 }
10794
10795 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10796}
10797
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010798void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10799 bool DefinitionRequired) {
10800 // Ignore any vtable uses in unevaluated operands or for classes that do
10801 // not have a vtable.
10802 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10803 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010804 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010805 return;
10806
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010807 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010808 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010809 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10810 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10811 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10812 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010813 // If we already had an entry, check to see if we are promoting this vtable
10814 // to required a definition. If so, we need to reappend to the VTableUses
10815 // list, since we may have already processed the first entry.
10816 if (DefinitionRequired && !Pos.first->second) {
10817 Pos.first->second = true;
10818 } else {
10819 // Otherwise, we can early exit.
10820 return;
10821 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010822 }
10823
10824 // Local classes need to have their virtual members marked
10825 // immediately. For all other classes, we mark their virtual members
10826 // at the end of the translation unit.
10827 if (Class->isLocalClass())
10828 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010829 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010830 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010831}
10832
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010833bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010834 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010835 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010836 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010837
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010838 // Note: The VTableUses vector could grow as a result of marking
10839 // the members of a class as "used", so we check the size each
10840 // time through the loop and prefer indices (with are stable) to
10841 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010842 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010843 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010844 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010845 if (!Class)
10846 continue;
10847
10848 SourceLocation Loc = VTableUses[I].second;
10849
10850 // If this class has a key function, but that key function is
10851 // defined in another translation unit, we don't need to emit the
10852 // vtable even though we're using it.
10853 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010854 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010855 switch (KeyFunction->getTemplateSpecializationKind()) {
10856 case TSK_Undeclared:
10857 case TSK_ExplicitSpecialization:
10858 case TSK_ExplicitInstantiationDeclaration:
10859 // The key function is in another translation unit.
10860 continue;
10861
10862 case TSK_ExplicitInstantiationDefinition:
10863 case TSK_ImplicitInstantiation:
10864 // We will be instantiating the key function.
10865 break;
10866 }
10867 } else if (!KeyFunction) {
10868 // If we have a class with no key function that is the subject
10869 // of an explicit instantiation declaration, suppress the
10870 // vtable; it will live with the explicit instantiation
10871 // definition.
10872 bool IsExplicitInstantiationDeclaration
10873 = Class->getTemplateSpecializationKind()
10874 == TSK_ExplicitInstantiationDeclaration;
10875 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10876 REnd = Class->redecls_end();
10877 R != REnd; ++R) {
10878 TemplateSpecializationKind TSK
10879 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10880 if (TSK == TSK_ExplicitInstantiationDeclaration)
10881 IsExplicitInstantiationDeclaration = true;
10882 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10883 IsExplicitInstantiationDeclaration = false;
10884 break;
10885 }
10886 }
10887
10888 if (IsExplicitInstantiationDeclaration)
10889 continue;
10890 }
10891
10892 // Mark all of the virtual members of this class as referenced, so
10893 // that we can build a vtable. Then, tell the AST consumer that a
10894 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010895 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010896 MarkVirtualMembersReferenced(Loc, Class);
10897 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10898 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10899
10900 // Optionally warn if we're emitting a weak vtable.
10901 if (Class->getLinkage() == ExternalLinkage &&
10902 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010903 const FunctionDecl *KeyFunctionDef = 0;
10904 if (!KeyFunction ||
10905 (KeyFunction->hasBody(KeyFunctionDef) &&
10906 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010907 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10908 TSK_ExplicitInstantiationDefinition
10909 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10910 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010911 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010912 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010913 VTableUses.clear();
10914
Douglas Gregor78844032011-04-22 22:25:37 +000010915 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010916}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010917
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010918void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10919 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010920 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10921 e = RD->method_end(); i != e; ++i) {
10922 CXXMethodDecl *MD = *i;
10923
10924 // C++ [basic.def.odr]p2:
10925 // [...] A virtual member function is used if it is not pure. [...]
10926 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010927 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010928 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010929
10930 // Only classes that have virtual bases need a VTT.
10931 if (RD->getNumVBases() == 0)
10932 return;
10933
10934 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10935 e = RD->bases_end(); i != e; ++i) {
10936 const CXXRecordDecl *Base =
10937 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010938 if (Base->getNumVBases() == 0)
10939 continue;
10940 MarkVirtualMembersReferenced(Loc, Base);
10941 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010942}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010943
10944/// SetIvarInitializers - This routine builds initialization ASTs for the
10945/// Objective-C implementation whose ivars need be initialized.
10946void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10947 if (!getLangOptions().CPlusPlus)
10948 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010949 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010950 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010951 CollectIvarsToConstructOrDestruct(OID, ivars);
10952 if (ivars.empty())
10953 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010954 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010955 for (unsigned i = 0; i < ivars.size(); i++) {
10956 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010957 if (Field->isInvalidDecl())
10958 continue;
10959
Sean Huntcbb67482011-01-08 20:30:50 +000010960 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010961 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10962 InitializationKind InitKind =
10963 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10964
10965 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010966 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010967 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010968 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010969 // Note, MemberInit could actually come back empty if no initialization
10970 // is required (e.g., because it would call a trivial default constructor)
10971 if (!MemberInit.get() || MemberInit.isInvalid())
10972 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010973
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010974 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010975 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10976 SourceLocation(),
10977 MemberInit.takeAs<Expr>(),
10978 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010979 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010980
10981 // Be sure that the destructor is accessible and is marked as referenced.
10982 if (const RecordType *RecordTy
10983 = Context.getBaseElementType(Field->getType())
10984 ->getAs<RecordType>()) {
10985 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010986 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010987 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010988 CheckDestructorAccess(Field->getLocation(), Destructor,
10989 PDiag(diag::err_access_dtor_ivar)
10990 << Context.getBaseElementType(Field->getType()));
10991 }
10992 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010993 }
10994 ObjCImplementation->setIvarInitializers(Context,
10995 AllToInit.data(), AllToInit.size());
10996 }
10997}
Sean Huntfe57eef2011-05-04 05:57:24 +000010998
Sean Huntebcbe1d2011-05-04 23:29:54 +000010999static
11000void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11001 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11002 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11003 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11004 Sema &S) {
11005 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11006 CE = Current.end();
11007 if (Ctor->isInvalidDecl())
11008 return;
11009
11010 const FunctionDecl *FNTarget = 0;
11011 CXXConstructorDecl *Target;
11012
11013 // We ignore the result here since if we don't have a body, Target will be
11014 // null below.
11015 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
11016 Target
11017= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
11018
11019 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11020 // Avoid dereferencing a null pointer here.
11021 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11022
11023 if (!Current.insert(Canonical))
11024 return;
11025
11026 // We know that beyond here, we aren't chaining into a cycle.
11027 if (!Target || !Target->isDelegatingConstructor() ||
11028 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11029 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11030 Valid.insert(*CI);
11031 Current.clear();
11032 // We've hit a cycle.
11033 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11034 Current.count(TCanonical)) {
11035 // If we haven't diagnosed this cycle yet, do so now.
11036 if (!Invalid.count(TCanonical)) {
11037 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011038 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011039 << Ctor;
11040
11041 // Don't add a note for a function delegating directo to itself.
11042 if (TCanonical != Canonical)
11043 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11044
11045 CXXConstructorDecl *C = Target;
11046 while (C->getCanonicalDecl() != Canonical) {
11047 (void)C->getTargetConstructor()->hasBody(FNTarget);
11048 assert(FNTarget && "Ctor cycle through bodiless function");
11049
11050 C
11051 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11052 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11053 }
11054 }
11055
11056 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11057 Invalid.insert(*CI);
11058 Current.clear();
11059 } else {
11060 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11061 }
11062}
11063
11064
Sean Huntfe57eef2011-05-04 05:57:24 +000011065void Sema::CheckDelegatingCtorCycles() {
11066 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11067
Sean Huntebcbe1d2011-05-04 23:29:54 +000011068 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11069 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011070
Douglas Gregor0129b562011-07-27 21:57:17 +000011071 for (DelegatingCtorDeclsType::iterator
11072 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011073 E = DelegatingCtorDecls.end();
11074 I != E; ++I) {
11075 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000011076 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011077
11078 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11079 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011080}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011081
11082/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11083Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11084 // Implicitly declared functions (e.g. copy constructors) are
11085 // __host__ __device__
11086 if (D->isImplicit())
11087 return CFT_HostDevice;
11088
11089 if (D->hasAttr<CUDAGlobalAttr>())
11090 return CFT_Global;
11091
11092 if (D->hasAttr<CUDADeviceAttr>()) {
11093 if (D->hasAttr<CUDAHostAttr>())
11094 return CFT_HostDevice;
11095 else
11096 return CFT_Device;
11097 }
11098
11099 return CFT_Host;
11100}
11101
11102bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11103 CUDAFunctionTarget CalleeTarget) {
11104 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11105 // Callable from the device only."
11106 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11107 return true;
11108
11109 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11110 // Callable from the host only."
11111 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11112 // Callable from the host only."
11113 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11114 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11115 return true;
11116
11117 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11118 return true;
11119
11120 return false;
11121}