blob: 10883af4b4111266dc76e37a1a0a90e0727c6070 [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.
Richard Smithd79093a2012-02-05 02:30:54 +0000840bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body,
841 bool IsInstantiation) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000842 if (isa<CXXTryStmt>(Body)) {
Richard Smith5ba73e12012-02-04 00:33:54 +0000843 // C++11 [dcl.constexpr]p3:
Richard Smith9f569cc2011-10-01 02:31:28 +0000844 // The definition of a constexpr function shall satisfy the following
845 // constraints: [...]
846 // - its function-body shall be = delete, = default, or a
847 // compound-statement
848 //
Richard Smith5ba73e12012-02-04 00:33:54 +0000849 // C++11 [dcl.constexpr]p4:
Richard Smith9f569cc2011-10-01 02:31:28 +0000850 // In the definition of a constexpr constructor, [...]
851 // - its function-body shall not be a function-try-block;
852 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
853 << isa<CXXConstructorDecl>(Dcl);
854 return false;
855 }
856
857 // - its function-body shall be [...] a compound-statement that contains only
858 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
859
860 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
861 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
862 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
863 switch ((*BodyIt)->getStmtClass()) {
864 case Stmt::NullStmtClass:
865 // - null statements,
866 continue;
867
868 case Stmt::DeclStmtClass:
869 // - static_assert-declarations
870 // - using-declarations,
871 // - using-directives,
872 // - typedef declarations and alias-declarations that do not define
873 // classes or enumerations,
874 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
875 return false;
876 continue;
877
878 case Stmt::ReturnStmtClass:
879 // - and exactly one return statement;
880 if (isa<CXXConstructorDecl>(Dcl))
881 break;
882
883 ReturnStmts.push_back((*BodyIt)->getLocStart());
884 // FIXME
885 // - every constructor call and implicit conversion used in initializing
886 // the return value shall be one of those allowed in a constant
887 // expression.
888 // Deal with this as part of a general check that the function can produce
889 // a constant expression (for [dcl.constexpr]p5).
890 continue;
891
892 default:
893 break;
894 }
895
896 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
897 << isa<CXXConstructorDecl>(Dcl);
898 return false;
899 }
900
901 if (const CXXConstructorDecl *Constructor
902 = dyn_cast<CXXConstructorDecl>(Dcl)) {
903 const CXXRecordDecl *RD = Constructor->getParent();
904 // - every non-static data member and base class sub-object shall be
905 // initialized;
906 if (RD->isUnion()) {
907 // DR1359: Exactly one member of a union shall be initialized.
908 if (Constructor->getNumCtorInitializers() == 0) {
909 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
910 return false;
911 }
Richard Smith6e433752011-10-10 16:38:04 +0000912 } else if (!Constructor->isDependentContext() &&
913 !Constructor->isDelegatingConstructor()) {
Richard Smith9f569cc2011-10-01 02:31:28 +0000914 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
915
916 // Skip detailed checking if we have enough initializers, and we would
917 // allow at most one initializer per member.
918 bool AnyAnonStructUnionMembers = false;
919 unsigned Fields = 0;
920 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
921 E = RD->field_end(); I != E; ++I, ++Fields) {
922 if ((*I)->isAnonymousStructOrUnion()) {
923 AnyAnonStructUnionMembers = true;
924 break;
925 }
926 }
927 if (AnyAnonStructUnionMembers ||
928 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
929 // Check initialization of non-static data members. Base classes are
930 // always initialized so do not need to be checked. Dependent bases
931 // might not have initializers in the member initializer list.
932 llvm::SmallSet<Decl*, 16> Inits;
933 for (CXXConstructorDecl::init_const_iterator
934 I = Constructor->init_begin(), E = Constructor->init_end();
935 I != E; ++I) {
936 if (FieldDecl *FD = (*I)->getMember())
937 Inits.insert(FD);
938 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
939 Inits.insert(ID->chain_begin(), ID->chain_end());
940 }
941
942 bool Diagnosed = false;
943 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
944 E = RD->field_end(); I != E; ++I)
945 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
946 if (Diagnosed)
947 return false;
948 }
949 }
950
951 // FIXME
952 // - every constructor involved in initializing non-static data members
953 // and base class sub-objects shall be a constexpr constructor;
954 // - every assignment-expression that is an initializer-clause appearing
955 // directly or indirectly within a brace-or-equal-initializer for
956 // a non-static data member that is not named by a mem-initializer-id
957 // shall be a constant expression; and
958 // - every implicit conversion used in converting a constructor argument
959 // to the corresponding parameter type and converting
960 // a full-expression to the corresponding member type shall be one of
961 // those allowed in a constant expression.
962 // Deal with these as part of a general check that the function can produce
963 // a constant expression (for [dcl.constexpr]p5).
964 } else {
965 if (ReturnStmts.empty()) {
966 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
967 return false;
968 }
969 if (ReturnStmts.size() > 1) {
970 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
971 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
972 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
973 return false;
974 }
975 }
976
Richard Smith5ba73e12012-02-04 00:33:54 +0000977 // C++11 [dcl.constexpr]p5:
978 // if no function argument values exist such that the function invocation
979 // substitution would produce a constant expression, the program is
980 // ill-formed; no diagnostic required.
981 // C++11 [dcl.constexpr]p3:
982 // - every constructor call and implicit conversion used in initializing the
983 // return value shall be one of those allowed in a constant expression.
984 // C++11 [dcl.constexpr]p4:
985 // - every constructor involved in initializing non-static data members and
986 // base class sub-objects shall be a constexpr constructor.
987 //
988 // FIXME: We currently disable this check inside system headers, to work
989 // around early STL implementations which contain constexpr functions which
990 // can't produce constant expressions.
Richard Smith745f5142012-01-27 01:14:48 +0000991 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith5ba73e12012-02-04 00:33:54 +0000992 if (!Context.getSourceManager().isInSystemHeader(Dcl->getLocation()) &&
Richard Smithd79093a2012-02-05 02:30:54 +0000993 !IsInstantiation && !Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000994 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
995 << isa<CXXConstructorDecl>(Dcl);
996 for (size_t I = 0, N = Diags.size(); I != N; ++I)
997 Diag(Diags[I].first, Diags[I].second);
998 return false;
999 }
1000
Richard Smith9f569cc2011-10-01 02:31:28 +00001001 return true;
1002}
1003
Douglas Gregorb48fe382008-10-31 09:07:45 +00001004/// isCurrentClassName - Determine whether the identifier II is the
1005/// name of the class type currently being defined. In the case of
1006/// nested classes, this will only return true if II is the name of
1007/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001008bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1009 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001010 assert(getLangOptions().CPlusPlus && "No class names in C!");
1011
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001012 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001013 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001014 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001015 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1016 } else
1017 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1018
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001019 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001020 return &II == CurDecl->getIdentifier();
1021 else
1022 return false;
1023}
1024
Mike Stump1eb44332009-09-09 15:08:12 +00001025/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001026///
1027/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1028/// and returns NULL otherwise.
1029CXXBaseSpecifier *
1030Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1031 SourceRange SpecifierRange,
1032 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001033 TypeSourceInfo *TInfo,
1034 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001035 QualType BaseType = TInfo->getType();
1036
Douglas Gregor2943aed2009-03-03 04:44:36 +00001037 // C++ [class.union]p1:
1038 // A union shall not have base classes.
1039 if (Class->isUnion()) {
1040 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1041 << SpecifierRange;
1042 return 0;
1043 }
1044
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001045 if (EllipsisLoc.isValid() &&
1046 !TInfo->getType()->containsUnexpandedParameterPack()) {
1047 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1048 << TInfo->getTypeLoc().getSourceRange();
1049 EllipsisLoc = SourceLocation();
1050 }
1051
Douglas Gregor2943aed2009-03-03 04:44:36 +00001052 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001053 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001054 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001055 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001056
1057 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001058
1059 // Base specifiers must be record types.
1060 if (!BaseType->isRecordType()) {
1061 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1062 return 0;
1063 }
1064
1065 // C++ [class.union]p1:
1066 // A union shall not be used as a base class.
1067 if (BaseType->isUnionType()) {
1068 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1069 return 0;
1070 }
1071
1072 // C++ [class.derived]p2:
1073 // The class-name in a base-specifier shall not be an incompletely
1074 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001075 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001076 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001077 << SpecifierRange)) {
1078 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001079 return 0;
John McCall572fc622010-08-17 07:23:57 +00001080 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001081
Eli Friedman1d954f62009-08-15 21:55:26 +00001082 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001083 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001084 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001085 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001086 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001087 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1088 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001089
Anders Carlsson1d209272011-03-25 14:55:14 +00001090 // C++ [class]p3:
1091 // If a class is marked final and it appears as a base-type-specifier in
1092 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001093 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001094 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1095 << CXXBaseDecl->getDeclName();
1096 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1097 << CXXBaseDecl->getDeclName();
1098 return 0;
1099 }
1100
John McCall572fc622010-08-17 07:23:57 +00001101 if (BaseDecl->isInvalidDecl())
1102 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001103
1104 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001105 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001106 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001107 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001108}
1109
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001110/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1111/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001112/// example:
1113/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001114/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001115BaseResult
John McCalld226f652010-08-21 09:40:31 +00001116Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001117 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001118 ParsedType basetype, SourceLocation BaseLoc,
1119 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001120 if (!classdecl)
1121 return true;
1122
Douglas Gregor40808ce2009-03-09 23:48:35 +00001123 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001124 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001125 if (!Class)
1126 return true;
1127
Nick Lewycky56062202010-07-26 16:56:01 +00001128 TypeSourceInfo *TInfo = 0;
1129 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001130
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001131 if (EllipsisLoc.isInvalid() &&
1132 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001133 UPPC_BaseType))
1134 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001135
Douglas Gregor2943aed2009-03-03 04:44:36 +00001136 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001137 Virtual, Access, TInfo,
1138 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001139 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Douglas Gregor2943aed2009-03-03 04:44:36 +00001141 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001142}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001143
Douglas Gregor2943aed2009-03-03 04:44:36 +00001144/// \brief Performs the actual work of attaching the given base class
1145/// specifiers to a C++ class.
1146bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1147 unsigned NumBases) {
1148 if (NumBases == 0)
1149 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001150
1151 // Used to keep track of which base types we have already seen, so
1152 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001153 // that the key is always the unqualified canonical type of the base
1154 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001155 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1156
1157 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001158 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001159 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001160 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001161 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001162 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001163 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001164 if (KnownBaseTypes[NewBaseType]) {
1165 // C++ [class.mi]p3:
1166 // A class shall not be specified as a direct base class of a
1167 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001168 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001169 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +00001170 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001171 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001172
1173 // Delete the duplicate base class specifier; we're going to
1174 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001175 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001176
1177 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001178 } else {
1179 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001180 KnownBaseTypes[NewBaseType] = Bases[idx];
1181 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001182 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001183 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1184 if (RD->hasAttr<WeakAttr>())
1185 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001186 }
1187 }
1188
1189 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001190 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001191
1192 // Delete the remaining (good) base class specifiers, since their
1193 // data has been copied into the CXXRecordDecl.
1194 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001195 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001196
1197 return Invalid;
1198}
1199
1200/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1201/// class, after checking whether there are any duplicate base
1202/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001203void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001204 unsigned NumBases) {
1205 if (!ClassDecl || !Bases || !NumBases)
1206 return;
1207
1208 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001209 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001210 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001211}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001212
John McCall3cb0ebd2010-03-10 03:28:59 +00001213static CXXRecordDecl *GetClassForType(QualType T) {
1214 if (const RecordType *RT = T->getAs<RecordType>())
1215 return cast<CXXRecordDecl>(RT->getDecl());
1216 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1217 return ICT->getDecl();
1218 else
1219 return 0;
1220}
1221
Douglas Gregora8f32e02009-10-06 17:59:45 +00001222/// \brief Determine whether the type \p Derived is a C++ class that is
1223/// derived from the type \p Base.
1224bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1225 if (!getLangOptions().CPlusPlus)
1226 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001227
1228 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1229 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001230 return false;
1231
John McCall3cb0ebd2010-03-10 03:28:59 +00001232 CXXRecordDecl *BaseRD = GetClassForType(Base);
1233 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001234 return false;
1235
John McCall86ff3082010-02-04 22:26:26 +00001236 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1237 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001238}
1239
1240/// \brief Determine whether the type \p Derived is a C++ class that is
1241/// derived from the type \p Base.
1242bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1243 if (!getLangOptions().CPlusPlus)
1244 return false;
1245
John McCall3cb0ebd2010-03-10 03:28:59 +00001246 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1247 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001248 return false;
1249
John McCall3cb0ebd2010-03-10 03:28:59 +00001250 CXXRecordDecl *BaseRD = GetClassForType(Base);
1251 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001252 return false;
1253
Douglas Gregora8f32e02009-10-06 17:59:45 +00001254 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1255}
1256
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001257void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001258 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001259 assert(BasePathArray.empty() && "Base path array must be empty!");
1260 assert(Paths.isRecordingPaths() && "Must record paths!");
1261
1262 const CXXBasePath &Path = Paths.front();
1263
1264 // We first go backward and check if we have a virtual base.
1265 // FIXME: It would be better if CXXBasePath had the base specifier for
1266 // the nearest virtual base.
1267 unsigned Start = 0;
1268 for (unsigned I = Path.size(); I != 0; --I) {
1269 if (Path[I - 1].Base->isVirtual()) {
1270 Start = I - 1;
1271 break;
1272 }
1273 }
1274
1275 // Now add all bases.
1276 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001277 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001278}
1279
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001280/// \brief Determine whether the given base path includes a virtual
1281/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001282bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1283 for (CXXCastPath::const_iterator B = BasePath.begin(),
1284 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001285 B != BEnd; ++B)
1286 if ((*B)->isVirtual())
1287 return true;
1288
1289 return false;
1290}
1291
Douglas Gregora8f32e02009-10-06 17:59:45 +00001292/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1293/// conversion (where Derived and Base are class types) is
1294/// well-formed, meaning that the conversion is unambiguous (and
1295/// that all of the base classes are accessible). Returns true
1296/// and emits a diagnostic if the code is ill-formed, returns false
1297/// otherwise. Loc is the location where this routine should point to
1298/// if there is an error, and Range is the source range to highlight
1299/// if there is an error.
1300bool
1301Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001302 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001303 unsigned AmbigiousBaseConvID,
1304 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001305 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001306 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001307 // First, determine whether the path from Derived to Base is
1308 // ambiguous. This is slightly more expensive than checking whether
1309 // the Derived to Base conversion exists, because here we need to
1310 // explore multiple paths to determine if there is an ambiguity.
1311 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1312 /*DetectVirtual=*/false);
1313 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1314 assert(DerivationOkay &&
1315 "Can only be used with a derived-to-base conversion");
1316 (void)DerivationOkay;
1317
1318 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001319 if (InaccessibleBaseID) {
1320 // Check that the base class can be accessed.
1321 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1322 InaccessibleBaseID)) {
1323 case AR_inaccessible:
1324 return true;
1325 case AR_accessible:
1326 case AR_dependent:
1327 case AR_delayed:
1328 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001329 }
John McCall6b2accb2010-02-10 09:31:12 +00001330 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001331
1332 // Build a base path if necessary.
1333 if (BasePath)
1334 BuildBasePathArray(Paths, *BasePath);
1335 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001336 }
1337
1338 // We know that the derived-to-base conversion is ambiguous, and
1339 // we're going to produce a diagnostic. Perform the derived-to-base
1340 // search just one more time to compute all of the possible paths so
1341 // that we can print them out. This is more expensive than any of
1342 // the previous derived-to-base checks we've done, but at this point
1343 // performance isn't as much of an issue.
1344 Paths.clear();
1345 Paths.setRecordingPaths(true);
1346 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1347 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1348 (void)StillOkay;
1349
1350 // Build up a textual representation of the ambiguous paths, e.g.,
1351 // D -> B -> A, that will be used to illustrate the ambiguous
1352 // conversions in the diagnostic. We only print one of the paths
1353 // to each base class subobject.
1354 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1355
1356 Diag(Loc, AmbigiousBaseConvID)
1357 << Derived << Base << PathDisplayStr << Range << Name;
1358 return true;
1359}
1360
1361bool
1362Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001363 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001364 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001365 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001366 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001367 IgnoreAccess ? 0
1368 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001369 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001370 Loc, Range, DeclarationName(),
1371 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001372}
1373
1374
1375/// @brief Builds a string representing ambiguous paths from a
1376/// specific derived class to different subobjects of the same base
1377/// class.
1378///
1379/// This function builds a string that can be used in error messages
1380/// to show the different paths that one can take through the
1381/// inheritance hierarchy to go from the derived class to different
1382/// subobjects of a base class. The result looks something like this:
1383/// @code
1384/// struct D -> struct B -> struct A
1385/// struct D -> struct C -> struct A
1386/// @endcode
1387std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1388 std::string PathDisplayStr;
1389 std::set<unsigned> DisplayedPaths;
1390 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1391 Path != Paths.end(); ++Path) {
1392 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1393 // We haven't displayed a path to this particular base
1394 // class subobject yet.
1395 PathDisplayStr += "\n ";
1396 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1397 for (CXXBasePath::const_iterator Element = Path->begin();
1398 Element != Path->end(); ++Element)
1399 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1400 }
1401 }
1402
1403 return PathDisplayStr;
1404}
1405
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001406//===----------------------------------------------------------------------===//
1407// C++ class member Handling
1408//===----------------------------------------------------------------------===//
1409
Abramo Bagnara6206d532010-06-05 05:09:32 +00001410/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001411bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1412 SourceLocation ASLoc,
1413 SourceLocation ColonLoc,
1414 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001415 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001416 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001417 ASLoc, ColonLoc);
1418 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001419 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001420}
1421
Anders Carlsson9e682d92011-01-20 05:57:14 +00001422/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001423void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001424 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001425 if (!MD || !MD->isVirtual())
1426 return;
1427
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001428 if (MD->isDependentContext())
1429 return;
1430
Anders Carlsson9e682d92011-01-20 05:57:14 +00001431 // C++0x [class.virtual]p3:
1432 // If a virtual function is marked with the virt-specifier override and does
1433 // not override a member function of a base class,
1434 // the program is ill-formed.
1435 bool HasOverriddenMethods =
1436 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001437 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001438 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001439 diag::err_function_marked_override_not_overriding)
1440 << MD->getDeclName();
1441 return;
1442 }
1443}
1444
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001445/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1446/// function overrides a virtual member function marked 'final', according to
1447/// C++0x [class.virtual]p3.
1448bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1449 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001450 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001451 return false;
1452
1453 Diag(New->getLocation(), diag::err_final_function_overridden)
1454 << New->getDeclName();
1455 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1456 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001457}
1458
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001459/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1460/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001461/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1462/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1463/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001464Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001465Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001466 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001467 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001468 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001469 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001470 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1471 DeclarationName Name = NameInfo.getName();
1472 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001473
1474 // For anonymous bitfields, the location should point to the type.
1475 if (Loc.isInvalid())
1476 Loc = D.getSourceRange().getBegin();
1477
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001478 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001479
John McCall4bde1e12010-06-04 08:34:12 +00001480 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001481 assert(!DS.isFriendSpecified());
1482
Richard Smith1ab0d902011-06-25 02:28:38 +00001483 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001484
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001485 // C++ 9.2p6: A member shall not be declared to have automatic storage
1486 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001487 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1488 // data members and cannot be applied to names declared const or static,
1489 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001490 switch (DS.getStorageClassSpec()) {
1491 case DeclSpec::SCS_unspecified:
1492 case DeclSpec::SCS_typedef:
1493 case DeclSpec::SCS_static:
1494 // FALL THROUGH.
1495 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001496 case DeclSpec::SCS_mutable:
1497 if (isFunc) {
1498 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001499 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001500 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001501 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Sebastian Redla11f42f2008-11-17 23:24:37 +00001503 // FIXME: It would be nicer if the keyword was ignored only for this
1504 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001505 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001506 }
1507 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001508 default:
1509 if (DS.getStorageClassSpecLoc().isValid())
1510 Diag(DS.getStorageClassSpecLoc(),
1511 diag::err_storageclass_invalid_for_member);
1512 else
1513 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1514 D.getMutableDeclSpec().ClearStorageClassSpecs();
1515 }
1516
Sebastian Redl669d5d72008-11-14 23:42:31 +00001517 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1518 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001519 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001520
1521 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001522 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001523 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001524
1525 // Data members must have identifiers for names.
1526 if (Name.getNameKind() != DeclarationName::Identifier) {
1527 Diag(Loc, diag::err_bad_variable_name)
1528 << Name;
1529 return 0;
1530 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001531
Douglas Gregorf2503652011-09-21 14:40:46 +00001532 IdentifierInfo *II = Name.getAsIdentifierInfo();
1533
1534 // Member field could not be with "template" keyword.
1535 // So TemplateParameterLists should be empty in this case.
1536 if (TemplateParameterLists.size()) {
1537 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1538 if (TemplateParams->size()) {
1539 // There is no such thing as a member field template.
1540 Diag(D.getIdentifierLoc(), diag::err_template_member)
1541 << II
1542 << SourceRange(TemplateParams->getTemplateLoc(),
1543 TemplateParams->getRAngleLoc());
1544 } else {
1545 // There is an extraneous 'template<>' for this member.
1546 Diag(TemplateParams->getTemplateLoc(),
1547 diag::err_template_member_noparams)
1548 << II
1549 << SourceRange(TemplateParams->getTemplateLoc(),
1550 TemplateParams->getRAngleLoc());
1551 }
1552 return 0;
1553 }
1554
Douglas Gregor922fff22010-10-13 22:19:53 +00001555 if (SS.isSet() && !SS.isInvalid()) {
1556 // The user provided a superfluous scope specifier inside a class
1557 // definition:
1558 //
1559 // class X {
1560 // int X::member;
1561 // };
1562 DeclContext *DC = 0;
1563 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1564 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001565 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001566 else
1567 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1568 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001569
Douglas Gregor922fff22010-10-13 22:19:53 +00001570 SS.clear();
1571 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001572
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001573 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001574 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001575 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001576 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001577 assert(!HasDeferredInit);
1578
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001579 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001580 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001581 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001582 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001583
1584 // Non-instance-fields can't have a bitfield.
1585 if (BitWidth) {
1586 if (Member->isInvalidDecl()) {
1587 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001588 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001589 // C++ 9.6p3: A bit-field shall not be a static member.
1590 // "static member 'A' cannot be a bit-field"
1591 Diag(Loc, diag::err_static_not_bitfield)
1592 << Name << BitWidth->getSourceRange();
1593 } else if (isa<TypedefDecl>(Member)) {
1594 // "typedef member 'x' cannot be a bit-field"
1595 Diag(Loc, diag::err_typedef_not_bitfield)
1596 << Name << BitWidth->getSourceRange();
1597 } else {
1598 // A function typedef ("typedef int f(); f a;").
1599 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1600 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001601 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001602 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001603 }
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Chris Lattner8b963ef2009-03-05 23:01:03 +00001605 BitWidth = 0;
1606 Member->setInvalidDecl();
1607 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001608
1609 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Douglas Gregor37b372b2009-08-20 22:52:58 +00001611 // If we have declared a member function template, set the access of the
1612 // templated declaration as well.
1613 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1614 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001615 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001616
Anders Carlssonaae5af22011-01-20 04:34:22 +00001617 if (VS.isOverrideSpecified()) {
1618 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1619 if (!MD || !MD->isVirtual()) {
1620 Diag(Member->getLocStart(),
1621 diag::override_keyword_only_allowed_on_virtual_member_functions)
1622 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001623 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001624 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001625 }
1626 if (VS.isFinalSpecified()) {
1627 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1628 if (!MD || !MD->isVirtual()) {
1629 Diag(Member->getLocStart(),
1630 diag::override_keyword_only_allowed_on_virtual_member_functions)
1631 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001632 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001633 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001634 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001635
Douglas Gregorf5251602011-03-08 17:10:18 +00001636 if (VS.getLastLocation().isValid()) {
1637 // Update the end location of a method that has a virt-specifiers.
1638 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1639 MD->setRangeEnd(VS.getLastLocation());
1640 }
1641
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001642 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001643
Douglas Gregor10bd3682008-11-17 22:58:34 +00001644 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001645
John McCallb25b2952011-02-15 07:12:36 +00001646 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001647 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001648 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001649}
1650
Richard Smith7a614d82011-06-11 17:19:42 +00001651/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001652/// in-class initializer for a non-static C++ class member, and after
1653/// instantiating an in-class initializer in a class template. Such actions
1654/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001655void
1656Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1657 Expr *InitExpr) {
1658 FieldDecl *FD = cast<FieldDecl>(D);
1659
1660 if (!InitExpr) {
1661 FD->setInvalidDecl();
1662 FD->removeInClassInitializer();
1663 return;
1664 }
1665
Peter Collingbournefef21892011-10-23 18:59:44 +00001666 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1667 FD->setInvalidDecl();
1668 FD->removeInClassInitializer();
1669 return;
1670 }
1671
Richard Smith7a614d82011-06-11 17:19:42 +00001672 ExprResult Init = InitExpr;
1673 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1674 // FIXME: if there is no EqualLoc, this is list-initialization.
1675 Init = PerformCopyInitialization(
1676 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1677 if (Init.isInvalid()) {
1678 FD->setInvalidDecl();
1679 return;
1680 }
1681
1682 CheckImplicitConversions(Init.get(), EqualLoc);
1683 }
1684
1685 // C++0x [class.base.init]p7:
1686 // The initialization of each base and member constitutes a
1687 // full-expression.
1688 Init = MaybeCreateExprWithCleanups(Init);
1689 if (Init.isInvalid()) {
1690 FD->setInvalidDecl();
1691 return;
1692 }
1693
1694 InitExpr = Init.release();
1695
1696 FD->setInClassInitializer(InitExpr);
1697}
1698
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001699/// \brief Find the direct and/or virtual base specifiers that
1700/// correspond to the given base type, for use in base initialization
1701/// within a constructor.
1702static bool FindBaseInitializer(Sema &SemaRef,
1703 CXXRecordDecl *ClassDecl,
1704 QualType BaseType,
1705 const CXXBaseSpecifier *&DirectBaseSpec,
1706 const CXXBaseSpecifier *&VirtualBaseSpec) {
1707 // First, check for a direct base class.
1708 DirectBaseSpec = 0;
1709 for (CXXRecordDecl::base_class_const_iterator Base
1710 = ClassDecl->bases_begin();
1711 Base != ClassDecl->bases_end(); ++Base) {
1712 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1713 // We found a direct base of this type. That's what we're
1714 // initializing.
1715 DirectBaseSpec = &*Base;
1716 break;
1717 }
1718 }
1719
1720 // Check for a virtual base class.
1721 // FIXME: We might be able to short-circuit this if we know in advance that
1722 // there are no virtual bases.
1723 VirtualBaseSpec = 0;
1724 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1725 // We haven't found a base yet; search the class hierarchy for a
1726 // virtual base class.
1727 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1728 /*DetectVirtual=*/false);
1729 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1730 BaseType, Paths)) {
1731 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1732 Path != Paths.end(); ++Path) {
1733 if (Path->back().Base->isVirtual()) {
1734 VirtualBaseSpec = Path->back().Base;
1735 break;
1736 }
1737 }
1738 }
1739 }
1740
1741 return DirectBaseSpec || VirtualBaseSpec;
1742}
1743
Sebastian Redl6df65482011-09-24 17:48:25 +00001744/// \brief Handle a C++ member initializer using braced-init-list syntax.
1745MemInitResult
1746Sema::ActOnMemInitializer(Decl *ConstructorD,
1747 Scope *S,
1748 CXXScopeSpec &SS,
1749 IdentifierInfo *MemberOrBase,
1750 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001751 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001752 SourceLocation IdLoc,
1753 Expr *InitList,
1754 SourceLocation EllipsisLoc) {
1755 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001756 DS, IdLoc, MultiInitializer(InitList),
1757 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001758}
1759
1760/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001761MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001762Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001763 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001764 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001765 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001766 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001767 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001768 SourceLocation IdLoc,
1769 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001770 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001771 SourceLocation RParenLoc,
1772 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00001773 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001774 DS, IdLoc, MultiInitializer(LParenLoc, Args,
1775 NumArgs, RParenLoc),
Sebastian Redl6df65482011-09-24 17:48:25 +00001776 EllipsisLoc);
1777}
1778
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001779namespace {
1780
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001781// Callback to only accept typo corrections that can be a valid C++ member
1782// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001783class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1784 public:
1785 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1786 : ClassDecl(ClassDecl) {}
1787
1788 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1789 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1790 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1791 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1792 else
1793 return isa<TypeDecl>(ND);
1794 }
1795 return false;
1796 }
1797
1798 private:
1799 CXXRecordDecl *ClassDecl;
1800};
1801
1802}
1803
Sebastian Redl6df65482011-09-24 17:48:25 +00001804/// \brief Handle a C++ member initializer.
1805MemInitResult
1806Sema::BuildMemInitializer(Decl *ConstructorD,
1807 Scope *S,
1808 CXXScopeSpec &SS,
1809 IdentifierInfo *MemberOrBase,
1810 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001811 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001812 SourceLocation IdLoc,
1813 const MultiInitializer &Args,
1814 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001815 if (!ConstructorD)
1816 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001818 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001819
1820 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001821 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001822 if (!Constructor) {
1823 // The user wrote a constructor initializer on a function that is
1824 // not a C++ constructor. Ignore the error for now, because we may
1825 // have more member initializers coming; we'll diagnose it just
1826 // once in ActOnMemInitializers.
1827 return true;
1828 }
1829
1830 CXXRecordDecl *ClassDecl = Constructor->getParent();
1831
1832 // C++ [class.base.init]p2:
1833 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001834 // constructor's class and, if not found in that scope, are looked
1835 // up in the scope containing the constructor's definition.
1836 // [Note: if the constructor's class contains a member with the
1837 // same name as a direct or virtual base class of the class, a
1838 // mem-initializer-id naming the member or base class and composed
1839 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001840 // mem-initializer-id for the hidden base class may be specified
1841 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001842 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001843 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001844 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001845 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001846 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001847 ValueDecl *Member;
1848 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1849 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001850 if (EllipsisLoc.isValid())
1851 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl6df65482011-09-24 17:48:25 +00001852 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1853
1854 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001855 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001856 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001857 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001858 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001859 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001860 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001861
1862 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001863 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001864 } else if (DS.getTypeSpecType() == TST_decltype) {
1865 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001866 } else {
1867 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1868 LookupParsedName(R, S, &SS);
1869
1870 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1871 if (!TyD) {
1872 if (R.isAmbiguous()) return true;
1873
John McCallfd225442010-04-09 19:01:14 +00001874 // We don't want access-control diagnostics here.
1875 R.suppressDiagnostics();
1876
Douglas Gregor7a886e12010-01-19 06:46:48 +00001877 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1878 bool NotUnknownSpecialization = false;
1879 DeclContext *DC = computeDeclContext(SS, false);
1880 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1881 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1882
1883 if (!NotUnknownSpecialization) {
1884 // When the scope specifier can refer to a member of an unknown
1885 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001886 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1887 SS.getWithLocInContext(Context),
1888 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001889 if (BaseType.isNull())
1890 return true;
1891
Douglas Gregor7a886e12010-01-19 06:46:48 +00001892 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001893 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001894 }
1895 }
1896
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001897 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001898 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001899 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001900 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001901 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001902 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001903 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1904 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1905 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001906 // We have found a non-static data member with a similar
1907 // name to what was typed; complain and initialize that
1908 // member.
1909 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1910 << MemberOrBase << true << CorrectedQuotedStr
1911 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1912 Diag(Member->getLocation(), diag::note_previous_decl)
1913 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001914
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001915 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001916 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001917 const CXXBaseSpecifier *DirectBaseSpec;
1918 const CXXBaseSpecifier *VirtualBaseSpec;
1919 if (FindBaseInitializer(*this, ClassDecl,
1920 Context.getTypeDeclType(Type),
1921 DirectBaseSpec, VirtualBaseSpec)) {
1922 // We have found a direct or virtual base class with a
1923 // similar name to what was typed; complain and initialize
1924 // that base class.
1925 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001926 << MemberOrBase << false << CorrectedQuotedStr
1927 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001928
1929 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1930 : VirtualBaseSpec;
1931 Diag(BaseSpec->getSourceRange().getBegin(),
1932 diag::note_base_class_specified_here)
1933 << BaseSpec->getType()
1934 << BaseSpec->getSourceRange();
1935
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001936 TyD = Type;
1937 }
1938 }
1939 }
1940
Douglas Gregor7a886e12010-01-19 06:46:48 +00001941 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001942 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl6df65482011-09-24 17:48:25 +00001943 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001944 return true;
1945 }
John McCall2b194412009-12-21 10:41:20 +00001946 }
1947
Douglas Gregor7a886e12010-01-19 06:46:48 +00001948 if (BaseType.isNull()) {
1949 BaseType = Context.getTypeDeclType(TyD);
1950 if (SS.isSet()) {
1951 NestedNameSpecifier *Qualifier =
1952 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001953
Douglas Gregor7a886e12010-01-19 06:46:48 +00001954 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001955 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001956 }
John McCall2b194412009-12-21 10:41:20 +00001957 }
1958 }
Mike Stump1eb44332009-09-09 15:08:12 +00001959
John McCalla93c9342009-12-07 02:54:59 +00001960 if (!TInfo)
1961 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001962
Sebastian Redl6df65482011-09-24 17:48:25 +00001963 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001964}
1965
Chandler Carruth81c64772011-09-03 01:14:15 +00001966/// Checks a member initializer expression for cases where reference (or
1967/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001968static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1969 Expr *Init,
1970 SourceLocation IdLoc) {
1971 QualType MemberTy = Member->getType();
1972
1973 // We only handle pointers and references currently.
1974 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1975 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1976 return;
1977
1978 const bool IsPointer = MemberTy->isPointerType();
1979 if (IsPointer) {
1980 if (const UnaryOperator *Op
1981 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1982 // The only case we're worried about with pointers requires taking the
1983 // address.
1984 if (Op->getOpcode() != UO_AddrOf)
1985 return;
1986
1987 Init = Op->getSubExpr();
1988 } else {
1989 // We only handle address-of expression initializers for pointers.
1990 return;
1991 }
1992 }
1993
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001994 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1995 // Taking the address of a temporary will be diagnosed as a hard error.
1996 if (IsPointer)
1997 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001998
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001999 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2000 << Member << Init->getSourceRange();
2001 } else if (const DeclRefExpr *DRE
2002 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2003 // We only warn when referring to a non-reference parameter declaration.
2004 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2005 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002006 return;
2007
2008 S.Diag(Init->getExprLoc(),
2009 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2010 : diag::warn_bind_ref_member_to_parameter)
2011 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002012 } else {
2013 // Other initializers are fine.
2014 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002015 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002016
2017 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2018 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002019}
2020
John McCallb4190042009-11-04 23:02:40 +00002021/// Checks an initializer expression for use of uninitialized fields, such as
2022/// containing the field that is being initialized. Returns true if there is an
2023/// uninitialized field was used an updates the SourceLocation parameter; false
2024/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002025static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002026 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002027 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002028 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2029
Nick Lewycky43ad1822010-06-15 07:32:55 +00002030 if (isa<CallExpr>(S)) {
2031 // Do not descend into function calls or constructors, as the use
2032 // of an uninitialized field may be valid. One would have to inspect
2033 // the contents of the function/ctor to determine if it is safe or not.
2034 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2035 // may be safe, depending on what the function/ctor does.
2036 return false;
2037 }
2038 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2039 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002040
2041 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2042 // The member expression points to a static data member.
2043 assert(VD->isStaticDataMember() &&
2044 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002045 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002046 return false;
2047 }
2048
2049 if (isa<EnumConstantDecl>(RhsField)) {
2050 // The member expression points to an enum.
2051 return false;
2052 }
2053
John McCallb4190042009-11-04 23:02:40 +00002054 if (RhsField == LhsField) {
2055 // Initializing a field with itself. Throw a warning.
2056 // But wait; there are exceptions!
2057 // Exception #1: The field may not belong to this record.
2058 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002059 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002060 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2061 // Even though the field matches, it does not belong to this record.
2062 return false;
2063 }
2064 // None of the exceptions triggered; return true to indicate an
2065 // uninitialized field was used.
2066 *L = ME->getMemberLoc();
2067 return true;
2068 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002069 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002070 // sizeof/alignof doesn't reference contents, do not warn.
2071 return false;
2072 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2073 // address-of doesn't reference contents (the pointer may be dereferenced
2074 // in the same expression but it would be rare; and weird).
2075 if (UOE->getOpcode() == UO_AddrOf)
2076 return false;
John McCallb4190042009-11-04 23:02:40 +00002077 }
John McCall7502c1d2011-02-13 04:07:26 +00002078 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002079 if (!*it) {
2080 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002081 continue;
2082 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002083 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2084 return true;
John McCallb4190042009-11-04 23:02:40 +00002085 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002086 return false;
John McCallb4190042009-11-04 23:02:40 +00002087}
2088
John McCallf312b1e2010-08-26 23:41:50 +00002089MemInitResult
Sebastian Redl6df65482011-09-24 17:48:25 +00002090Sema::BuildMemberInitializer(ValueDecl *Member,
2091 const MultiInitializer &Args,
2092 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002093 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2094 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2095 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002096 "Member must be a FieldDecl or IndirectFieldDecl");
2097
Peter Collingbournefef21892011-10-23 18:59:44 +00002098 if (Args.DiagnoseUnexpandedParameterPack(*this))
2099 return true;
2100
Douglas Gregor464b2f02010-11-05 22:21:31 +00002101 if (Member->isInvalidDecl())
2102 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002103
John McCallb4190042009-11-04 23:02:40 +00002104 // Diagnose value-uses of fields to initialize themselves, e.g.
2105 // foo(foo)
2106 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002107 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl6df65482011-09-24 17:48:25 +00002108 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2109 I != E; ++I) {
John McCallb4190042009-11-04 23:02:40 +00002110 SourceLocation L;
Sebastian Redl6df65482011-09-24 17:48:25 +00002111 Expr *Arg = *I;
2112 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2113 Arg = DIE->getInit();
2114 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002115 // FIXME: Return true in the case when other fields are used before being
2116 // uninitialized. For example, let this field be the i'th field. When
2117 // initializing the i'th field, throw a warning if any of the >= i'th
2118 // fields are used, as they are not yet initialized.
2119 // Right now we are only handling the case where the i'th field uses
2120 // itself in its initializer.
2121 Diag(L, diag::warn_field_is_uninit);
2122 }
2123 }
2124
Sebastian Redl6df65482011-09-24 17:48:25 +00002125 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002126
Chandler Carruth894aed92010-12-06 09:23:57 +00002127 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00002128 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002129 // Can't check initialization for a member of dependent type or when
2130 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002131 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002132
John McCallf85e1932011-06-15 23:02:42 +00002133 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002134 } else {
2135 // Initialize the member.
2136 InitializedEntity MemberEntity =
2137 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2138 : InitializedEntity::InitializeMember(IndirectMember, 0);
2139 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002140 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2141 Args.getEndLoc());
John McCallb4eb64d2010-10-08 02:01:28 +00002142
Sebastian Redl6df65482011-09-24 17:48:25 +00002143 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruth894aed92010-12-06 09:23:57 +00002144 if (MemberInit.isInvalid())
2145 return true;
2146
Sebastian Redl6df65482011-09-24 17:48:25 +00002147 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002148
2149 // C++0x [class.base.init]p7:
2150 // The initialization of each base and member constitutes a
2151 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002152 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002153 if (MemberInit.isInvalid())
2154 return true;
2155
2156 // If we are in a dependent context, template instantiation will
2157 // perform this type-checking again. Just save the arguments that we
2158 // received in a ParenListExpr.
2159 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2160 // of the information that we have about the member
2161 // initializer. However, deconstructing the ASTs is a dicey process,
2162 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002163 if (CurContext->isDependentContext()) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002164 Init = Args.CreateInitExpr(Context,
2165 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00002166 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002167 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002168 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2169 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002170 }
2171
Chandler Carruth894aed92010-12-06 09:23:57 +00002172 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00002173 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002174 IdLoc, Args.getStartLoc(),
2175 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002176 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00002177 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002178 IdLoc, Args.getStartLoc(),
2179 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002180 }
Eli Friedman59c04372009-07-29 19:44:27 +00002181}
2182
John McCallf312b1e2010-08-26 23:41:50 +00002183MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00002184Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002185 const MultiInitializer &Args,
Sean Hunt41717662011-02-26 19:13:13 +00002186 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002187 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002188 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002189 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002190 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002191 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002192
Sean Hunt41717662011-02-26 19:13:13 +00002193 // Initialize the object.
2194 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2195 QualType(ClassDecl->getTypeForDecl(), 0));
2196 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002197 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2198 Args.getEndLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002199
Sebastian Redl6df65482011-09-24 17:48:25 +00002200 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Sean Hunt41717662011-02-26 19:13:13 +00002201 if (DelegationInit.isInvalid())
2202 return true;
2203
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002204 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2205 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002206
Sebastian Redl6df65482011-09-24 17:48:25 +00002207 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002208
2209 // C++0x [class.base.init]p7:
2210 // The initialization of each base and member constitutes a
2211 // full-expression.
2212 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2213 if (DelegationInit.isInvalid())
2214 return true;
2215
Douglas Gregor76852c22011-11-01 01:16:03 +00002216 return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
Sean Hunt41717662011-02-26 19:13:13 +00002217 DelegationInit.takeAs<Expr>(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002218 Args.getEndLoc());
Sean Hunt97fcc492011-01-08 19:20:43 +00002219}
2220
2221MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002222Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002223 const MultiInitializer &Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002224 CXXRecordDecl *ClassDecl,
2225 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002226 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002227
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002228 SourceLocation BaseLoc
2229 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002230
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002231 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2232 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2233 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2234
2235 // C++ [class.base.init]p2:
2236 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002237 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002238 // of that class, the mem-initializer is ill-formed. A
2239 // mem-initializer-list can initialize a base class using any
2240 // name that denotes that base class type.
2241 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2242
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002243 if (EllipsisLoc.isValid()) {
2244 // This is a pack expansion.
2245 if (!BaseType->containsUnexpandedParameterPack()) {
2246 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl6df65482011-09-24 17:48:25 +00002247 << SourceRange(BaseLoc, Args.getEndLoc());
2248
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002249 EllipsisLoc = SourceLocation();
2250 }
2251 } else {
2252 // Check for any unexpanded parameter packs.
2253 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2254 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002255
2256 if (Args.DiagnoseUnexpandedParameterPack(*this))
2257 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002258 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002259
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002260 // Check for direct and virtual base classes.
2261 const CXXBaseSpecifier *DirectBaseSpec = 0;
2262 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2263 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002264 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2265 BaseType))
Douglas Gregor76852c22011-11-01 01:16:03 +00002266 return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002267
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002268 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2269 VirtualBaseSpec);
2270
2271 // C++ [base.class.init]p2:
2272 // Unless the mem-initializer-id names a nonstatic data member of the
2273 // constructor's class or a direct or virtual base of that class, the
2274 // mem-initializer is ill-formed.
2275 if (!DirectBaseSpec && !VirtualBaseSpec) {
2276 // If the class has any dependent bases, then it's possible that
2277 // one of those types will resolve to the same type as
2278 // BaseType. Therefore, just treat this as a dependent base
2279 // class initialization. FIXME: Should we try to check the
2280 // initialization anyway? It seems odd.
2281 if (ClassDecl->hasAnyDependentBases())
2282 Dependent = true;
2283 else
2284 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2285 << BaseType << Context.getTypeDeclType(ClassDecl)
2286 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2287 }
2288 }
2289
2290 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002291 // Can't check initialization for a base of dependent type or when
2292 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002293 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman59c04372009-07-29 19:44:27 +00002294
John McCallf85e1932011-06-15 23:02:42 +00002295 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Sebastian Redl6df65482011-09-24 17:48:25 +00002297 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2298 /*IsVirtual=*/false,
2299 Args.getStartLoc(), BaseInit,
2300 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002301 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002302
2303 // C++ [base.class.init]p2:
2304 // If a mem-initializer-id is ambiguous because it designates both
2305 // a direct non-virtual base class and an inherited virtual base
2306 // class, the mem-initializer is ill-formed.
2307 if (DirectBaseSpec && VirtualBaseSpec)
2308 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002309 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002310
2311 CXXBaseSpecifier *BaseSpec
2312 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2313 if (!BaseSpec)
2314 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2315
2316 // Initialize the base.
2317 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00002318 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002319 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002320 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2321 Args.getEndLoc());
2322
2323 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002324 if (BaseInit.isInvalid())
2325 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002326
Sebastian Redl6df65482011-09-24 17:48:25 +00002327 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2328
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002329 // C++0x [class.base.init]p7:
2330 // The initialization of each base and member constitutes a
2331 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002332 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002333 if (BaseInit.isInvalid())
2334 return true;
2335
2336 // If we are in a dependent context, template instantiation will
2337 // perform this type-checking again. Just save the arguments that we
2338 // received in a ParenListExpr.
2339 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2340 // of the information that we have about the base
2341 // initializer. However, deconstructing the ASTs is a dicey process,
2342 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002343 if (CurContext->isDependentContext())
2344 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002345
Sean Huntcbb67482011-01-08 20:30:50 +00002346 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002347 BaseSpec->isVirtual(),
2348 Args.getStartLoc(),
2349 BaseInit.takeAs<Expr>(),
2350 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002351}
2352
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002353// Create a static_cast\<T&&>(expr).
2354static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2355 QualType ExprType = E->getType();
2356 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2357 SourceLocation ExprLoc = E->getLocStart();
2358 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2359 TargetType, ExprLoc);
2360
2361 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2362 SourceRange(ExprLoc, ExprLoc),
2363 E->getSourceRange()).take();
2364}
2365
Anders Carlssone5ef7402010-04-23 03:10:23 +00002366/// ImplicitInitializerKind - How an implicit base or member initializer should
2367/// initialize its base or member.
2368enum ImplicitInitializerKind {
2369 IIK_Default,
2370 IIK_Copy,
2371 IIK_Move
2372};
2373
Anders Carlssondefefd22010-04-23 02:00:02 +00002374static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002375BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002376 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002377 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002378 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002379 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002380 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002381 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2382 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002383
John McCall60d7b3a2010-08-24 06:29:42 +00002384 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002385
2386 switch (ImplicitInitKind) {
2387 case IIK_Default: {
2388 InitializationKind InitKind
2389 = InitializationKind::CreateDefault(Constructor->getLocation());
2390 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2391 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002392 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002393 break;
2394 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002395
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002396 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002397 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002398 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002399 ParmVarDecl *Param = Constructor->getParamDecl(0);
2400 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002401
Anders Carlssone5ef7402010-04-23 03:10:23 +00002402 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002403 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2404 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002405 Constructor->getLocation(), ParamType,
2406 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002407
Eli Friedman5f2987c2012-02-02 03:46:19 +00002408 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2409
Anders Carlssonc7957502010-04-24 22:02:54 +00002410 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002411 QualType ArgTy =
2412 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2413 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002414
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002415 if (Moving) {
2416 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2417 }
2418
John McCallf871d0c2010-08-07 06:22:56 +00002419 CXXCastPath BasePath;
2420 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002421 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2422 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002423 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002424 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002425
Anders Carlssone5ef7402010-04-23 03:10:23 +00002426 InitializationKind InitKind
2427 = InitializationKind::CreateDirect(Constructor->getLocation(),
2428 SourceLocation(), SourceLocation());
2429 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2430 &CopyCtorArg, 1);
2431 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002432 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002433 break;
2434 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002435 }
John McCall9ae2f072010-08-23 23:25:46 +00002436
Douglas Gregor53c374f2010-12-07 00:41:46 +00002437 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002438 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002439 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002440
Anders Carlssondefefd22010-04-23 02:00:02 +00002441 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002442 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002443 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2444 SourceLocation()),
2445 BaseSpec->isVirtual(),
2446 SourceLocation(),
2447 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002448 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002449 SourceLocation());
2450
Anders Carlssondefefd22010-04-23 02:00:02 +00002451 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002452}
2453
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002454static bool RefersToRValueRef(Expr *MemRef) {
2455 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2456 return Referenced->getType()->isRValueReferenceType();
2457}
2458
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002459static bool
2460BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002461 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002462 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002463 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002464 if (Field->isInvalidDecl())
2465 return true;
2466
Chandler Carruthf186b542010-06-29 23:50:44 +00002467 SourceLocation Loc = Constructor->getLocation();
2468
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002469 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2470 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002471 ParmVarDecl *Param = Constructor->getParamDecl(0);
2472 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002473
2474 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002475 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2476 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002477
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002478 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002479 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2480 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002481 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002482
Eli Friedman5f2987c2012-02-02 03:46:19 +00002483 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2484
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002485 if (Moving) {
2486 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2487 }
2488
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002489 // Build a reference to this field within the parameter.
2490 CXXScopeSpec SS;
2491 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2492 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002493 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2494 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002495 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002496 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002497 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002498 ParamType, Loc,
2499 /*IsArrow=*/false,
2500 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002501 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002502 /*FirstQualifierInScope=*/0,
2503 MemberLookup,
2504 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002505 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002506 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002507
2508 // C++11 [class.copy]p15:
2509 // - if a member m has rvalue reference type T&&, it is direct-initialized
2510 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002511 if (RefersToRValueRef(CtorArg.get())) {
2512 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002513 }
2514
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002515 // When the field we are copying is an array, create index variables for
2516 // each dimension of the array. We use these index variables to subscript
2517 // the source array, and other clients (e.g., CodeGen) will perform the
2518 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002519 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002520 QualType BaseType = Field->getType();
2521 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002522 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002523 while (const ConstantArrayType *Array
2524 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002525 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002526 // Create the iteration variable for this array index.
2527 IdentifierInfo *IterationVarName = 0;
2528 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002529 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002530 llvm::raw_svector_ostream OS(Str);
2531 OS << "__i" << IndexVariables.size();
2532 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2533 }
2534 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002535 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002536 IterationVarName, SizeType,
2537 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002538 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002539 IndexVariables.push_back(IterationVar);
2540
2541 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002542 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002543 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002544 assert(!IterationVarRef.isInvalid() &&
2545 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002546 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2547 assert(!IterationVarRef.isInvalid() &&
2548 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002549
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002550 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002551 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002552 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002553 Loc);
2554 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002555 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002556
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002557 BaseType = Array->getElementType();
2558 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002559
2560 // The array subscript expression is an lvalue, which is wrong for moving.
2561 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002562 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002563
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002564 // Construct the entity that we will be initializing. For an array, this
2565 // will be first element in the array, which may require several levels
2566 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002567 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002568 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002569 if (Indirect)
2570 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2571 else
2572 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002573 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2574 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2575 0,
2576 Entities.back()));
2577
2578 // Direct-initialize to use the copy constructor.
2579 InitializationKind InitKind =
2580 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2581
Sebastian Redl74e611a2011-09-04 18:14:28 +00002582 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002583 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002584 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002585
John McCall60d7b3a2010-08-24 06:29:42 +00002586 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002587 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002588 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002589 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002590 if (MemberInit.isInvalid())
2591 return true;
2592
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002593 if (Indirect) {
2594 assert(IndexVariables.size() == 0 &&
2595 "Indirect field improperly initialized");
2596 CXXMemberInit
2597 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2598 Loc, Loc,
2599 MemberInit.takeAs<Expr>(),
2600 Loc);
2601 } else
2602 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2603 Loc, MemberInit.takeAs<Expr>(),
2604 Loc,
2605 IndexVariables.data(),
2606 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002607 return false;
2608 }
2609
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002610 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2611
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002612 QualType FieldBaseElementType =
2613 SemaRef.Context.getBaseElementType(Field->getType());
2614
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002615 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002616 InitializedEntity InitEntity
2617 = Indirect? InitializedEntity::InitializeMember(Indirect)
2618 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002619 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002620 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002621
2622 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002623 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002624 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002625
Douglas Gregor53c374f2010-12-07 00:41:46 +00002626 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002627 if (MemberInit.isInvalid())
2628 return true;
2629
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002630 if (Indirect)
2631 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2632 Indirect, Loc,
2633 Loc,
2634 MemberInit.get(),
2635 Loc);
2636 else
2637 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2638 Field, Loc, Loc,
2639 MemberInit.get(),
2640 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002641 return false;
2642 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002643
Sean Hunt1f2f3842011-05-17 00:19:05 +00002644 if (!Field->getParent()->isUnion()) {
2645 if (FieldBaseElementType->isReferenceType()) {
2646 SemaRef.Diag(Constructor->getLocation(),
2647 diag::err_uninitialized_member_in_ctor)
2648 << (int)Constructor->isImplicit()
2649 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2650 << 0 << Field->getDeclName();
2651 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2652 return true;
2653 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002654
Sean Hunt1f2f3842011-05-17 00:19:05 +00002655 if (FieldBaseElementType.isConstQualified()) {
2656 SemaRef.Diag(Constructor->getLocation(),
2657 diag::err_uninitialized_member_in_ctor)
2658 << (int)Constructor->isImplicit()
2659 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2660 << 1 << Field->getDeclName();
2661 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2662 return true;
2663 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002664 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002665
John McCallf85e1932011-06-15 23:02:42 +00002666 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2667 FieldBaseElementType->isObjCRetainableType() &&
2668 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2669 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2670 // Instant objects:
2671 // Default-initialize Objective-C pointers to NULL.
2672 CXXMemberInit
2673 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2674 Loc, Loc,
2675 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2676 Loc);
2677 return false;
2678 }
2679
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002680 // Nothing to initialize.
2681 CXXMemberInit = 0;
2682 return false;
2683}
John McCallf1860e52010-05-20 23:23:51 +00002684
2685namespace {
2686struct BaseAndFieldInfo {
2687 Sema &S;
2688 CXXConstructorDecl *Ctor;
2689 bool AnyErrorsInInits;
2690 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002691 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002692 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002693
2694 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2695 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002696 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2697 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002698 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002699 else if (Generated && Ctor->isMoveConstructor())
2700 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002701 else
2702 IIK = IIK_Default;
2703 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002704
2705 bool isImplicitCopyOrMove() const {
2706 switch (IIK) {
2707 case IIK_Copy:
2708 case IIK_Move:
2709 return true;
2710
2711 case IIK_Default:
2712 return false;
2713 }
David Blaikie30263482012-01-20 21:50:17 +00002714
2715 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002716 }
John McCallf1860e52010-05-20 23:23:51 +00002717};
2718}
2719
Richard Smitha4950662011-09-19 13:34:43 +00002720/// \brief Determine whether the given indirect field declaration is somewhere
2721/// within an anonymous union.
2722static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2723 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2724 CEnd = F->chain_end();
2725 C != CEnd; ++C)
2726 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2727 if (Record->isUnion())
2728 return true;
2729
2730 return false;
2731}
2732
Douglas Gregorddb21472011-11-02 23:04:16 +00002733/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2734/// array type.
2735static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2736 if (T->isIncompleteArrayType())
2737 return true;
2738
2739 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2740 if (!ArrayT->getSize())
2741 return true;
2742
2743 T = ArrayT->getElementType();
2744 }
2745
2746 return false;
2747}
2748
Richard Smith7a614d82011-06-11 17:19:42 +00002749static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002750 FieldDecl *Field,
2751 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002752
Chandler Carruthe861c602010-06-30 02:59:29 +00002753 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002754 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002755 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002756 return false;
2757 }
2758
Richard Smith7a614d82011-06-11 17:19:42 +00002759 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2760 // has a brace-or-equal-initializer, the entity is initialized as specified
2761 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002762 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002763 CXXCtorInitializer *Init;
2764 if (Indirect)
2765 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2766 SourceLocation(),
2767 SourceLocation(), 0,
2768 SourceLocation());
2769 else
2770 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2771 SourceLocation(),
2772 SourceLocation(), 0,
2773 SourceLocation());
2774 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002775 return false;
2776 }
2777
Richard Smithc115f632011-09-18 11:14:50 +00002778 // Don't build an implicit initializer for union members if none was
2779 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002780 if (Field->getParent()->isUnion() ||
2781 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002782 return false;
2783
Douglas Gregorddb21472011-11-02 23:04:16 +00002784 // Don't initialize incomplete or zero-length arrays.
2785 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2786 return false;
2787
John McCallf1860e52010-05-20 23:23:51 +00002788 // Don't try to build an implicit initializer if there were semantic
2789 // errors in any of the initializers (and therefore we might be
2790 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002791 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002792 return false;
2793
Sean Huntcbb67482011-01-08 20:30:50 +00002794 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002795 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2796 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002797 return true;
John McCallf1860e52010-05-20 23:23:51 +00002798
Francois Pichet00eb3f92010-12-04 09:14:42 +00002799 if (Init)
2800 Info.AllToInit.push_back(Init);
2801
John McCallf1860e52010-05-20 23:23:51 +00002802 return false;
2803}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002804
2805bool
2806Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2807 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002808 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002809 Constructor->setNumCtorInitializers(1);
2810 CXXCtorInitializer **initializer =
2811 new (Context) CXXCtorInitializer*[1];
2812 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2813 Constructor->setCtorInitializers(initializer);
2814
Sean Huntb76af9c2011-05-03 23:05:34 +00002815 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002816 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002817 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2818 }
2819
Sean Huntc1598702011-05-05 00:05:47 +00002820 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002821
Sean Hunt059ce0d2011-05-01 07:04:31 +00002822 return false;
2823}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002824
John McCallb77115d2011-06-17 00:18:42 +00002825bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2826 CXXCtorInitializer **Initializers,
2827 unsigned NumInitializers,
2828 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002829 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002830 // Just store the initializers as written, they will be checked during
2831 // instantiation.
2832 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002833 Constructor->setNumCtorInitializers(NumInitializers);
2834 CXXCtorInitializer **baseOrMemberInitializers =
2835 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002836 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002837 NumInitializers * sizeof(CXXCtorInitializer*));
2838 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002839 }
2840
2841 return false;
2842 }
2843
John McCallf1860e52010-05-20 23:23:51 +00002844 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002845
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002846 // We need to build the initializer AST according to order of construction
2847 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002848 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002849 if (!ClassDecl)
2850 return true;
2851
Eli Friedman80c30da2009-11-09 19:20:36 +00002852 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002853
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002854 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002855 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002856
2857 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002858 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002859 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002860 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002861 }
2862
Anders Carlsson711f34a2010-04-21 19:52:01 +00002863 // Keep track of the direct virtual bases.
2864 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2865 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2866 E = ClassDecl->bases_end(); I != E; ++I) {
2867 if (I->isVirtual())
2868 DirectVBases.insert(I);
2869 }
2870
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002871 // Push virtual bases before others.
2872 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2873 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2874
Sean Huntcbb67482011-01-08 20:30:50 +00002875 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002876 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2877 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002878 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002879 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002880 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002881 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002882 VBase, IsInheritedVirtualBase,
2883 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002884 HadError = true;
2885 continue;
2886 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002887
John McCallf1860e52010-05-20 23:23:51 +00002888 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002889 }
2890 }
Mike Stump1eb44332009-09-09 15:08:12 +00002891
John McCallf1860e52010-05-20 23:23:51 +00002892 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002893 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2894 E = ClassDecl->bases_end(); Base != E; ++Base) {
2895 // Virtuals are in the virtual base list and already constructed.
2896 if (Base->isVirtual())
2897 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002898
Sean Huntcbb67482011-01-08 20:30:50 +00002899 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002900 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2901 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002902 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002903 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002904 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002905 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002906 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002907 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002908 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002909 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002910
John McCallf1860e52010-05-20 23:23:51 +00002911 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002912 }
2913 }
Mike Stump1eb44332009-09-09 15:08:12 +00002914
John McCallf1860e52010-05-20 23:23:51 +00002915 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002916 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2917 MemEnd = ClassDecl->decls_end();
2918 Mem != MemEnd; ++Mem) {
2919 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002920 // C++ [class.bit]p2:
2921 // A declaration for a bit-field that omits the identifier declares an
2922 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2923 // initialized.
2924 if (F->isUnnamedBitfield())
2925 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002926
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002927 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002928 // handle anonymous struct/union fields based on their individual
2929 // indirect fields.
2930 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2931 continue;
2932
2933 if (CollectFieldInitializer(*this, Info, F))
2934 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002935 continue;
2936 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002937
2938 // Beyond this point, we only consider default initialization.
2939 if (Info.IIK != IIK_Default)
2940 continue;
2941
2942 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2943 if (F->getType()->isIncompleteArrayType()) {
2944 assert(ClassDecl->hasFlexibleArrayMember() &&
2945 "Incomplete array type is not valid");
2946 continue;
2947 }
2948
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002949 // Initialize each field of an anonymous struct individually.
2950 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2951 HadError = true;
2952
2953 continue;
2954 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002955 }
Mike Stump1eb44332009-09-09 15:08:12 +00002956
John McCallf1860e52010-05-20 23:23:51 +00002957 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002958 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002959 Constructor->setNumCtorInitializers(NumInitializers);
2960 CXXCtorInitializer **baseOrMemberInitializers =
2961 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002962 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002963 NumInitializers * sizeof(CXXCtorInitializer*));
2964 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002965
John McCallef027fe2010-03-16 21:39:52 +00002966 // Constructors implicitly reference the base and member
2967 // destructors.
2968 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2969 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002970 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002971
2972 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002973}
2974
Eli Friedman6347f422009-07-21 19:28:10 +00002975static void *GetKeyForTopLevelField(FieldDecl *Field) {
2976 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002977 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002978 if (RT->getDecl()->isAnonymousStructOrUnion())
2979 return static_cast<void *>(RT->getDecl());
2980 }
2981 return static_cast<void *>(Field);
2982}
2983
Anders Carlssonea356fb2010-04-02 05:42:15 +00002984static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002985 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002986}
2987
Anders Carlssonea356fb2010-04-02 05:42:15 +00002988static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002989 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002990 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002991 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002992
Eli Friedman6347f422009-07-21 19:28:10 +00002993 // For fields injected into the class via declaration of an anonymous union,
2994 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002995 FieldDecl *Field = Member->getAnyMember();
2996
John McCall3c3ccdb2010-04-10 09:28:51 +00002997 // If the field is a member of an anonymous struct or union, our key
2998 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002999 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003000 if (RD->isAnonymousStructOrUnion()) {
3001 while (true) {
3002 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3003 if (Parent->isAnonymousStructOrUnion())
3004 RD = Parent;
3005 else
3006 break;
3007 }
3008
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003009 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003010 }
Mike Stump1eb44332009-09-09 15:08:12 +00003011
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003012 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003013}
3014
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003015static void
3016DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003017 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003018 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003019 unsigned NumInits) {
3020 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003021 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003022
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003023 // Don't check initializers order unless the warning is enabled at the
3024 // location of at least one initializer.
3025 bool ShouldCheckOrder = false;
3026 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003027 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003028 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3029 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003030 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003031 ShouldCheckOrder = true;
3032 break;
3033 }
3034 }
3035 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003036 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003037
John McCalld6ca8da2010-04-10 07:37:23 +00003038 // Build the list of bases and members in the order that they'll
3039 // actually be initialized. The explicit initializers should be in
3040 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003041 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003042
Anders Carlsson071d6102010-04-02 03:38:04 +00003043 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3044
John McCalld6ca8da2010-04-10 07:37:23 +00003045 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003046 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003047 ClassDecl->vbases_begin(),
3048 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003049 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003050
John McCalld6ca8da2010-04-10 07:37:23 +00003051 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003052 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003053 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003054 if (Base->isVirtual())
3055 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003056 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003057 }
Mike Stump1eb44332009-09-09 15:08:12 +00003058
John McCalld6ca8da2010-04-10 07:37:23 +00003059 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003060 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003061 E = ClassDecl->field_end(); Field != E; ++Field) {
3062 if (Field->isUnnamedBitfield())
3063 continue;
3064
John McCalld6ca8da2010-04-10 07:37:23 +00003065 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003066 }
3067
John McCalld6ca8da2010-04-10 07:37:23 +00003068 unsigned NumIdealInits = IdealInitKeys.size();
3069 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003070
Sean Huntcbb67482011-01-08 20:30:50 +00003071 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003072 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003073 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003074 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003075
3076 // Scan forward to try to find this initializer in the idealized
3077 // initializers list.
3078 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3079 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003080 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003081
3082 // If we didn't find this initializer, it must be because we
3083 // scanned past it on a previous iteration. That can only
3084 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003085 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003086 Sema::SemaDiagnosticBuilder D =
3087 SemaRef.Diag(PrevInit->getSourceLocation(),
3088 diag::warn_initializer_out_of_order);
3089
Francois Pichet00eb3f92010-12-04 09:14:42 +00003090 if (PrevInit->isAnyMemberInitializer())
3091 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003092 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003093 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003094
Francois Pichet00eb3f92010-12-04 09:14:42 +00003095 if (Init->isAnyMemberInitializer())
3096 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003097 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003098 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003099
3100 // Move back to the initializer's location in the ideal list.
3101 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3102 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003103 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003104
3105 assert(IdealIndex != NumIdealInits &&
3106 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003107 }
John McCalld6ca8da2010-04-10 07:37:23 +00003108
3109 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003110 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003111}
3112
John McCall3c3ccdb2010-04-10 09:28:51 +00003113namespace {
3114bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003115 CXXCtorInitializer *Init,
3116 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003117 if (!PrevInit) {
3118 PrevInit = Init;
3119 return false;
3120 }
3121
3122 if (FieldDecl *Field = Init->getMember())
3123 S.Diag(Init->getSourceLocation(),
3124 diag::err_multiple_mem_initialization)
3125 << Field->getDeclName()
3126 << Init->getSourceRange();
3127 else {
John McCallf4c73712011-01-19 06:33:43 +00003128 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003129 assert(BaseClass && "neither field nor base");
3130 S.Diag(Init->getSourceLocation(),
3131 diag::err_multiple_base_initialization)
3132 << QualType(BaseClass, 0)
3133 << Init->getSourceRange();
3134 }
3135 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3136 << 0 << PrevInit->getSourceRange();
3137
3138 return true;
3139}
3140
Sean Huntcbb67482011-01-08 20:30:50 +00003141typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003142typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3143
3144bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003145 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003146 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003147 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003148 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003149 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003150
3151 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003152 if (Parent->isUnion()) {
3153 UnionEntry &En = Unions[Parent];
3154 if (En.first && En.first != Child) {
3155 S.Diag(Init->getSourceLocation(),
3156 diag::err_multiple_mem_union_initialization)
3157 << Field->getDeclName()
3158 << Init->getSourceRange();
3159 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3160 << 0 << En.second->getSourceRange();
3161 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003162 }
3163 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003164 En.first = Child;
3165 En.second = Init;
3166 }
David Blaikie6fe29652011-11-17 06:01:57 +00003167 if (!Parent->isAnonymousStructOrUnion())
3168 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003169 }
3170
3171 Child = Parent;
3172 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003173 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003174
3175 return false;
3176}
3177}
3178
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003179/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003180void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003181 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003182 CXXCtorInitializer **meminits,
3183 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003184 bool AnyErrors) {
3185 if (!ConstructorDecl)
3186 return;
3187
3188 AdjustDeclIfTemplate(ConstructorDecl);
3189
3190 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003191 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003192
3193 if (!Constructor) {
3194 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3195 return;
3196 }
3197
Sean Huntcbb67482011-01-08 20:30:50 +00003198 CXXCtorInitializer **MemInits =
3199 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003200
3201 // Mapping for the duplicate initializers check.
3202 // For member initializers, this is keyed with a FieldDecl*.
3203 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003204 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003205
3206 // Mapping for the inconsistent anonymous-union initializers check.
3207 RedundantUnionMap MemberUnions;
3208
Anders Carlssonea356fb2010-04-02 05:42:15 +00003209 bool HadError = false;
3210 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003211 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003212
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003213 // Set the source order index.
3214 Init->setSourceOrder(i);
3215
Francois Pichet00eb3f92010-12-04 09:14:42 +00003216 if (Init->isAnyMemberInitializer()) {
3217 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003218 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3219 CheckRedundantUnionInit(*this, Init, MemberUnions))
3220 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003221 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003222 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3223 if (CheckRedundantInit(*this, Init, Members[Key]))
3224 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003225 } else {
3226 assert(Init->isDelegatingInitializer());
3227 // This must be the only initializer
3228 if (i != 0 || NumMemInits > 1) {
3229 Diag(MemInits[0]->getSourceLocation(),
3230 diag::err_delegating_initializer_alone)
3231 << MemInits[0]->getSourceRange();
3232 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003233 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003234 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003235 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003236 // Return immediately as the initializer is set.
3237 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003238 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003239 }
3240
Anders Carlssonea356fb2010-04-02 05:42:15 +00003241 if (HadError)
3242 return;
3243
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003244 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003245
Sean Huntcbb67482011-01-08 20:30:50 +00003246 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003247}
3248
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003249void
John McCallef027fe2010-03-16 21:39:52 +00003250Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3251 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003252 // Ignore dependent contexts. Also ignore unions, since their members never
3253 // have destructors implicitly called.
3254 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003255 return;
John McCall58e6f342010-03-16 05:22:47 +00003256
3257 // FIXME: all the access-control diagnostics are positioned on the
3258 // field/base declaration. That's probably good; that said, the
3259 // user might reasonably want to know why the destructor is being
3260 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003261
Anders Carlsson9f853df2009-11-17 04:44:12 +00003262 // Non-static data members.
3263 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3264 E = ClassDecl->field_end(); I != E; ++I) {
3265 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003266 if (Field->isInvalidDecl())
3267 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003268
3269 // Don't destroy incomplete or zero-length arrays.
3270 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3271 continue;
3272
Anders Carlsson9f853df2009-11-17 04:44:12 +00003273 QualType FieldType = Context.getBaseElementType(Field->getType());
3274
3275 const RecordType* RT = FieldType->getAs<RecordType>();
3276 if (!RT)
3277 continue;
3278
3279 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003280 if (FieldClassDecl->isInvalidDecl())
3281 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003282 if (FieldClassDecl->hasTrivialDestructor())
3283 continue;
3284
Douglas Gregordb89f282010-07-01 22:47:18 +00003285 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003286 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003287 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003288 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003289 << Field->getDeclName()
3290 << FieldType);
3291
Eli Friedman5f2987c2012-02-02 03:46:19 +00003292 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003293 }
3294
John McCall58e6f342010-03-16 05:22:47 +00003295 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3296
Anders Carlsson9f853df2009-11-17 04:44:12 +00003297 // Bases.
3298 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3299 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003300 // Bases are always records in a well-formed non-dependent class.
3301 const RecordType *RT = Base->getType()->getAs<RecordType>();
3302
3303 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003304 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003305 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003306
John McCall58e6f342010-03-16 05:22:47 +00003307 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003308 // If our base class is invalid, we probably can't get its dtor anyway.
3309 if (BaseClassDecl->isInvalidDecl())
3310 continue;
3311 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003312 if (BaseClassDecl->hasTrivialDestructor())
3313 continue;
John McCall58e6f342010-03-16 05:22:47 +00003314
Douglas Gregordb89f282010-07-01 22:47:18 +00003315 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003316 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003317
3318 // FIXME: caret should be on the start of the class name
3319 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003320 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003321 << Base->getType()
3322 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003323
Eli Friedman5f2987c2012-02-02 03:46:19 +00003324 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003325 }
3326
3327 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003328 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3329 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003330
3331 // Bases are always records in a well-formed non-dependent class.
3332 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3333
3334 // Ignore direct virtual bases.
3335 if (DirectVirtualBases.count(RT))
3336 continue;
3337
John McCall58e6f342010-03-16 05:22:47 +00003338 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003339 // If our base class is invalid, we probably can't get its dtor anyway.
3340 if (BaseClassDecl->isInvalidDecl())
3341 continue;
3342 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003343 if (BaseClassDecl->hasTrivialDestructor())
3344 continue;
John McCall58e6f342010-03-16 05:22:47 +00003345
Douglas Gregordb89f282010-07-01 22:47:18 +00003346 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003347 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003348 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003349 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003350 << VBase->getType());
3351
Eli Friedman5f2987c2012-02-02 03:46:19 +00003352 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003353 }
3354}
3355
John McCalld226f652010-08-21 09:40:31 +00003356void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003357 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003358 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003359
Mike Stump1eb44332009-09-09 15:08:12 +00003360 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003361 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003362 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003363}
3364
Mike Stump1eb44332009-09-09 15:08:12 +00003365bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003366 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003367 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003368 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003369 else
John McCall94c3b562010-08-18 09:41:07 +00003370 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003371}
3372
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003373bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003374 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003375 if (!getLangOptions().CPlusPlus)
3376 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003377
Anders Carlsson11f21a02009-03-23 19:10:31 +00003378 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003379 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003380
Ted Kremenek6217b802009-07-29 21:53:49 +00003381 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003382 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003383 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003384 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003385
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003386 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003387 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003388 }
Mike Stump1eb44332009-09-09 15:08:12 +00003389
Ted Kremenek6217b802009-07-29 21:53:49 +00003390 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003391 if (!RT)
3392 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003393
John McCall86ff3082010-02-04 22:26:26 +00003394 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003395
John McCall94c3b562010-08-18 09:41:07 +00003396 // We can't answer whether something is abstract until it has a
3397 // definition. If it's currently being defined, we'll walk back
3398 // over all the declarations when we have a full definition.
3399 const CXXRecordDecl *Def = RD->getDefinition();
3400 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003401 return false;
3402
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003403 if (!RD->isAbstract())
3404 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003405
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003406 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003407 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003408
John McCall94c3b562010-08-18 09:41:07 +00003409 return true;
3410}
3411
3412void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3413 // Check if we've already emitted the list of pure virtual functions
3414 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003415 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003416 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003417
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003418 CXXFinalOverriderMap FinalOverriders;
3419 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003420
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003421 // Keep a set of seen pure methods so we won't diagnose the same method
3422 // more than once.
3423 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3424
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003425 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3426 MEnd = FinalOverriders.end();
3427 M != MEnd;
3428 ++M) {
3429 for (OverridingMethods::iterator SO = M->second.begin(),
3430 SOEnd = M->second.end();
3431 SO != SOEnd; ++SO) {
3432 // C++ [class.abstract]p4:
3433 // A class is abstract if it contains or inherits at least one
3434 // pure virtual function for which the final overrider is pure
3435 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003437 //
3438 if (SO->second.size() != 1)
3439 continue;
3440
3441 if (!SO->second.front().Method->isPure())
3442 continue;
3443
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003444 if (!SeenPureMethods.insert(SO->second.front().Method))
3445 continue;
3446
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003447 Diag(SO->second.front().Method->getLocation(),
3448 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003449 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003450 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003451 }
3452
3453 if (!PureVirtualClassDiagSet)
3454 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3455 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003456}
3457
Anders Carlsson8211eff2009-03-24 01:19:16 +00003458namespace {
John McCall94c3b562010-08-18 09:41:07 +00003459struct AbstractUsageInfo {
3460 Sema &S;
3461 CXXRecordDecl *Record;
3462 CanQualType AbstractType;
3463 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003464
John McCall94c3b562010-08-18 09:41:07 +00003465 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3466 : S(S), Record(Record),
3467 AbstractType(S.Context.getCanonicalType(
3468 S.Context.getTypeDeclType(Record))),
3469 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003470
John McCall94c3b562010-08-18 09:41:07 +00003471 void DiagnoseAbstractType() {
3472 if (Invalid) return;
3473 S.DiagnoseAbstractType(Record);
3474 Invalid = true;
3475 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003476
John McCall94c3b562010-08-18 09:41:07 +00003477 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3478};
3479
3480struct CheckAbstractUsage {
3481 AbstractUsageInfo &Info;
3482 const NamedDecl *Ctx;
3483
3484 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3485 : Info(Info), Ctx(Ctx) {}
3486
3487 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3488 switch (TL.getTypeLocClass()) {
3489#define ABSTRACT_TYPELOC(CLASS, PARENT)
3490#define TYPELOC(CLASS, PARENT) \
3491 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3492#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003493 }
John McCall94c3b562010-08-18 09:41:07 +00003494 }
Mike Stump1eb44332009-09-09 15:08:12 +00003495
John McCall94c3b562010-08-18 09:41:07 +00003496 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3497 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3498 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003499 if (!TL.getArg(I))
3500 continue;
3501
John McCall94c3b562010-08-18 09:41:07 +00003502 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3503 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003504 }
John McCall94c3b562010-08-18 09:41:07 +00003505 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003506
John McCall94c3b562010-08-18 09:41:07 +00003507 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3508 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3509 }
Mike Stump1eb44332009-09-09 15:08:12 +00003510
John McCall94c3b562010-08-18 09:41:07 +00003511 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3512 // Visit the type parameters from a permissive context.
3513 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3514 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3515 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3516 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3517 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3518 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003519 }
John McCall94c3b562010-08-18 09:41:07 +00003520 }
Mike Stump1eb44332009-09-09 15:08:12 +00003521
John McCall94c3b562010-08-18 09:41:07 +00003522 // Visit pointee types from a permissive context.
3523#define CheckPolymorphic(Type) \
3524 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3525 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3526 }
3527 CheckPolymorphic(PointerTypeLoc)
3528 CheckPolymorphic(ReferenceTypeLoc)
3529 CheckPolymorphic(MemberPointerTypeLoc)
3530 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003531 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003532
John McCall94c3b562010-08-18 09:41:07 +00003533 /// Handle all the types we haven't given a more specific
3534 /// implementation for above.
3535 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3536 // Every other kind of type that we haven't called out already
3537 // that has an inner type is either (1) sugar or (2) contains that
3538 // inner type in some way as a subobject.
3539 if (TypeLoc Next = TL.getNextTypeLoc())
3540 return Visit(Next, Sel);
3541
3542 // If there's no inner type and we're in a permissive context,
3543 // don't diagnose.
3544 if (Sel == Sema::AbstractNone) return;
3545
3546 // Check whether the type matches the abstract type.
3547 QualType T = TL.getType();
3548 if (T->isArrayType()) {
3549 Sel = Sema::AbstractArrayType;
3550 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003551 }
John McCall94c3b562010-08-18 09:41:07 +00003552 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3553 if (CT != Info.AbstractType) return;
3554
3555 // It matched; do some magic.
3556 if (Sel == Sema::AbstractArrayType) {
3557 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3558 << T << TL.getSourceRange();
3559 } else {
3560 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3561 << Sel << T << TL.getSourceRange();
3562 }
3563 Info.DiagnoseAbstractType();
3564 }
3565};
3566
3567void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3568 Sema::AbstractDiagSelID Sel) {
3569 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3570}
3571
3572}
3573
3574/// Check for invalid uses of an abstract type in a method declaration.
3575static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3576 CXXMethodDecl *MD) {
3577 // No need to do the check on definitions, which require that
3578 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003579 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003580 return;
3581
3582 // For safety's sake, just ignore it if we don't have type source
3583 // information. This should never happen for non-implicit methods,
3584 // but...
3585 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3586 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3587}
3588
3589/// Check for invalid uses of an abstract type within a class definition.
3590static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3591 CXXRecordDecl *RD) {
3592 for (CXXRecordDecl::decl_iterator
3593 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3594 Decl *D = *I;
3595 if (D->isImplicit()) continue;
3596
3597 // Methods and method templates.
3598 if (isa<CXXMethodDecl>(D)) {
3599 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3600 } else if (isa<FunctionTemplateDecl>(D)) {
3601 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3602 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3603
3604 // Fields and static variables.
3605 } else if (isa<FieldDecl>(D)) {
3606 FieldDecl *FD = cast<FieldDecl>(D);
3607 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3608 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3609 } else if (isa<VarDecl>(D)) {
3610 VarDecl *VD = cast<VarDecl>(D);
3611 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3612 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3613
3614 // Nested classes and class templates.
3615 } else if (isa<CXXRecordDecl>(D)) {
3616 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3617 } else if (isa<ClassTemplateDecl>(D)) {
3618 CheckAbstractClassUsage(Info,
3619 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3620 }
3621 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003622}
3623
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003624/// \brief Perform semantic checks on a class definition that has been
3625/// completing, introducing implicitly-declared members, checking for
3626/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003627void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003628 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003629 return;
3630
John McCall94c3b562010-08-18 09:41:07 +00003631 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3632 AbstractUsageInfo Info(*this, Record);
3633 CheckAbstractClassUsage(Info, Record);
3634 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003635
3636 // If this is not an aggregate type and has no user-declared constructor,
3637 // complain about any non-static data members of reference or const scalar
3638 // type, since they will never get initializers.
3639 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3640 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3641 bool Complained = false;
3642 for (RecordDecl::field_iterator F = Record->field_begin(),
3643 FEnd = Record->field_end();
3644 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003645 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003646 continue;
3647
Douglas Gregor325e5932010-04-15 00:00:53 +00003648 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003649 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003650 if (!Complained) {
3651 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3652 << Record->getTagKind() << Record;
3653 Complained = true;
3654 }
3655
3656 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3657 << F->getType()->isReferenceType()
3658 << F->getDeclName();
3659 }
3660 }
3661 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003662
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003663 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003664 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003665
3666 if (Record->getIdentifier()) {
3667 // C++ [class.mem]p13:
3668 // If T is the name of a class, then each of the following shall have a
3669 // name different from T:
3670 // - every member of every anonymous union that is a member of class T.
3671 //
3672 // C++ [class.mem]p14:
3673 // In addition, if class T has a user-declared constructor (12.1), every
3674 // non-static data member of class T shall have a name different from T.
3675 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003676 R.first != R.second; ++R.first) {
3677 NamedDecl *D = *R.first;
3678 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3679 isa<IndirectFieldDecl>(D)) {
3680 Diag(D->getLocation(), diag::err_member_name_of_class)
3681 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003682 break;
3683 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003684 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003685 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003686
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003687 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003688 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003689 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003690 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003691 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3692 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3693 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003694
3695 // See if a method overloads virtual methods in a base
3696 /// class without overriding any.
3697 if (!Record->isDependentType()) {
3698 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3699 MEnd = Record->method_end();
3700 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003701 if (!(*M)->isStatic())
3702 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003703 }
3704 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003705
Richard Smith9f569cc2011-10-01 02:31:28 +00003706 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3707 // function that is not a constructor declares that member function to be
3708 // const. [...] The class of which that function is a member shall be
3709 // a literal type.
3710 //
3711 // It's fine to diagnose constructors here too: such constructors cannot
3712 // produce a constant expression, so are ill-formed (no diagnostic required).
3713 //
3714 // If the class has virtual bases, any constexpr members will already have
3715 // been diagnosed by the checks performed on the member declaration, so
3716 // suppress this (less useful) diagnostic.
3717 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3718 !Record->isLiteral() && !Record->getNumVBases()) {
3719 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3720 MEnd = Record->method_end();
3721 M != MEnd; ++M) {
Eli Friedman9ec0ef32012-01-13 02:31:53 +00003722 if (M->isConstexpr() && M->isInstance()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003723 switch (Record->getTemplateSpecializationKind()) {
3724 case TSK_ImplicitInstantiation:
3725 case TSK_ExplicitInstantiationDeclaration:
3726 case TSK_ExplicitInstantiationDefinition:
3727 // If a template instantiates to a non-literal type, but its members
3728 // instantiate to constexpr functions, the template is technically
3729 // ill-formed, but we allow it for sanity. Such members are treated as
3730 // non-constexpr.
3731 (*M)->setConstexpr(false);
3732 continue;
3733
3734 case TSK_Undeclared:
3735 case TSK_ExplicitSpecialization:
3736 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3737 PDiag(diag::err_constexpr_method_non_literal));
3738 break;
3739 }
3740
3741 // Only produce one error per class.
3742 break;
3743 }
3744 }
3745 }
3746
Sebastian Redlf677ea32011-02-05 19:23:19 +00003747 // Declare inherited constructors. We do this eagerly here because:
3748 // - The standard requires an eager diagnostic for conflicting inherited
3749 // constructors from different classes.
3750 // - The lazy declaration of the other implicit constructors is so as to not
3751 // waste space and performance on classes that are not meant to be
3752 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3753 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003754 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003755
Sean Hunteb88ae52011-05-23 21:07:59 +00003756 if (!Record->isDependentType())
3757 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003758}
3759
3760void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003761 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3762 ME = Record->method_end();
3763 MI != ME; ++MI) {
3764 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3765 switch (getSpecialMember(*MI)) {
3766 case CXXDefaultConstructor:
3767 CheckExplicitlyDefaultedDefaultConstructor(
3768 cast<CXXConstructorDecl>(*MI));
3769 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003770
Sean Huntcb45a0f2011-05-12 22:46:25 +00003771 case CXXDestructor:
3772 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3773 break;
3774
3775 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003776 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3777 break;
3778
Sean Huntcb45a0f2011-05-12 22:46:25 +00003779 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003780 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003781 break;
3782
Sean Hunt82713172011-05-25 23:16:36 +00003783 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003784 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003785 break;
3786
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003787 case CXXMoveAssignment:
3788 CheckExplicitlyDefaultedMoveAssignment(*MI);
3789 break;
3790
3791 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003792 llvm_unreachable("non-special member explicitly defaulted!");
3793 }
Sean Hunt001cad92011-05-10 00:49:42 +00003794 }
3795 }
3796
Sean Hunt001cad92011-05-10 00:49:42 +00003797}
3798
3799void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3800 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3801
3802 // Whether this was the first-declared instance of the constructor.
3803 // This affects whether we implicitly add an exception spec (and, eventually,
3804 // constexpr). It is also ill-formed to explicitly default a constructor such
3805 // that it would be deleted. (C++0x [decl.fct.def.default])
3806 bool First = CD == CD->getCanonicalDecl();
3807
Sean Hunt49634cf2011-05-13 06:10:58 +00003808 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003809 if (CD->getNumParams() != 0) {
3810 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3811 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003812 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003813 }
3814
3815 ImplicitExceptionSpecification Spec
3816 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3817 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003818 if (EPI.ExceptionSpecType == EST_Delayed) {
3819 // Exception specification depends on some deferred part of the class. We'll
3820 // try again when the class's definition has been fully processed.
3821 return;
3822 }
Sean Hunt001cad92011-05-10 00:49:42 +00003823 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3824 *ExceptionType = Context.getFunctionType(
3825 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3826
Richard Smith61802452011-12-22 02:22:31 +00003827 // C++11 [dcl.fct.def.default]p2:
3828 // An explicitly-defaulted function may be declared constexpr only if it
3829 // would have been implicitly declared as constexpr,
3830 if (CD->isConstexpr()) {
3831 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3832 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3833 << CXXDefaultConstructor;
3834 HadError = true;
3835 }
3836 }
3837 // and may have an explicit exception-specification only if it is compatible
3838 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003839 if (CtorType->hasExceptionSpec()) {
3840 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003841 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003842 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003843 PDiag(),
3844 ExceptionType, SourceLocation(),
3845 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003846 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003847 }
Richard Smith61802452011-12-22 02:22:31 +00003848 }
3849
3850 // If a function is explicitly defaulted on its first declaration,
3851 if (First) {
3852 // -- it is implicitly considered to be constexpr if the implicit
3853 // definition would be,
3854 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3855
3856 // -- it is implicitly considered to have the same
3857 // exception-specification as if it had been implicitly declared
3858 //
3859 // FIXME: a compatible, but different, explicit exception specification
3860 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003861 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003862 }
Sean Huntca46d132011-05-12 03:51:48 +00003863
Sean Hunt49634cf2011-05-13 06:10:58 +00003864 if (HadError) {
3865 CD->setInvalidDecl();
3866 return;
3867 }
3868
Sean Hunte16da072011-10-10 06:18:57 +00003869 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003870 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003871 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003872 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003873 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003874 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003875 CD->setInvalidDecl();
3876 }
3877 }
3878}
3879
3880void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3881 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3882
3883 // Whether this was the first-declared instance of the constructor.
3884 bool First = CD == CD->getCanonicalDecl();
3885
3886 bool HadError = false;
3887 if (CD->getNumParams() != 1) {
3888 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3889 << CD->getSourceRange();
3890 HadError = true;
3891 }
3892
3893 ImplicitExceptionSpecification Spec(Context);
3894 bool Const;
3895 llvm::tie(Spec, Const) =
3896 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3897
3898 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3899 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3900 *ExceptionType = Context.getFunctionType(
3901 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3902
3903 // Check for parameter type matching.
3904 // This is a copy ctor so we know it's a cv-qualified reference to T.
3905 QualType ArgType = CtorType->getArgType(0);
3906 if (ArgType->getPointeeType().isVolatileQualified()) {
3907 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3908 HadError = true;
3909 }
3910 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3911 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3912 HadError = true;
3913 }
3914
Richard Smith61802452011-12-22 02:22:31 +00003915 // C++11 [dcl.fct.def.default]p2:
3916 // An explicitly-defaulted function may be declared constexpr only if it
3917 // would have been implicitly declared as constexpr,
3918 if (CD->isConstexpr()) {
3919 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3920 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3921 << CXXCopyConstructor;
3922 HadError = true;
3923 }
3924 }
3925 // and may have an explicit exception-specification only if it is compatible
3926 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003927 if (CtorType->hasExceptionSpec()) {
3928 if (CheckEquivalentExceptionSpec(
3929 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003930 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003931 PDiag(),
3932 ExceptionType, SourceLocation(),
3933 CtorType, CD->getLocation())) {
3934 HadError = true;
3935 }
Richard Smith61802452011-12-22 02:22:31 +00003936 }
3937
3938 // If a function is explicitly defaulted on its first declaration,
3939 if (First) {
3940 // -- it is implicitly considered to be constexpr if the implicit
3941 // definition would be,
3942 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3943
3944 // -- it is implicitly considered to have the same
3945 // exception-specification as if it had been implicitly declared, and
3946 //
3947 // FIXME: a compatible, but different, explicit exception specification
3948 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003949 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003950
3951 // -- [...] it shall have the same parameter type as if it had been
3952 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003953 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3954 }
3955
3956 if (HadError) {
3957 CD->setInvalidDecl();
3958 return;
3959 }
3960
Sean Huntc32d6842011-10-11 04:55:36 +00003961 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003962 if (First) {
3963 CD->setDeletedAsWritten();
3964 } else {
3965 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003966 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003967 CD->setInvalidDecl();
3968 }
Sean Huntca46d132011-05-12 03:51:48 +00003969 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003970}
Sean Hunt001cad92011-05-10 00:49:42 +00003971
Sean Hunt2b188082011-05-14 05:23:28 +00003972void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3973 assert(MD->isExplicitlyDefaulted());
3974
3975 // Whether this was the first-declared instance of the operator
3976 bool First = MD == MD->getCanonicalDecl();
3977
3978 bool HadError = false;
3979 if (MD->getNumParams() != 1) {
3980 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3981 << MD->getSourceRange();
3982 HadError = true;
3983 }
3984
3985 QualType ReturnType =
3986 MD->getType()->getAs<FunctionType>()->getResultType();
3987 if (!ReturnType->isLValueReferenceType() ||
3988 !Context.hasSameType(
3989 Context.getCanonicalType(ReturnType->getPointeeType()),
3990 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3991 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3992 HadError = true;
3993 }
3994
3995 ImplicitExceptionSpecification Spec(Context);
3996 bool Const;
3997 llvm::tie(Spec, Const) =
3998 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3999
4000 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4001 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4002 *ExceptionType = Context.getFunctionType(
4003 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4004
Sean Hunt2b188082011-05-14 05:23:28 +00004005 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004006 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004007 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004008 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004009 } else {
4010 if (ArgType->getPointeeType().isVolatileQualified()) {
4011 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4012 HadError = true;
4013 }
4014 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4015 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4016 HadError = true;
4017 }
Sean Hunt2b188082011-05-14 05:23:28 +00004018 }
Sean Huntbe631222011-05-17 20:44:43 +00004019
Sean Hunt2b188082011-05-14 05:23:28 +00004020 if (OperType->getTypeQuals()) {
4021 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4022 HadError = true;
4023 }
4024
4025 if (OperType->hasExceptionSpec()) {
4026 if (CheckEquivalentExceptionSpec(
4027 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004028 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004029 PDiag(),
4030 ExceptionType, SourceLocation(),
4031 OperType, MD->getLocation())) {
4032 HadError = true;
4033 }
Richard Smith61802452011-12-22 02:22:31 +00004034 }
4035 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004036 // We set the declaration to have the computed exception spec here.
4037 // We duplicate the one parameter type.
4038 EPI.RefQualifier = OperType->getRefQualifier();
4039 EPI.ExtInfo = OperType->getExtInfo();
4040 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4041 }
4042
4043 if (HadError) {
4044 MD->setInvalidDecl();
4045 return;
4046 }
4047
4048 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4049 if (First) {
4050 MD->setDeletedAsWritten();
4051 } else {
4052 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004053 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004054 MD->setInvalidDecl();
4055 }
4056 }
4057}
4058
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004059void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4060 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4061
4062 // Whether this was the first-declared instance of the constructor.
4063 bool First = CD == CD->getCanonicalDecl();
4064
4065 bool HadError = false;
4066 if (CD->getNumParams() != 1) {
4067 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4068 << CD->getSourceRange();
4069 HadError = true;
4070 }
4071
4072 ImplicitExceptionSpecification Spec(
4073 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4074
4075 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4076 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4077 *ExceptionType = Context.getFunctionType(
4078 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4079
4080 // Check for parameter type matching.
4081 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4082 QualType ArgType = CtorType->getArgType(0);
4083 if (ArgType->getPointeeType().isVolatileQualified()) {
4084 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4085 HadError = true;
4086 }
4087 if (ArgType->getPointeeType().isConstQualified()) {
4088 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4089 HadError = true;
4090 }
4091
Richard Smith61802452011-12-22 02:22:31 +00004092 // C++11 [dcl.fct.def.default]p2:
4093 // An explicitly-defaulted function may be declared constexpr only if it
4094 // would have been implicitly declared as constexpr,
4095 if (CD->isConstexpr()) {
4096 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4097 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4098 << CXXMoveConstructor;
4099 HadError = true;
4100 }
4101 }
4102 // and may have an explicit exception-specification only if it is compatible
4103 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004104 if (CtorType->hasExceptionSpec()) {
4105 if (CheckEquivalentExceptionSpec(
4106 PDiag(diag::err_incorrect_defaulted_exception_spec)
4107 << CXXMoveConstructor,
4108 PDiag(),
4109 ExceptionType, SourceLocation(),
4110 CtorType, CD->getLocation())) {
4111 HadError = true;
4112 }
Richard Smith61802452011-12-22 02:22:31 +00004113 }
4114
4115 // If a function is explicitly defaulted on its first declaration,
4116 if (First) {
4117 // -- it is implicitly considered to be constexpr if the implicit
4118 // definition would be,
4119 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4120
4121 // -- it is implicitly considered to have the same
4122 // exception-specification as if it had been implicitly declared, and
4123 //
4124 // FIXME: a compatible, but different, explicit exception specification
4125 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004126 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004127
4128 // -- [...] it shall have the same parameter type as if it had been
4129 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004130 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4131 }
4132
4133 if (HadError) {
4134 CD->setInvalidDecl();
4135 return;
4136 }
4137
Sean Hunt769bb2d2011-10-11 06:43:29 +00004138 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004139 if (First) {
4140 CD->setDeletedAsWritten();
4141 } else {
4142 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4143 << CXXMoveConstructor;
4144 CD->setInvalidDecl();
4145 }
4146 }
4147}
4148
4149void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4150 assert(MD->isExplicitlyDefaulted());
4151
4152 // Whether this was the first-declared instance of the operator
4153 bool First = MD == MD->getCanonicalDecl();
4154
4155 bool HadError = false;
4156 if (MD->getNumParams() != 1) {
4157 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4158 << MD->getSourceRange();
4159 HadError = true;
4160 }
4161
4162 QualType ReturnType =
4163 MD->getType()->getAs<FunctionType>()->getResultType();
4164 if (!ReturnType->isLValueReferenceType() ||
4165 !Context.hasSameType(
4166 Context.getCanonicalType(ReturnType->getPointeeType()),
4167 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4168 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4169 HadError = true;
4170 }
4171
4172 ImplicitExceptionSpecification Spec(
4173 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4174
4175 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4176 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4177 *ExceptionType = Context.getFunctionType(
4178 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4179
4180 QualType ArgType = OperType->getArgType(0);
4181 if (!ArgType->isRValueReferenceType()) {
4182 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4183 HadError = true;
4184 } else {
4185 if (ArgType->getPointeeType().isVolatileQualified()) {
4186 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4187 HadError = true;
4188 }
4189 if (ArgType->getPointeeType().isConstQualified()) {
4190 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4191 HadError = true;
4192 }
4193 }
4194
4195 if (OperType->getTypeQuals()) {
4196 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4197 HadError = true;
4198 }
4199
4200 if (OperType->hasExceptionSpec()) {
4201 if (CheckEquivalentExceptionSpec(
4202 PDiag(diag::err_incorrect_defaulted_exception_spec)
4203 << CXXMoveAssignment,
4204 PDiag(),
4205 ExceptionType, SourceLocation(),
4206 OperType, MD->getLocation())) {
4207 HadError = true;
4208 }
Richard Smith61802452011-12-22 02:22:31 +00004209 }
4210 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004211 // We set the declaration to have the computed exception spec here.
4212 // We duplicate the one parameter type.
4213 EPI.RefQualifier = OperType->getRefQualifier();
4214 EPI.ExtInfo = OperType->getExtInfo();
4215 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4216 }
4217
4218 if (HadError) {
4219 MD->setInvalidDecl();
4220 return;
4221 }
4222
4223 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4224 if (First) {
4225 MD->setDeletedAsWritten();
4226 } else {
4227 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4228 << CXXMoveAssignment;
4229 MD->setInvalidDecl();
4230 }
4231 }
4232}
4233
Sean Huntcb45a0f2011-05-12 22:46:25 +00004234void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4235 assert(DD->isExplicitlyDefaulted());
4236
4237 // Whether this was the first-declared instance of the destructor.
4238 bool First = DD == DD->getCanonicalDecl();
4239
4240 ImplicitExceptionSpecification Spec
4241 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4242 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4243 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4244 *ExceptionType = Context.getFunctionType(
4245 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4246
4247 if (DtorType->hasExceptionSpec()) {
4248 if (CheckEquivalentExceptionSpec(
4249 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004250 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004251 PDiag(),
4252 ExceptionType, SourceLocation(),
4253 DtorType, DD->getLocation())) {
4254 DD->setInvalidDecl();
4255 return;
4256 }
Richard Smith61802452011-12-22 02:22:31 +00004257 }
4258 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004259 // We set the declaration to have the computed exception spec here.
4260 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004261 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004262 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4263 }
4264
4265 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004266 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004267 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004268 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004269 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004270 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004271 DD->setInvalidDecl();
4272 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004273 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004274}
4275
Sean Hunte16da072011-10-10 06:18:57 +00004276/// This function implements the following C++0x paragraphs:
4277/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004278/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004279bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4280 assert(!MD->isInvalidDecl());
4281 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004282 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004283 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004284 return false;
4285
Sean Hunte16da072011-10-10 06:18:57 +00004286 bool IsUnion = RD->isUnion();
4287 bool IsConstructor = false;
4288 bool IsAssignment = false;
4289 bool IsMove = false;
4290
4291 bool ConstArg = false;
4292
4293 switch (CSM) {
4294 case CXXDefaultConstructor:
4295 IsConstructor = true;
4296 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004297 case CXXCopyConstructor:
4298 IsConstructor = true;
4299 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4300 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004301 case CXXMoveConstructor:
4302 IsConstructor = true;
4303 IsMove = true;
4304 break;
Sean Hunte16da072011-10-10 06:18:57 +00004305 default:
4306 llvm_unreachable("function only currently implemented for default ctors");
4307 }
4308
4309 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004310
Sean Huntc32d6842011-10-11 04:55:36 +00004311 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004312 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004313
Sean Huntcdee3fe2011-05-11 22:34:38 +00004314 bool AllConst = true;
4315
Sean Huntcdee3fe2011-05-11 22:34:38 +00004316 // We do this because we should never actually use an anonymous
4317 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004318 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004319 return false;
4320
4321 // FIXME: We should put some diagnostic logic right into this function.
4322
Sean Huntcdee3fe2011-05-11 22:34:38 +00004323 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4324 BE = RD->bases_end();
4325 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004326 // We'll handle this one later
4327 if (BI->isVirtual())
4328 continue;
4329
Sean Huntcdee3fe2011-05-11 22:34:38 +00004330 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4331 assert(BaseDecl && "base isn't a CXXRecordDecl");
4332
Sean Hunte16da072011-10-10 06:18:57 +00004333 // Unless we have an assignment operator, the base's destructor must
4334 // be accessible and not deleted.
4335 if (!IsAssignment) {
4336 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4337 if (BaseDtor->isDeleted())
4338 return true;
4339 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4340 AR_accessible)
4341 return true;
4342 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004343
Sean Hunte16da072011-10-10 06:18:57 +00004344 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004345 // unique, accessible, non-deleted function. If we are doing
4346 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004347 if (CSM != CXXDestructor) {
4348 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004349 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004350 false);
4351 if (!SMOR->hasSuccess())
4352 return true;
4353 CXXMethodDecl *BaseMember = SMOR->getMethod();
4354 if (IsConstructor) {
4355 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4356 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4357 PDiag()) != AR_accessible)
4358 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004359
4360 // For a move operation, the corresponding operation must actually
4361 // be a move operation (and not a copy selected by overload
4362 // resolution) unless we are working on a trivially copyable class.
4363 if (IsMove && !BaseCtor->isMoveConstructor() &&
4364 !BaseDecl->isTriviallyCopyable())
4365 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004366 }
4367 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004368 }
4369
4370 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4371 BE = RD->vbases_end();
4372 BI != BE; ++BI) {
4373 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4374 assert(BaseDecl && "base isn't a CXXRecordDecl");
4375
Sean Hunte16da072011-10-10 06:18:57 +00004376 // Unless we have an assignment operator, the base's destructor must
4377 // be accessible and not deleted.
4378 if (!IsAssignment) {
4379 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4380 if (BaseDtor->isDeleted())
4381 return true;
4382 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4383 AR_accessible)
4384 return true;
4385 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004386
Sean Hunte16da072011-10-10 06:18:57 +00004387 // Finding the corresponding member in the base should lead to a
4388 // unique, accessible, non-deleted function.
4389 if (CSM != CXXDestructor) {
4390 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004391 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004392 false);
4393 if (!SMOR->hasSuccess())
4394 return true;
4395 CXXMethodDecl *BaseMember = SMOR->getMethod();
4396 if (IsConstructor) {
4397 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4398 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4399 PDiag()) != AR_accessible)
4400 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004401
4402 // For a move operation, the corresponding operation must actually
4403 // be a move operation (and not a copy selected by overload
4404 // resolution) unless we are working on a trivially copyable class.
4405 if (IsMove && !BaseCtor->isMoveConstructor() &&
4406 !BaseDecl->isTriviallyCopyable())
4407 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004408 }
4409 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004410 }
4411
4412 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4413 FE = RD->field_end();
4414 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004415 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004416 continue;
4417
Sean Huntcdee3fe2011-05-11 22:34:38 +00004418 QualType FieldType = Context.getBaseElementType(FI->getType());
4419 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004420
Sean Hunte16da072011-10-10 06:18:57 +00004421 // For a default constructor, all references must be initialized in-class
4422 // and, if a union, it must have a non-const member.
4423 if (CSM == CXXDefaultConstructor) {
4424 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4425 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004426
Sean Hunte16da072011-10-10 06:18:57 +00004427 if (IsUnion && !FieldType.isConstQualified())
4428 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004429 // For a copy constructor, data members must not be of rvalue reference
4430 // type.
4431 } else if (CSM == CXXCopyConstructor) {
4432 if (FieldType->isRValueReferenceType())
4433 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004434 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004435
4436 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004437 // For a default constructor, a const member must have a user-provided
4438 // default constructor or else be explicitly initialized.
4439 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004440 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004441 !FieldRecord->hasUserProvidedDefaultConstructor())
4442 return true;
4443
Sean Huntc32d6842011-10-11 04:55:36 +00004444 // Some additional restrictions exist on the variant members.
4445 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004446 FieldRecord->isAnonymousStructOrUnion()) {
4447 // We're okay to reuse AllConst here since we only care about the
4448 // value otherwise if we're in a union.
4449 AllConst = true;
4450
4451 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4452 UE = FieldRecord->field_end();
4453 UI != UE; ++UI) {
4454 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4455 CXXRecordDecl *UnionFieldRecord =
4456 UnionFieldType->getAsCXXRecordDecl();
4457
4458 if (!UnionFieldType.isConstQualified())
4459 AllConst = false;
4460
Sean Huntc32d6842011-10-11 04:55:36 +00004461 if (UnionFieldRecord) {
4462 // FIXME: Checking for accessibility and validity of this
4463 // destructor is technically going beyond the
4464 // standard, but this is believed to be a defect.
4465 if (!IsAssignment) {
4466 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4467 if (FieldDtor->isDeleted())
4468 return true;
4469 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4470 AR_accessible)
4471 return true;
4472 if (!FieldDtor->isTrivial())
4473 return true;
4474 }
4475
4476 if (CSM != CXXDestructor) {
4477 SpecialMemberOverloadResult *SMOR =
4478 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004479 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004480 // FIXME: Checking for accessibility and validity of this
4481 // corresponding member is technically going beyond the
4482 // standard, but this is believed to be a defect.
4483 if (!SMOR->hasSuccess())
4484 return true;
4485
4486 CXXMethodDecl *FieldMember = SMOR->getMethod();
4487 // A member of a union must have a trivial corresponding
4488 // constructor.
4489 if (!FieldMember->isTrivial())
4490 return true;
4491
4492 if (IsConstructor) {
4493 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4494 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4495 PDiag()) != AR_accessible)
4496 return true;
4497 }
4498 }
4499 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004500 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004501
Sean Huntc32d6842011-10-11 04:55:36 +00004502 // At least one member in each anonymous union must be non-const
4503 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004504 return true;
4505
4506 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004507 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004508 continue;
4509 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004510
Sean Huntc32d6842011-10-11 04:55:36 +00004511 // Unless we're doing assignment, the field's destructor must be
4512 // accessible and not deleted.
4513 if (!IsAssignment) {
4514 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4515 if (FieldDtor->isDeleted())
4516 return true;
4517 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4518 AR_accessible)
4519 return true;
4520 }
4521
Sean Hunte16da072011-10-10 06:18:57 +00004522 // Check that the corresponding member of the field is accessible,
4523 // unique, and non-deleted. We don't do this if it has an explicit
4524 // initialization when default-constructing.
4525 if (CSM != CXXDestructor &&
4526 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4527 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004528 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004529 false);
4530 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004531 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004532
4533 CXXMethodDecl *FieldMember = SMOR->getMethod();
4534 if (IsConstructor) {
4535 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4536 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4537 PDiag()) != AR_accessible)
4538 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004539
4540 // For a move operation, the corresponding operation must actually
4541 // be a move operation (and not a copy selected by overload
4542 // resolution) unless we are working on a trivially copyable class.
4543 if (IsMove && !FieldCtor->isMoveConstructor() &&
4544 !FieldRecord->isTriviallyCopyable())
4545 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004546 }
4547
4548 // We need the corresponding member of a union to be trivial so that
4549 // we can safely copy them all simultaneously.
4550 // FIXME: Note that performing the check here (where we rely on the lack
4551 // of an in-class initializer) is technically ill-formed. However, this
4552 // seems most obviously to be a bug in the standard.
4553 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004554 return true;
4555 }
Sean Hunte16da072011-10-10 06:18:57 +00004556 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4557 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4558 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004559 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004560 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004561 }
4562
Sean Hunte16da072011-10-10 06:18:57 +00004563 // We can't have all const members in a union when default-constructing,
4564 // or else they're all nonsensical garbage values that can't be changed.
4565 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004566 return true;
4567
4568 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004569}
4570
Sean Hunt7f410192011-05-14 05:23:24 +00004571bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4572 CXXRecordDecl *RD = MD->getParent();
4573 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004574 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004575 return false;
4576
Sean Hunt71a682f2011-05-18 03:41:58 +00004577 SourceLocation Loc = MD->getLocation();
4578
Sean Hunt7f410192011-05-14 05:23:24 +00004579 // Do access control from the constructor
4580 ContextRAII MethodContext(*this, MD);
4581
4582 bool Union = RD->isUnion();
4583
Sean Hunt661c67a2011-06-21 23:42:56 +00004584 unsigned ArgQuals =
4585 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4586 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004587
4588 // We do this because we should never actually use an anonymous
4589 // union's constructor.
4590 if (Union && RD->isAnonymousStructOrUnion())
4591 return false;
4592
Sean Hunt7f410192011-05-14 05:23:24 +00004593 // FIXME: We should put some diagnostic logic right into this function.
4594
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004595 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004596 // A defaulted [copy] assignment operator for class X is defined as deleted
4597 // if X has:
4598
4599 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4600 BE = RD->bases_end();
4601 BI != BE; ++BI) {
4602 // We'll handle this one later
4603 if (BI->isVirtual())
4604 continue;
4605
4606 QualType BaseType = BI->getType();
4607 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4608 assert(BaseDecl && "base isn't a CXXRecordDecl");
4609
4610 // -- a [direct base class] B that cannot be [copied] because overload
4611 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004612 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004613 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004614 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4615 0);
4616 if (!CopyOper || CopyOper->isDeleted())
4617 return true;
4618 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004619 return true;
4620 }
4621
4622 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4623 BE = RD->vbases_end();
4624 BI != BE; ++BI) {
4625 QualType BaseType = BI->getType();
4626 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4627 assert(BaseDecl && "base isn't a CXXRecordDecl");
4628
Sean Hunt7f410192011-05-14 05:23:24 +00004629 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004630 // resolution, as applied to B's [copy] assignment operator, results in
4631 // an ambiguity or a function that is deleted or inaccessible from the
4632 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004633 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4634 0);
4635 if (!CopyOper || CopyOper->isDeleted())
4636 return true;
4637 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004638 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004639 }
4640
4641 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4642 FE = RD->field_end();
4643 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004644 if (FI->isUnnamedBitfield())
4645 continue;
4646
Sean Hunt7f410192011-05-14 05:23:24 +00004647 QualType FieldType = Context.getBaseElementType(FI->getType());
4648
4649 // -- a non-static data member of reference type
4650 if (FieldType->isReferenceType())
4651 return true;
4652
4653 // -- a non-static data member of const non-class type (or array thereof)
4654 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4655 return true;
4656
4657 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4658
4659 if (FieldRecord) {
4660 // This is an anonymous union
4661 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4662 // Anonymous unions inside unions do not variant members create
4663 if (!Union) {
4664 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4665 UE = FieldRecord->field_end();
4666 UI != UE; ++UI) {
4667 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4668 CXXRecordDecl *UnionFieldRecord =
4669 UnionFieldType->getAsCXXRecordDecl();
4670
4671 // -- a variant member with a non-trivial [copy] assignment operator
4672 // and X is a union-like class
4673 if (UnionFieldRecord &&
4674 !UnionFieldRecord->hasTrivialCopyAssignment())
4675 return true;
4676 }
4677 }
4678
4679 // Don't try to initalize an anonymous union
4680 continue;
4681 // -- a variant member with a non-trivial [copy] assignment operator
4682 // and X is a union-like class
4683 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4684 return true;
4685 }
Sean Hunt7f410192011-05-14 05:23:24 +00004686
Sean Hunt661c67a2011-06-21 23:42:56 +00004687 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4688 false, 0);
4689 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004690 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004691 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004692 return true;
4693 }
4694 }
4695
4696 return false;
4697}
4698
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004699bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4700 CXXRecordDecl *RD = MD->getParent();
4701 assert(!RD->isDependentType() && "do deletion after instantiation");
4702 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4703 return false;
4704
4705 SourceLocation Loc = MD->getLocation();
4706
4707 // Do access control from the constructor
4708 ContextRAII MethodContext(*this, MD);
4709
4710 bool Union = RD->isUnion();
4711
4712 // We do this because we should never actually use an anonymous
4713 // union's constructor.
4714 if (Union && RD->isAnonymousStructOrUnion())
4715 return false;
4716
4717 // C++0x [class.copy]/20
4718 // A defaulted [move] assignment operator for class X is defined as deleted
4719 // if X has:
4720
4721 // -- for the move constructor, [...] any direct or indirect virtual base
4722 // class.
4723 if (RD->getNumVBases() != 0)
4724 return true;
4725
4726 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4727 BE = RD->bases_end();
4728 BI != BE; ++BI) {
4729
4730 QualType BaseType = BI->getType();
4731 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4732 assert(BaseDecl && "base isn't a CXXRecordDecl");
4733
4734 // -- a [direct base class] B that cannot be [moved] because overload
4735 // resolution, as applied to B's [move] assignment operator, results in
4736 // an ambiguity or a function that is deleted or inaccessible from the
4737 // assignment operator
4738 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4739 if (!MoveOper || MoveOper->isDeleted())
4740 return true;
4741 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4742 return true;
4743
4744 // -- for the move assignment operator, a [direct base class] with a type
4745 // that does not have a move assignment operator and is not trivially
4746 // copyable.
4747 if (!MoveOper->isMoveAssignmentOperator() &&
4748 !BaseDecl->isTriviallyCopyable())
4749 return true;
4750 }
4751
4752 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4753 FE = RD->field_end();
4754 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004755 if (FI->isUnnamedBitfield())
4756 continue;
4757
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004758 QualType FieldType = Context.getBaseElementType(FI->getType());
4759
4760 // -- a non-static data member of reference type
4761 if (FieldType->isReferenceType())
4762 return true;
4763
4764 // -- a non-static data member of const non-class type (or array thereof)
4765 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4766 return true;
4767
4768 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4769
4770 if (FieldRecord) {
4771 // This is an anonymous union
4772 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4773 // Anonymous unions inside unions do not variant members create
4774 if (!Union) {
4775 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4776 UE = FieldRecord->field_end();
4777 UI != UE; ++UI) {
4778 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4779 CXXRecordDecl *UnionFieldRecord =
4780 UnionFieldType->getAsCXXRecordDecl();
4781
4782 // -- a variant member with a non-trivial [move] assignment operator
4783 // and X is a union-like class
4784 if (UnionFieldRecord &&
4785 !UnionFieldRecord->hasTrivialMoveAssignment())
4786 return true;
4787 }
4788 }
4789
4790 // Don't try to initalize an anonymous union
4791 continue;
4792 // -- a variant member with a non-trivial [move] assignment operator
4793 // and X is a union-like class
4794 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4795 return true;
4796 }
4797
4798 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4799 if (!MoveOper || MoveOper->isDeleted())
4800 return true;
4801 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4802 return true;
4803
4804 // -- for the move assignment operator, a [non-static data member] with a
4805 // type that does not have a move assignment operator and is not
4806 // trivially copyable.
4807 if (!MoveOper->isMoveAssignmentOperator() &&
4808 !FieldRecord->isTriviallyCopyable())
4809 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004810 }
Sean Hunt7f410192011-05-14 05:23:24 +00004811 }
4812
4813 return false;
4814}
4815
Sean Huntcb45a0f2011-05-12 22:46:25 +00004816bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4817 CXXRecordDecl *RD = DD->getParent();
4818 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004819 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004820 return false;
4821
Sean Hunt71a682f2011-05-18 03:41:58 +00004822 SourceLocation Loc = DD->getLocation();
4823
Sean Huntcb45a0f2011-05-12 22:46:25 +00004824 // Do access control from the destructor
4825 ContextRAII CtorContext(*this, DD);
4826
4827 bool Union = RD->isUnion();
4828
Sean Hunt49634cf2011-05-13 06:10:58 +00004829 // We do this because we should never actually use an anonymous
4830 // union's destructor.
4831 if (Union && RD->isAnonymousStructOrUnion())
4832 return false;
4833
Sean Huntcb45a0f2011-05-12 22:46:25 +00004834 // C++0x [class.dtor]p5
4835 // A defaulted destructor for a class X is defined as deleted if:
4836 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4837 BE = RD->bases_end();
4838 BI != BE; ++BI) {
4839 // We'll handle this one later
4840 if (BI->isVirtual())
4841 continue;
4842
4843 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4844 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4845 assert(BaseDtor && "base has no destructor");
4846
4847 // -- any direct or virtual base class has a deleted destructor or
4848 // a destructor that is inaccessible from the defaulted destructor
4849 if (BaseDtor->isDeleted())
4850 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004851 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004852 AR_accessible)
4853 return true;
4854 }
4855
4856 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4857 BE = RD->vbases_end();
4858 BI != BE; ++BI) {
4859 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4860 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4861 assert(BaseDtor && "base has no destructor");
4862
4863 // -- any direct or virtual base class has a deleted destructor or
4864 // a destructor that is inaccessible from the defaulted destructor
4865 if (BaseDtor->isDeleted())
4866 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004867 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004868 AR_accessible)
4869 return true;
4870 }
4871
4872 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4873 FE = RD->field_end();
4874 FI != FE; ++FI) {
4875 QualType FieldType = Context.getBaseElementType(FI->getType());
4876 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4877 if (FieldRecord) {
4878 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4879 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4880 UE = FieldRecord->field_end();
4881 UI != UE; ++UI) {
4882 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4883 CXXRecordDecl *UnionFieldRecord =
4884 UnionFieldType->getAsCXXRecordDecl();
4885
4886 // -- X is a union-like class that has a variant member with a non-
4887 // trivial destructor.
4888 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4889 return true;
4890 }
4891 // Technically we are supposed to do this next check unconditionally.
4892 // But that makes absolutely no sense.
4893 } else {
4894 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4895
4896 // -- any of the non-static data members has class type M (or array
4897 // thereof) and M has a deleted destructor or a destructor that is
4898 // inaccessible from the defaulted destructor
4899 if (FieldDtor->isDeleted())
4900 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004901 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004902 AR_accessible)
4903 return true;
4904
4905 // -- X is a union-like class that has a variant member with a non-
4906 // trivial destructor.
4907 if (Union && !FieldDtor->isTrivial())
4908 return true;
4909 }
4910 }
4911 }
4912
4913 if (DD->isVirtual()) {
4914 FunctionDecl *OperatorDelete = 0;
4915 DeclarationName Name =
4916 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004917 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004918 false))
4919 return true;
4920 }
4921
4922
4923 return false;
4924}
4925
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004926/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004927namespace {
4928 struct FindHiddenVirtualMethodData {
4929 Sema *S;
4930 CXXMethodDecl *Method;
4931 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004932 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004933 };
4934}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004935
4936/// \brief Member lookup function that determines whether a given C++
4937/// method overloads virtual methods in a base class without overriding any,
4938/// to be used with CXXRecordDecl::lookupInBases().
4939static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4940 CXXBasePath &Path,
4941 void *UserData) {
4942 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4943
4944 FindHiddenVirtualMethodData &Data
4945 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4946
4947 DeclarationName Name = Data.Method->getDeclName();
4948 assert(Name.getNameKind() == DeclarationName::Identifier);
4949
4950 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004951 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004952 for (Path.Decls = BaseRecord->lookup(Name);
4953 Path.Decls.first != Path.Decls.second;
4954 ++Path.Decls.first) {
4955 NamedDecl *D = *Path.Decls.first;
4956 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004957 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004958 foundSameNameMethod = true;
4959 // Interested only in hidden virtual methods.
4960 if (!MD->isVirtual())
4961 continue;
4962 // If the method we are checking overrides a method from its base
4963 // don't warn about the other overloaded methods.
4964 if (!Data.S->IsOverload(Data.Method, MD, false))
4965 return true;
4966 // Collect the overload only if its hidden.
4967 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4968 overloadedMethods.push_back(MD);
4969 }
4970 }
4971
4972 if (foundSameNameMethod)
4973 Data.OverloadedMethods.append(overloadedMethods.begin(),
4974 overloadedMethods.end());
4975 return foundSameNameMethod;
4976}
4977
4978/// \brief See if a method overloads virtual methods in a base class without
4979/// overriding any.
4980void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4981 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004982 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004983 return;
4984 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4985 return;
4986
4987 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4988 /*bool RecordPaths=*/false,
4989 /*bool DetectVirtual=*/false);
4990 FindHiddenVirtualMethodData Data;
4991 Data.Method = MD;
4992 Data.S = this;
4993
4994 // Keep the base methods that were overriden or introduced in the subclass
4995 // by 'using' in a set. A base method not in this set is hidden.
4996 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4997 res.first != res.second; ++res.first) {
4998 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4999 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5000 E = MD->end_overridden_methods();
5001 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005002 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005003 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5004 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005005 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005006 }
5007
5008 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5009 !Data.OverloadedMethods.empty()) {
5010 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5011 << MD << (Data.OverloadedMethods.size() > 1);
5012
5013 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5014 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5015 Diag(overloadedMD->getLocation(),
5016 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5017 }
5018 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005019}
5020
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005021void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005022 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005023 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005024 SourceLocation RBrac,
5025 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005026 if (!TagDecl)
5027 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005028
Douglas Gregor42af25f2009-05-11 19:58:34 +00005029 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005030
David Blaikie77b6de02011-09-22 02:58:26 +00005031 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005032 // strict aliasing violation!
5033 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005034 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005035
Douglas Gregor23c94db2010-07-02 17:43:08 +00005036 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005037 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005038}
5039
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005040/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5041/// special functions, such as the default constructor, copy
5042/// constructor, or destructor, to the given C++ class (C++
5043/// [special]p1). This routine can only be executed just before the
5044/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005045void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005046 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005047 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005048
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005049 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005050 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005051
Richard Smithb701d3d2011-12-24 21:56:24 +00005052 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5053 ++ASTContext::NumImplicitMoveConstructors;
5054
Douglas Gregora376d102010-07-02 21:50:04 +00005055 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5056 ++ASTContext::NumImplicitCopyAssignmentOperators;
5057
5058 // If we have a dynamic class, then the copy assignment operator may be
5059 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5060 // it shows up in the right place in the vtable and that we diagnose
5061 // problems with the implicit exception specification.
5062 if (ClassDecl->isDynamicClass())
5063 DeclareImplicitCopyAssignment(ClassDecl);
5064 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005065
Richard Smithb701d3d2011-12-24 21:56:24 +00005066 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5067 ++ASTContext::NumImplicitMoveAssignmentOperators;
5068
5069 // Likewise for the move assignment operator.
5070 if (ClassDecl->isDynamicClass())
5071 DeclareImplicitMoveAssignment(ClassDecl);
5072 }
5073
Douglas Gregor4923aa22010-07-02 20:37:36 +00005074 if (!ClassDecl->hasUserDeclaredDestructor()) {
5075 ++ASTContext::NumImplicitDestructors;
5076
5077 // If we have a dynamic class, then the destructor may be virtual, so we
5078 // have to declare the destructor immediately. This ensures that, e.g., it
5079 // shows up in the right place in the vtable and that we diagnose problems
5080 // with the implicit exception specification.
5081 if (ClassDecl->isDynamicClass())
5082 DeclareImplicitDestructor(ClassDecl);
5083 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005084}
5085
Francois Pichet8387e2a2011-04-22 22:18:13 +00005086void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5087 if (!D)
5088 return;
5089
5090 int NumParamList = D->getNumTemplateParameterLists();
5091 for (int i = 0; i < NumParamList; i++) {
5092 TemplateParameterList* Params = D->getTemplateParameterList(i);
5093 for (TemplateParameterList::iterator Param = Params->begin(),
5094 ParamEnd = Params->end();
5095 Param != ParamEnd; ++Param) {
5096 NamedDecl *Named = cast<NamedDecl>(*Param);
5097 if (Named->getDeclName()) {
5098 S->AddDecl(Named);
5099 IdResolver.AddDecl(Named);
5100 }
5101 }
5102 }
5103}
5104
John McCalld226f652010-08-21 09:40:31 +00005105void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005106 if (!D)
5107 return;
5108
5109 TemplateParameterList *Params = 0;
5110 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5111 Params = Template->getTemplateParameters();
5112 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5113 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5114 Params = PartialSpec->getTemplateParameters();
5115 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005116 return;
5117
Douglas Gregor6569d682009-05-27 23:11:45 +00005118 for (TemplateParameterList::iterator Param = Params->begin(),
5119 ParamEnd = Params->end();
5120 Param != ParamEnd; ++Param) {
5121 NamedDecl *Named = cast<NamedDecl>(*Param);
5122 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005123 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005124 IdResolver.AddDecl(Named);
5125 }
5126 }
5127}
5128
John McCalld226f652010-08-21 09:40:31 +00005129void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005130 if (!RecordD) return;
5131 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005132 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005133 PushDeclContext(S, Record);
5134}
5135
John McCalld226f652010-08-21 09:40:31 +00005136void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005137 if (!RecordD) return;
5138 PopDeclContext();
5139}
5140
Douglas Gregor72b505b2008-12-16 21:30:33 +00005141/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5142/// parsing a top-level (non-nested) C++ class, and we are now
5143/// parsing those parts of the given Method declaration that could
5144/// not be parsed earlier (C++ [class.mem]p2), such as default
5145/// arguments. This action should enter the scope of the given
5146/// Method declaration as if we had just parsed the qualified method
5147/// name. However, it should not bring the parameters into scope;
5148/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005149void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005150}
5151
5152/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5153/// C++ method declaration. We're (re-)introducing the given
5154/// function parameter into scope for use in parsing later parts of
5155/// the method declaration. For example, we could see an
5156/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005157void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005158 if (!ParamD)
5159 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005160
John McCalld226f652010-08-21 09:40:31 +00005161 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005162
5163 // If this parameter has an unparsed default argument, clear it out
5164 // to make way for the parsed default argument.
5165 if (Param->hasUnparsedDefaultArg())
5166 Param->setDefaultArg(0);
5167
John McCalld226f652010-08-21 09:40:31 +00005168 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005169 if (Param->getDeclName())
5170 IdResolver.AddDecl(Param);
5171}
5172
5173/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5174/// processing the delayed method declaration for Method. The method
5175/// declaration is now considered finished. There may be a separate
5176/// ActOnStartOfFunctionDef action later (not necessarily
5177/// immediately!) for this method, if it was also defined inside the
5178/// class body.
John McCalld226f652010-08-21 09:40:31 +00005179void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005180 if (!MethodD)
5181 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005182
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005183 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005184
John McCalld226f652010-08-21 09:40:31 +00005185 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005186
5187 // Now that we have our default arguments, check the constructor
5188 // again. It could produce additional diagnostics or affect whether
5189 // the class has implicitly-declared destructors, among other
5190 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005191 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5192 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005193
5194 // Check the default arguments, which we may have added.
5195 if (!Method->isInvalidDecl())
5196 CheckCXXDefaultArguments(Method);
5197}
5198
Douglas Gregor42a552f2008-11-05 20:51:48 +00005199/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005200/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005201/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005202/// emit diagnostics and set the invalid bit to true. In any case, the type
5203/// will be updated to reflect a well-formed type for the constructor and
5204/// returned.
5205QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005206 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005207 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005208
5209 // C++ [class.ctor]p3:
5210 // A constructor shall not be virtual (10.3) or static (9.4). A
5211 // constructor can be invoked for a const, volatile or const
5212 // volatile object. A constructor shall not be declared const,
5213 // volatile, or const volatile (9.3.2).
5214 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005215 if (!D.isInvalidType())
5216 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5217 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5218 << SourceRange(D.getIdentifierLoc());
5219 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005220 }
John McCalld931b082010-08-26 03:08:43 +00005221 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005222 if (!D.isInvalidType())
5223 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5224 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5225 << SourceRange(D.getIdentifierLoc());
5226 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005227 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005228 }
Mike Stump1eb44332009-09-09 15:08:12 +00005229
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005230 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005231 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005232 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005233 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5234 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005235 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005236 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5237 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005238 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005239 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5240 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005241 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005242 }
Mike Stump1eb44332009-09-09 15:08:12 +00005243
Douglas Gregorc938c162011-01-26 05:01:58 +00005244 // C++0x [class.ctor]p4:
5245 // A constructor shall not be declared with a ref-qualifier.
5246 if (FTI.hasRefQualifier()) {
5247 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5248 << FTI.RefQualifierIsLValueRef
5249 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5250 D.setInvalidType();
5251 }
5252
Douglas Gregor42a552f2008-11-05 20:51:48 +00005253 // Rebuild the function type "R" without any type qualifiers (in
5254 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005255 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005256 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005257 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5258 return R;
5259
5260 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5261 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005262 EPI.RefQualifier = RQ_None;
5263
Chris Lattner65401802009-04-25 08:28:21 +00005264 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005265 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005266}
5267
Douglas Gregor72b505b2008-12-16 21:30:33 +00005268/// CheckConstructor - Checks a fully-formed constructor for
5269/// well-formedness, issuing any diagnostics required. Returns true if
5270/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005271void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005272 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005273 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5274 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005275 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005276
5277 // C++ [class.copy]p3:
5278 // A declaration of a constructor for a class X is ill-formed if
5279 // its first parameter is of type (optionally cv-qualified) X and
5280 // either there are no other parameters or else all other
5281 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005282 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005283 ((Constructor->getNumParams() == 1) ||
5284 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005285 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5286 Constructor->getTemplateSpecializationKind()
5287 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005288 QualType ParamType = Constructor->getParamDecl(0)->getType();
5289 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5290 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005291 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005292 const char *ConstRef
5293 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5294 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005295 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005296 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005297
5298 // FIXME: Rather that making the constructor invalid, we should endeavor
5299 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005300 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005301 }
5302 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005303}
5304
John McCall15442822010-08-04 01:04:25 +00005305/// CheckDestructor - Checks a fully-formed destructor definition for
5306/// well-formedness, issuing any diagnostics required. Returns true
5307/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005308bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005309 CXXRecordDecl *RD = Destructor->getParent();
5310
5311 if (Destructor->isVirtual()) {
5312 SourceLocation Loc;
5313
5314 if (!Destructor->isImplicit())
5315 Loc = Destructor->getLocation();
5316 else
5317 Loc = RD->getLocation();
5318
5319 // If we have a virtual destructor, look up the deallocation function
5320 FunctionDecl *OperatorDelete = 0;
5321 DeclarationName Name =
5322 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005323 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005324 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005325
Eli Friedman5f2987c2012-02-02 03:46:19 +00005326 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005327
5328 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005329 }
Anders Carlsson37909802009-11-30 21:24:50 +00005330
5331 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005332}
5333
Mike Stump1eb44332009-09-09 15:08:12 +00005334static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005335FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5336 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5337 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005338 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005339}
5340
Douglas Gregor42a552f2008-11-05 20:51:48 +00005341/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5342/// the well-formednes of the destructor declarator @p D with type @p
5343/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005344/// emit diagnostics and set the declarator to invalid. Even if this happens,
5345/// will be updated to reflect a well-formed type for the destructor and
5346/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005347QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005348 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005349 // C++ [class.dtor]p1:
5350 // [...] A typedef-name that names a class is a class-name
5351 // (7.1.3); however, a typedef-name that names a class shall not
5352 // be used as the identifier in the declarator for a destructor
5353 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005354 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005355 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005356 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005357 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005358 else if (const TemplateSpecializationType *TST =
5359 DeclaratorType->getAs<TemplateSpecializationType>())
5360 if (TST->isTypeAlias())
5361 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5362 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005363
5364 // C++ [class.dtor]p2:
5365 // A destructor is used to destroy objects of its class type. A
5366 // destructor takes no parameters, and no return type can be
5367 // specified for it (not even void). The address of a destructor
5368 // shall not be taken. A destructor shall not be static. A
5369 // destructor can be invoked for a const, volatile or const
5370 // volatile object. A destructor shall not be declared const,
5371 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005372 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005373 if (!D.isInvalidType())
5374 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5375 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005376 << SourceRange(D.getIdentifierLoc())
5377 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5378
John McCalld931b082010-08-26 03:08:43 +00005379 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005380 }
Chris Lattner65401802009-04-25 08:28:21 +00005381 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005382 // Destructors don't have return types, but the parser will
5383 // happily parse something like:
5384 //
5385 // class X {
5386 // float ~X();
5387 // };
5388 //
5389 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005390 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5391 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5392 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005393 }
Mike Stump1eb44332009-09-09 15:08:12 +00005394
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005395 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005396 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005397 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005398 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5399 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005400 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005401 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5402 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005403 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005404 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5405 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005406 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005407 }
5408
Douglas Gregorc938c162011-01-26 05:01:58 +00005409 // C++0x [class.dtor]p2:
5410 // A destructor shall not be declared with a ref-qualifier.
5411 if (FTI.hasRefQualifier()) {
5412 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5413 << FTI.RefQualifierIsLValueRef
5414 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5415 D.setInvalidType();
5416 }
5417
Douglas Gregor42a552f2008-11-05 20:51:48 +00005418 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005419 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005420 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5421
5422 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005423 FTI.freeArgs();
5424 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005425 }
5426
Mike Stump1eb44332009-09-09 15:08:12 +00005427 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005428 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005429 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005430 D.setInvalidType();
5431 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005432
5433 // Rebuild the function type "R" without any type qualifiers or
5434 // parameters (in case any of the errors above fired) and with
5435 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005436 // types.
John McCalle23cf432010-12-14 08:05:40 +00005437 if (!D.isInvalidType())
5438 return R;
5439
Douglas Gregord92ec472010-07-01 05:10:53 +00005440 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005441 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5442 EPI.Variadic = false;
5443 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005444 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005445 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005446}
5447
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005448/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5449/// well-formednes of the conversion function declarator @p D with
5450/// type @p R. If there are any errors in the declarator, this routine
5451/// will emit diagnostics and return true. Otherwise, it will return
5452/// false. Either way, the type @p R will be updated to reflect a
5453/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005454void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005455 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005456 // C++ [class.conv.fct]p1:
5457 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005458 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005459 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005460 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005461 if (!D.isInvalidType())
5462 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5463 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5464 << SourceRange(D.getIdentifierLoc());
5465 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005466 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005467 }
John McCalla3f81372010-04-13 00:04:31 +00005468
5469 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5470
Chris Lattner6e475012009-04-25 08:35:12 +00005471 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005472 // Conversion functions don't have return types, but the parser will
5473 // happily parse something like:
5474 //
5475 // class X {
5476 // float operator bool();
5477 // };
5478 //
5479 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005480 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5481 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5482 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005483 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005484 }
5485
John McCalla3f81372010-04-13 00:04:31 +00005486 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5487
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005488 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005489 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005490 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5491
5492 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005493 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005494 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005495 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005496 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005497 D.setInvalidType();
5498 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005499
John McCalla3f81372010-04-13 00:04:31 +00005500 // Diagnose "&operator bool()" and other such nonsense. This
5501 // is actually a gcc extension which we don't support.
5502 if (Proto->getResultType() != ConvType) {
5503 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5504 << Proto->getResultType();
5505 D.setInvalidType();
5506 ConvType = Proto->getResultType();
5507 }
5508
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005509 // C++ [class.conv.fct]p4:
5510 // The conversion-type-id shall not represent a function type nor
5511 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005512 if (ConvType->isArrayType()) {
5513 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5514 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005515 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005516 } else if (ConvType->isFunctionType()) {
5517 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5518 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005519 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005520 }
5521
5522 // Rebuild the function type "R" without any parameters (in case any
5523 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005524 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005525 if (D.isInvalidType())
5526 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005527
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005528 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005529 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005530 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005531 getLangOptions().CPlusPlus0x ?
5532 diag::warn_cxx98_compat_explicit_conversion_functions :
5533 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005534 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005535}
5536
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005537/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5538/// the declaration of the given C++ conversion function. This routine
5539/// is responsible for recording the conversion function in the C++
5540/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005541Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005542 assert(Conversion && "Expected to receive a conversion function declaration");
5543
Douglas Gregor9d350972008-12-12 08:25:50 +00005544 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005545
5546 // Make sure we aren't redeclaring the conversion function.
5547 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005548
5549 // C++ [class.conv.fct]p1:
5550 // [...] A conversion function is never used to convert a
5551 // (possibly cv-qualified) object to the (possibly cv-qualified)
5552 // same object type (or a reference to it), to a (possibly
5553 // cv-qualified) base class of that type (or a reference to it),
5554 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005555 // FIXME: Suppress this warning if the conversion function ends up being a
5556 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005557 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005558 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005559 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005560 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005561 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5562 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005563 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005564 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005565 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5566 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005567 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005568 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005569 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005570 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005571 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005572 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005573 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005574 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005575 }
5576
Douglas Gregore80622f2010-09-29 04:25:11 +00005577 if (FunctionTemplateDecl *ConversionTemplate
5578 = Conversion->getDescribedFunctionTemplate())
5579 return ConversionTemplate;
5580
John McCalld226f652010-08-21 09:40:31 +00005581 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005582}
5583
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005584//===----------------------------------------------------------------------===//
5585// Namespace Handling
5586//===----------------------------------------------------------------------===//
5587
John McCallea318642010-08-26 09:15:37 +00005588
5589
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005590/// ActOnStartNamespaceDef - This is called at the start of a namespace
5591/// definition.
John McCalld226f652010-08-21 09:40:31 +00005592Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005593 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005594 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005595 SourceLocation IdentLoc,
5596 IdentifierInfo *II,
5597 SourceLocation LBrace,
5598 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005599 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5600 // For anonymous namespace, take the location of the left brace.
5601 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005602 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005603 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005604 bool IsStd = false;
5605 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005606 Scope *DeclRegionScope = NamespcScope->getParent();
5607
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005608 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005609 if (II) {
5610 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005611 // The identifier in an original-namespace-definition shall not
5612 // have been previously defined in the declarative region in
5613 // which the original-namespace-definition appears. The
5614 // identifier in an original-namespace-definition is the name of
5615 // the namespace. Subsequently in that declarative region, it is
5616 // treated as an original-namespace-name.
5617 //
5618 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005619 // look through using directives, just look for any ordinary names.
5620
5621 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005622 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5623 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005624 NamedDecl *PrevDecl = 0;
5625 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005626 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005627 R.first != R.second; ++R.first) {
5628 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5629 PrevDecl = *R.first;
5630 break;
5631 }
5632 }
5633
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005634 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5635
5636 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005637 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005638 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005639 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005640 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005641 // The user probably just forgot the 'inline', so suggest that it
5642 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005643 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005644 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5645 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005646 Diag(Loc, diag::err_inline_namespace_mismatch)
5647 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005648 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005649 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5650
5651 IsInline = PrevNS->isInline();
5652 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005653 } else if (PrevDecl) {
5654 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005655 Diag(Loc, diag::err_redefinition_different_kind)
5656 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005657 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005658 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005659 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005660 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005661 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005662 // This is the first "real" definition of the namespace "std", so update
5663 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005664 PrevNS = getStdNamespace();
5665 IsStd = true;
5666 AddToKnown = !IsInline;
5667 } else {
5668 // We've seen this namespace for the first time.
5669 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005670 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005671 } else {
John McCall9aeed322009-10-01 00:25:31 +00005672 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005673
5674 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005675 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005676 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005677 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005678 } else {
5679 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005680 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005681 }
5682
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005683 if (PrevNS && IsInline != PrevNS->isInline()) {
5684 // inline-ness must match
5685 Diag(Loc, diag::err_inline_namespace_mismatch)
5686 << IsInline;
5687 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005688
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005689 // Recover by ignoring the new namespace's inline status.
5690 IsInline = PrevNS->isInline();
5691 }
5692 }
5693
5694 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5695 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005696 if (IsInvalid)
5697 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005698
5699 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005700
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005701 // FIXME: Should we be merging attributes?
5702 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005703 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005704
5705 if (IsStd)
5706 StdNamespace = Namespc;
5707 if (AddToKnown)
5708 KnownNamespaces[Namespc] = false;
5709
5710 if (II) {
5711 PushOnScopeChains(Namespc, DeclRegionScope);
5712 } else {
5713 // Link the anonymous namespace into its parent.
5714 DeclContext *Parent = CurContext->getRedeclContext();
5715 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5716 TU->setAnonymousNamespace(Namespc);
5717 } else {
5718 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005719 }
John McCall9aeed322009-10-01 00:25:31 +00005720
Douglas Gregora4181472010-03-24 00:46:35 +00005721 CurContext->addDecl(Namespc);
5722
John McCall9aeed322009-10-01 00:25:31 +00005723 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5724 // behaves as if it were replaced by
5725 // namespace unique { /* empty body */ }
5726 // using namespace unique;
5727 // namespace unique { namespace-body }
5728 // where all occurrences of 'unique' in a translation unit are
5729 // replaced by the same identifier and this identifier differs
5730 // from all other identifiers in the entire program.
5731
5732 // We just create the namespace with an empty name and then add an
5733 // implicit using declaration, just like the standard suggests.
5734 //
5735 // CodeGen enforces the "universally unique" aspect by giving all
5736 // declarations semantically contained within an anonymous
5737 // namespace internal linkage.
5738
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005739 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005740 UsingDirectiveDecl* UD
5741 = UsingDirectiveDecl::Create(Context, CurContext,
5742 /* 'using' */ LBrace,
5743 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005744 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005745 /* identifier */ SourceLocation(),
5746 Namespc,
5747 /* Ancestor */ CurContext);
5748 UD->setImplicit();
5749 CurContext->addDecl(UD);
5750 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005751 }
5752
5753 // Although we could have an invalid decl (i.e. the namespace name is a
5754 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005755 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5756 // for the namespace has the declarations that showed up in that particular
5757 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005758 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005759 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005760}
5761
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005762/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5763/// is a namespace alias, returns the namespace it points to.
5764static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5765 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5766 return AD->getNamespace();
5767 return dyn_cast_or_null<NamespaceDecl>(D);
5768}
5769
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005770/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5771/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005772void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005773 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5774 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005775 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005776 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005777 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005778 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005779}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005780
John McCall384aff82010-08-25 07:42:41 +00005781CXXRecordDecl *Sema::getStdBadAlloc() const {
5782 return cast_or_null<CXXRecordDecl>(
5783 StdBadAlloc.get(Context.getExternalSource()));
5784}
5785
5786NamespaceDecl *Sema::getStdNamespace() const {
5787 return cast_or_null<NamespaceDecl>(
5788 StdNamespace.get(Context.getExternalSource()));
5789}
5790
Douglas Gregor66992202010-06-29 17:53:46 +00005791/// \brief Retrieve the special "std" namespace, which may require us to
5792/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005793NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005794 if (!StdNamespace) {
5795 // The "std" namespace has not yet been defined, so build one implicitly.
5796 StdNamespace = NamespaceDecl::Create(Context,
5797 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005798 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005799 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005800 &PP.getIdentifierTable().get("std"),
5801 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005802 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005803 }
5804
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005805 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005806}
5807
Sebastian Redl395e04d2012-01-17 22:49:33 +00005808bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5809 assert(getLangOptions().CPlusPlus &&
5810 "Looking for std::initializer_list outside of C++.");
5811
5812 // We're looking for implicit instantiations of
5813 // template <typename E> class std::initializer_list.
5814
5815 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5816 return false;
5817
Sebastian Redl84760e32012-01-17 22:49:58 +00005818 ClassTemplateDecl *Template = 0;
5819 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005820
Sebastian Redl84760e32012-01-17 22:49:58 +00005821 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005822
Sebastian Redl84760e32012-01-17 22:49:58 +00005823 ClassTemplateSpecializationDecl *Specialization =
5824 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5825 if (!Specialization)
5826 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005827
Sebastian Redl84760e32012-01-17 22:49:58 +00005828 Template = Specialization->getSpecializedTemplate();
5829 Arguments = Specialization->getTemplateArgs().data();
5830 } else if (const TemplateSpecializationType *TST =
5831 Ty->getAs<TemplateSpecializationType>()) {
5832 Template = dyn_cast_or_null<ClassTemplateDecl>(
5833 TST->getTemplateName().getAsTemplateDecl());
5834 Arguments = TST->getArgs();
5835 }
5836 if (!Template)
5837 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005838
5839 if (!StdInitializerList) {
5840 // Haven't recognized std::initializer_list yet, maybe this is it.
5841 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5842 if (TemplateClass->getIdentifier() !=
5843 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005844 !getStdNamespace()->InEnclosingNamespaceSetOf(
5845 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005846 return false;
5847 // This is a template called std::initializer_list, but is it the right
5848 // template?
5849 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005850 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005851 return false;
5852 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5853 return false;
5854
5855 // It's the right template.
5856 StdInitializerList = Template;
5857 }
5858
5859 if (Template != StdInitializerList)
5860 return false;
5861
5862 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005863 if (Element)
5864 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005865 return true;
5866}
5867
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005868static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5869 NamespaceDecl *Std = S.getStdNamespace();
5870 if (!Std) {
5871 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5872 return 0;
5873 }
5874
5875 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5876 Loc, Sema::LookupOrdinaryName);
5877 if (!S.LookupQualifiedName(Result, Std)) {
5878 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5879 return 0;
5880 }
5881 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5882 if (!Template) {
5883 Result.suppressDiagnostics();
5884 // We found something weird. Complain about the first thing we found.
5885 NamedDecl *Found = *Result.begin();
5886 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5887 return 0;
5888 }
5889
5890 // We found some template called std::initializer_list. Now verify that it's
5891 // correct.
5892 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005893 if (Params->getMinRequiredArguments() != 1 ||
5894 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005895 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5896 return 0;
5897 }
5898
5899 return Template;
5900}
5901
5902QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5903 if (!StdInitializerList) {
5904 StdInitializerList = LookupStdInitializerList(*this, Loc);
5905 if (!StdInitializerList)
5906 return QualType();
5907 }
5908
5909 TemplateArgumentListInfo Args(Loc, Loc);
5910 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5911 Context.getTrivialTypeSourceInfo(Element,
5912 Loc)));
5913 return Context.getCanonicalType(
5914 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5915}
5916
Sebastian Redl98d36062012-01-17 22:50:14 +00005917bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5918 // C++ [dcl.init.list]p2:
5919 // A constructor is an initializer-list constructor if its first parameter
5920 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5921 // std::initializer_list<E> for some type E, and either there are no other
5922 // parameters or else all other parameters have default arguments.
5923 if (Ctor->getNumParams() < 1 ||
5924 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5925 return false;
5926
5927 QualType ArgType = Ctor->getParamDecl(0)->getType();
5928 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5929 ArgType = RT->getPointeeType().getUnqualifiedType();
5930
5931 return isStdInitializerList(ArgType, 0);
5932}
5933
Douglas Gregor9172aa62011-03-26 22:25:30 +00005934/// \brief Determine whether a using statement is in a context where it will be
5935/// apply in all contexts.
5936static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5937 switch (CurContext->getDeclKind()) {
5938 case Decl::TranslationUnit:
5939 return true;
5940 case Decl::LinkageSpec:
5941 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5942 default:
5943 return false;
5944 }
5945}
5946
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005947namespace {
5948
5949// Callback to only accept typo corrections that are namespaces.
5950class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5951 public:
5952 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5953 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5954 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5955 }
5956 return false;
5957 }
5958};
5959
5960}
5961
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005962static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5963 CXXScopeSpec &SS,
5964 SourceLocation IdentLoc,
5965 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005966 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005967 R.clear();
5968 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005969 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005970 Validator)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005971 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5972 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5973 if (DeclContext *DC = S.computeDeclContext(SS, false))
5974 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5975 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5976 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5977 else
5978 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5979 << Ident << CorrectedQuotedStr
5980 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005981
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005982 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5983 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005984
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005985 Ident = Corrected.getCorrectionAsIdentifierInfo();
5986 R.addDecl(Corrected.getCorrectionDecl());
5987 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005988 }
5989 return false;
5990}
5991
John McCalld226f652010-08-21 09:40:31 +00005992Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005993 SourceLocation UsingLoc,
5994 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005995 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005996 SourceLocation IdentLoc,
5997 IdentifierInfo *NamespcName,
5998 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005999 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6000 assert(NamespcName && "Invalid NamespcName.");
6001 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00006002
6003 // This can only happen along a recovery path.
6004 while (S->getFlags() & Scope::TemplateParamScope)
6005 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006006 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006007
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006008 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006009 NestedNameSpecifier *Qualifier = 0;
6010 if (SS.isSet())
6011 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6012
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006013 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006014 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6015 LookupParsedName(R, S, &SS);
6016 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006017 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006018
Douglas Gregor66992202010-06-29 17:53:46 +00006019 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006020 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006021 // Allow "using namespace std;" or "using namespace ::std;" even if
6022 // "std" hasn't been defined yet, for GCC compatibility.
6023 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6024 NamespcName->isStr("std")) {
6025 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006026 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006027 R.resolveKind();
6028 }
6029 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006030 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006031 }
6032
John McCallf36e02d2009-10-09 21:13:30 +00006033 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006034 NamedDecl *Named = R.getFoundDecl();
6035 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6036 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006037 // C++ [namespace.udir]p1:
6038 // A using-directive specifies that the names in the nominated
6039 // namespace can be used in the scope in which the
6040 // using-directive appears after the using-directive. During
6041 // unqualified name lookup (3.4.1), the names appear as if they
6042 // were declared in the nearest enclosing namespace which
6043 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006044 // namespace. [Note: in this context, "contains" means "contains
6045 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006046
6047 // Find enclosing context containing both using-directive and
6048 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006049 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006050 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6051 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6052 CommonAncestor = CommonAncestor->getParent();
6053
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006054 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006055 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006056 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006057
Douglas Gregor9172aa62011-03-26 22:25:30 +00006058 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006059 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006060 Diag(IdentLoc, diag::warn_using_directive_in_header);
6061 }
6062
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006063 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006064 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006065 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006066 }
6067
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006068 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006069 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006070}
6071
6072void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6073 // If scope has associated entity, then using directive is at namespace
6074 // or translation unit scope. We add UsingDirectiveDecls, into
6075 // it's lookup structure.
6076 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006077 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006078 else
6079 // Otherwise it is block-sope. using-directives will affect lookup
6080 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00006081 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006082}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006083
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006084
John McCalld226f652010-08-21 09:40:31 +00006085Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006086 AccessSpecifier AS,
6087 bool HasUsingKeyword,
6088 SourceLocation UsingLoc,
6089 CXXScopeSpec &SS,
6090 UnqualifiedId &Name,
6091 AttributeList *AttrList,
6092 bool IsTypeName,
6093 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006094 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006095
Douglas Gregor12c118a2009-11-04 16:30:06 +00006096 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006097 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006098 case UnqualifiedId::IK_Identifier:
6099 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006100 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006101 case UnqualifiedId::IK_ConversionFunctionId:
6102 break;
6103
6104 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006105 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00006106 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00006107 Diag(Name.getSourceRange().getBegin(),
6108 getLangOptions().CPlusPlus0x ?
6109 diag::warn_cxx98_compat_using_decl_constructor :
6110 diag::err_using_decl_constructor)
6111 << SS.getRange();
6112
John McCall604e7f12009-12-08 07:46:18 +00006113 if (getLangOptions().CPlusPlus0x) break;
6114
John McCalld226f652010-08-21 09:40:31 +00006115 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006116
6117 case UnqualifiedId::IK_DestructorName:
6118 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6119 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006120 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006121
6122 case UnqualifiedId::IK_TemplateId:
6123 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6124 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006125 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006126 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006127
6128 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6129 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006130 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006131 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006132
John McCall60fa3cf2009-12-11 02:10:03 +00006133 // Warn about using declarations.
6134 // TODO: store that the declaration was written without 'using' and
6135 // talk about access decls instead of using decls in the
6136 // diagnostics.
6137 if (!HasUsingKeyword) {
6138 UsingLoc = Name.getSourceRange().getBegin();
6139
6140 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006141 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006142 }
6143
Douglas Gregor56c04582010-12-16 00:46:58 +00006144 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6145 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6146 return 0;
6147
John McCall9488ea12009-11-17 05:59:44 +00006148 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006149 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006150 /* IsInstantiation */ false,
6151 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006152 if (UD)
6153 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006154
John McCalld226f652010-08-21 09:40:31 +00006155 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006156}
6157
Douglas Gregor09acc982010-07-07 23:08:52 +00006158/// \brief Determine whether a using declaration considers the given
6159/// declarations as "equivalent", e.g., if they are redeclarations of
6160/// the same entity or are both typedefs of the same type.
6161static bool
6162IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6163 bool &SuppressRedeclaration) {
6164 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6165 SuppressRedeclaration = false;
6166 return true;
6167 }
6168
Richard Smith162e1c12011-04-15 14:24:37 +00006169 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6170 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006171 SuppressRedeclaration = true;
6172 return Context.hasSameType(TD1->getUnderlyingType(),
6173 TD2->getUnderlyingType());
6174 }
6175
6176 return false;
6177}
6178
6179
John McCall9f54ad42009-12-10 09:41:52 +00006180/// Determines whether to create a using shadow decl for a particular
6181/// decl, given the set of decls existing prior to this using lookup.
6182bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6183 const LookupResult &Previous) {
6184 // Diagnose finding a decl which is not from a base class of the
6185 // current class. We do this now because there are cases where this
6186 // function will silently decide not to build a shadow decl, which
6187 // will pre-empt further diagnostics.
6188 //
6189 // We don't need to do this in C++0x because we do the check once on
6190 // the qualifier.
6191 //
6192 // FIXME: diagnose the following if we care enough:
6193 // struct A { int foo; };
6194 // struct B : A { using A::foo; };
6195 // template <class T> struct C : A {};
6196 // template <class T> struct D : C<T> { using B::foo; } // <---
6197 // This is invalid (during instantiation) in C++03 because B::foo
6198 // resolves to the using decl in B, which is not a base class of D<T>.
6199 // We can't diagnose it immediately because C<T> is an unknown
6200 // specialization. The UsingShadowDecl in D<T> then points directly
6201 // to A::foo, which will look well-formed when we instantiate.
6202 // The right solution is to not collapse the shadow-decl chain.
6203 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6204 DeclContext *OrigDC = Orig->getDeclContext();
6205
6206 // Handle enums and anonymous structs.
6207 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6208 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6209 while (OrigRec->isAnonymousStructOrUnion())
6210 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6211
6212 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6213 if (OrigDC == CurContext) {
6214 Diag(Using->getLocation(),
6215 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006216 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006217 Diag(Orig->getLocation(), diag::note_using_decl_target);
6218 return true;
6219 }
6220
Douglas Gregordc355712011-02-25 00:36:19 +00006221 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006222 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006223 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006224 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006225 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006226 Diag(Orig->getLocation(), diag::note_using_decl_target);
6227 return true;
6228 }
6229 }
6230
6231 if (Previous.empty()) return false;
6232
6233 NamedDecl *Target = Orig;
6234 if (isa<UsingShadowDecl>(Target))
6235 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6236
John McCalld7533ec2009-12-11 02:33:26 +00006237 // If the target happens to be one of the previous declarations, we
6238 // don't have a conflict.
6239 //
6240 // FIXME: but we might be increasing its access, in which case we
6241 // should redeclare it.
6242 NamedDecl *NonTag = 0, *Tag = 0;
6243 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6244 I != E; ++I) {
6245 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006246 bool Result;
6247 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6248 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006249
6250 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6251 }
6252
John McCall9f54ad42009-12-10 09:41:52 +00006253 if (Target->isFunctionOrFunctionTemplate()) {
6254 FunctionDecl *FD;
6255 if (isa<FunctionTemplateDecl>(Target))
6256 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6257 else
6258 FD = cast<FunctionDecl>(Target);
6259
6260 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006261 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006262 case Ovl_Overload:
6263 return false;
6264
6265 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006266 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006267 break;
6268
6269 // We found a decl with the exact signature.
6270 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006271 // If we're in a record, we want to hide the target, so we
6272 // return true (without a diagnostic) to tell the caller not to
6273 // build a shadow decl.
6274 if (CurContext->isRecord())
6275 return true;
6276
6277 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006278 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006279 break;
6280 }
6281
6282 Diag(Target->getLocation(), diag::note_using_decl_target);
6283 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6284 return true;
6285 }
6286
6287 // Target is not a function.
6288
John McCall9f54ad42009-12-10 09:41:52 +00006289 if (isa<TagDecl>(Target)) {
6290 // No conflict between a tag and a non-tag.
6291 if (!Tag) return false;
6292
John McCall41ce66f2009-12-10 19:51:03 +00006293 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006294 Diag(Target->getLocation(), diag::note_using_decl_target);
6295 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6296 return true;
6297 }
6298
6299 // No conflict between a tag and a non-tag.
6300 if (!NonTag) return false;
6301
John McCall41ce66f2009-12-10 19:51:03 +00006302 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006303 Diag(Target->getLocation(), diag::note_using_decl_target);
6304 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6305 return true;
6306}
6307
John McCall9488ea12009-11-17 05:59:44 +00006308/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006309UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006310 UsingDecl *UD,
6311 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006312
6313 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006314 NamedDecl *Target = Orig;
6315 if (isa<UsingShadowDecl>(Target)) {
6316 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6317 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006318 }
6319
6320 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006321 = UsingShadowDecl::Create(Context, CurContext,
6322 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006323 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006324
6325 Shadow->setAccess(UD->getAccess());
6326 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6327 Shadow->setInvalidDecl();
6328
John McCall9488ea12009-11-17 05:59:44 +00006329 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006330 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006331 else
John McCall604e7f12009-12-08 07:46:18 +00006332 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006333
John McCall604e7f12009-12-08 07:46:18 +00006334
John McCall9f54ad42009-12-10 09:41:52 +00006335 return Shadow;
6336}
John McCall604e7f12009-12-08 07:46:18 +00006337
John McCall9f54ad42009-12-10 09:41:52 +00006338/// Hides a using shadow declaration. This is required by the current
6339/// using-decl implementation when a resolvable using declaration in a
6340/// class is followed by a declaration which would hide or override
6341/// one or more of the using decl's targets; for example:
6342///
6343/// struct Base { void foo(int); };
6344/// struct Derived : Base {
6345/// using Base::foo;
6346/// void foo(int);
6347/// };
6348///
6349/// The governing language is C++03 [namespace.udecl]p12:
6350///
6351/// When a using-declaration brings names from a base class into a
6352/// derived class scope, member functions in the derived class
6353/// override and/or hide member functions with the same name and
6354/// parameter types in a base class (rather than conflicting).
6355///
6356/// There are two ways to implement this:
6357/// (1) optimistically create shadow decls when they're not hidden
6358/// by existing declarations, or
6359/// (2) don't create any shadow decls (or at least don't make them
6360/// visible) until we've fully parsed/instantiated the class.
6361/// The problem with (1) is that we might have to retroactively remove
6362/// a shadow decl, which requires several O(n) operations because the
6363/// decl structures are (very reasonably) not designed for removal.
6364/// (2) avoids this but is very fiddly and phase-dependent.
6365void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006366 if (Shadow->getDeclName().getNameKind() ==
6367 DeclarationName::CXXConversionFunctionName)
6368 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6369
John McCall9f54ad42009-12-10 09:41:52 +00006370 // Remove it from the DeclContext...
6371 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006372
John McCall9f54ad42009-12-10 09:41:52 +00006373 // ...and the scope, if applicable...
6374 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006375 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006376 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006377 }
6378
John McCall9f54ad42009-12-10 09:41:52 +00006379 // ...and the using decl.
6380 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6381
6382 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006383 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006384}
6385
John McCall7ba107a2009-11-18 02:36:19 +00006386/// Builds a using declaration.
6387///
6388/// \param IsInstantiation - Whether this call arises from an
6389/// instantiation of an unresolved using declaration. We treat
6390/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006391NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6392 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006393 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006394 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006395 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006396 bool IsInstantiation,
6397 bool IsTypeName,
6398 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006399 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006400 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006401 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006402
Anders Carlsson550b14b2009-08-28 05:49:21 +00006403 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006404
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006405 if (SS.isEmpty()) {
6406 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006407 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006408 }
Mike Stump1eb44332009-09-09 15:08:12 +00006409
John McCall9f54ad42009-12-10 09:41:52 +00006410 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006411 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006412 ForRedeclaration);
6413 Previous.setHideTags(false);
6414 if (S) {
6415 LookupName(Previous, S);
6416
6417 // It is really dumb that we have to do this.
6418 LookupResult::Filter F = Previous.makeFilter();
6419 while (F.hasNext()) {
6420 NamedDecl *D = F.next();
6421 if (!isDeclInScope(D, CurContext, S))
6422 F.erase();
6423 }
6424 F.done();
6425 } else {
6426 assert(IsInstantiation && "no scope in non-instantiation");
6427 assert(CurContext->isRecord() && "scope not record in instantiation");
6428 LookupQualifiedName(Previous, CurContext);
6429 }
6430
John McCall9f54ad42009-12-10 09:41:52 +00006431 // Check for invalid redeclarations.
6432 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6433 return 0;
6434
6435 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006436 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6437 return 0;
6438
John McCallaf8e6ed2009-11-12 03:15:40 +00006439 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006440 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006441 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006442 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006443 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006444 // FIXME: not all declaration name kinds are legal here
6445 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6446 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006447 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006448 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006449 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006450 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6451 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006452 }
John McCalled976492009-12-04 22:46:56 +00006453 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006454 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6455 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006456 }
John McCalled976492009-12-04 22:46:56 +00006457 D->setAccess(AS);
6458 CurContext->addDecl(D);
6459
6460 if (!LookupContext) return D;
6461 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006462
John McCall77bb1aa2010-05-01 00:40:08 +00006463 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006464 UD->setInvalidDecl();
6465 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006466 }
6467
Sebastian Redlf677ea32011-02-05 19:23:19 +00006468 // Constructor inheriting using decls get special treatment.
6469 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006470 if (CheckInheritedConstructorUsingDecl(UD))
6471 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006472 return UD;
6473 }
6474
6475 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006476
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006477 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006478
John McCall604e7f12009-12-08 07:46:18 +00006479 // Unlike most lookups, we don't always want to hide tag
6480 // declarations: tag names are visible through the using declaration
6481 // even if hidden by ordinary names, *except* in a dependent context
6482 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006483 if (!IsInstantiation)
6484 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006485
John McCalla24dc2e2009-11-17 02:14:36 +00006486 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006487
John McCallf36e02d2009-10-09 21:13:30 +00006488 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006489 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006490 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006491 UD->setInvalidDecl();
6492 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006493 }
6494
John McCalled976492009-12-04 22:46:56 +00006495 if (R.isAmbiguous()) {
6496 UD->setInvalidDecl();
6497 return UD;
6498 }
Mike Stump1eb44332009-09-09 15:08:12 +00006499
John McCall7ba107a2009-11-18 02:36:19 +00006500 if (IsTypeName) {
6501 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006502 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006503 Diag(IdentLoc, diag::err_using_typename_non_type);
6504 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6505 Diag((*I)->getUnderlyingDecl()->getLocation(),
6506 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006507 UD->setInvalidDecl();
6508 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006509 }
6510 } else {
6511 // If we asked for a non-typename and we got a type, error out,
6512 // but only if this is an instantiation of an unresolved using
6513 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006514 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006515 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6516 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006517 UD->setInvalidDecl();
6518 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006519 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006520 }
6521
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006522 // C++0x N2914 [namespace.udecl]p6:
6523 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006524 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006525 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6526 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006527 UD->setInvalidDecl();
6528 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006529 }
Mike Stump1eb44332009-09-09 15:08:12 +00006530
John McCall9f54ad42009-12-10 09:41:52 +00006531 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6532 if (!CheckUsingShadowDecl(UD, *I, Previous))
6533 BuildUsingShadowDecl(S, UD, *I);
6534 }
John McCall9488ea12009-11-17 05:59:44 +00006535
6536 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006537}
6538
Sebastian Redlf677ea32011-02-05 19:23:19 +00006539/// Additional checks for a using declaration referring to a constructor name.
6540bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6541 if (UD->isTypeName()) {
6542 // FIXME: Cannot specify typename when specifying constructor
6543 return true;
6544 }
6545
Douglas Gregordc355712011-02-25 00:36:19 +00006546 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006547 assert(SourceType &&
6548 "Using decl naming constructor doesn't have type in scope spec.");
6549 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6550
6551 // Check whether the named type is a direct base class.
6552 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6553 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6554 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6555 BaseIt != BaseE; ++BaseIt) {
6556 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6557 if (CanonicalSourceType == BaseType)
6558 break;
6559 }
6560
6561 if (BaseIt == BaseE) {
6562 // Did not find SourceType in the bases.
6563 Diag(UD->getUsingLocation(),
6564 diag::err_using_decl_constructor_not_in_direct_base)
6565 << UD->getNameInfo().getSourceRange()
6566 << QualType(SourceType, 0) << TargetClass;
6567 return true;
6568 }
6569
6570 BaseIt->setInheritConstructors();
6571
6572 return false;
6573}
6574
John McCall9f54ad42009-12-10 09:41:52 +00006575/// Checks that the given using declaration is not an invalid
6576/// redeclaration. Note that this is checking only for the using decl
6577/// itself, not for any ill-formedness among the UsingShadowDecls.
6578bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6579 bool isTypeName,
6580 const CXXScopeSpec &SS,
6581 SourceLocation NameLoc,
6582 const LookupResult &Prev) {
6583 // C++03 [namespace.udecl]p8:
6584 // C++0x [namespace.udecl]p10:
6585 // A using-declaration is a declaration and can therefore be used
6586 // repeatedly where (and only where) multiple declarations are
6587 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006588 //
John McCall8a726212010-11-29 18:01:58 +00006589 // That's in non-member contexts.
6590 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006591 return false;
6592
6593 NestedNameSpecifier *Qual
6594 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6595
6596 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6597 NamedDecl *D = *I;
6598
6599 bool DTypename;
6600 NestedNameSpecifier *DQual;
6601 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6602 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006603 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006604 } else if (UnresolvedUsingValueDecl *UD
6605 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6606 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006607 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006608 } else if (UnresolvedUsingTypenameDecl *UD
6609 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6610 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006611 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006612 } else continue;
6613
6614 // using decls differ if one says 'typename' and the other doesn't.
6615 // FIXME: non-dependent using decls?
6616 if (isTypeName != DTypename) continue;
6617
6618 // using decls differ if they name different scopes (but note that
6619 // template instantiation can cause this check to trigger when it
6620 // didn't before instantiation).
6621 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6622 Context.getCanonicalNestedNameSpecifier(DQual))
6623 continue;
6624
6625 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006626 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006627 return true;
6628 }
6629
6630 return false;
6631}
6632
John McCall604e7f12009-12-08 07:46:18 +00006633
John McCalled976492009-12-04 22:46:56 +00006634/// Checks that the given nested-name qualifier used in a using decl
6635/// in the current context is appropriately related to the current
6636/// scope. If an error is found, diagnoses it and returns true.
6637bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6638 const CXXScopeSpec &SS,
6639 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006640 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006641
John McCall604e7f12009-12-08 07:46:18 +00006642 if (!CurContext->isRecord()) {
6643 // C++03 [namespace.udecl]p3:
6644 // C++0x [namespace.udecl]p8:
6645 // A using-declaration for a class member shall be a member-declaration.
6646
6647 // If we weren't able to compute a valid scope, it must be a
6648 // dependent class scope.
6649 if (!NamedContext || NamedContext->isRecord()) {
6650 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6651 << SS.getRange();
6652 return true;
6653 }
6654
6655 // Otherwise, everything is known to be fine.
6656 return false;
6657 }
6658
6659 // The current scope is a record.
6660
6661 // If the named context is dependent, we can't decide much.
6662 if (!NamedContext) {
6663 // FIXME: in C++0x, we can diagnose if we can prove that the
6664 // nested-name-specifier does not refer to a base class, which is
6665 // still possible in some cases.
6666
6667 // Otherwise we have to conservatively report that things might be
6668 // okay.
6669 return false;
6670 }
6671
6672 if (!NamedContext->isRecord()) {
6673 // Ideally this would point at the last name in the specifier,
6674 // but we don't have that level of source info.
6675 Diag(SS.getRange().getBegin(),
6676 diag::err_using_decl_nested_name_specifier_is_not_class)
6677 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6678 return true;
6679 }
6680
Douglas Gregor6fb07292010-12-21 07:41:49 +00006681 if (!NamedContext->isDependentContext() &&
6682 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6683 return true;
6684
John McCall604e7f12009-12-08 07:46:18 +00006685 if (getLangOptions().CPlusPlus0x) {
6686 // C++0x [namespace.udecl]p3:
6687 // In a using-declaration used as a member-declaration, the
6688 // nested-name-specifier shall name a base class of the class
6689 // being defined.
6690
6691 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6692 cast<CXXRecordDecl>(NamedContext))) {
6693 if (CurContext == NamedContext) {
6694 Diag(NameLoc,
6695 diag::err_using_decl_nested_name_specifier_is_current_class)
6696 << SS.getRange();
6697 return true;
6698 }
6699
6700 Diag(SS.getRange().getBegin(),
6701 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6702 << (NestedNameSpecifier*) SS.getScopeRep()
6703 << cast<CXXRecordDecl>(CurContext)
6704 << SS.getRange();
6705 return true;
6706 }
6707
6708 return false;
6709 }
6710
6711 // C++03 [namespace.udecl]p4:
6712 // A using-declaration used as a member-declaration shall refer
6713 // to a member of a base class of the class being defined [etc.].
6714
6715 // Salient point: SS doesn't have to name a base class as long as
6716 // lookup only finds members from base classes. Therefore we can
6717 // diagnose here only if we can prove that that can't happen,
6718 // i.e. if the class hierarchies provably don't intersect.
6719
6720 // TODO: it would be nice if "definitely valid" results were cached
6721 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6722 // need to be repeated.
6723
6724 struct UserData {
6725 llvm::DenseSet<const CXXRecordDecl*> Bases;
6726
6727 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6728 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6729 Data->Bases.insert(Base);
6730 return true;
6731 }
6732
6733 bool hasDependentBases(const CXXRecordDecl *Class) {
6734 return !Class->forallBases(collect, this);
6735 }
6736
6737 /// Returns true if the base is dependent or is one of the
6738 /// accumulated base classes.
6739 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6740 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6741 return !Data->Bases.count(Base);
6742 }
6743
6744 bool mightShareBases(const CXXRecordDecl *Class) {
6745 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6746 }
6747 };
6748
6749 UserData Data;
6750
6751 // Returns false if we find a dependent base.
6752 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6753 return false;
6754
6755 // Returns false if the class has a dependent base or if it or one
6756 // of its bases is present in the base set of the current context.
6757 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6758 return false;
6759
6760 Diag(SS.getRange().getBegin(),
6761 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6762 << (NestedNameSpecifier*) SS.getScopeRep()
6763 << cast<CXXRecordDecl>(CurContext)
6764 << SS.getRange();
6765
6766 return true;
John McCalled976492009-12-04 22:46:56 +00006767}
6768
Richard Smith162e1c12011-04-15 14:24:37 +00006769Decl *Sema::ActOnAliasDeclaration(Scope *S,
6770 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006771 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006772 SourceLocation UsingLoc,
6773 UnqualifiedId &Name,
6774 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006775 // Skip up to the relevant declaration scope.
6776 while (S->getFlags() & Scope::TemplateParamScope)
6777 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006778 assert((S->getFlags() & Scope::DeclScope) &&
6779 "got alias-declaration outside of declaration scope");
6780
6781 if (Type.isInvalid())
6782 return 0;
6783
6784 bool Invalid = false;
6785 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6786 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006787 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006788
6789 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6790 return 0;
6791
6792 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006793 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006794 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006795 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6796 TInfo->getTypeLoc().getBeginLoc());
6797 }
Richard Smith162e1c12011-04-15 14:24:37 +00006798
6799 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6800 LookupName(Previous, S);
6801
6802 // Warn about shadowing the name of a template parameter.
6803 if (Previous.isSingleResult() &&
6804 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006805 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006806 Previous.clear();
6807 }
6808
6809 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6810 "name in alias declaration must be an identifier");
6811 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6812 Name.StartLocation,
6813 Name.Identifier, TInfo);
6814
6815 NewTD->setAccess(AS);
6816
6817 if (Invalid)
6818 NewTD->setInvalidDecl();
6819
Richard Smith3e4c6c42011-05-05 21:57:07 +00006820 CheckTypedefForVariablyModifiedType(S, NewTD);
6821 Invalid |= NewTD->isInvalidDecl();
6822
Richard Smith162e1c12011-04-15 14:24:37 +00006823 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006824
6825 NamedDecl *NewND;
6826 if (TemplateParamLists.size()) {
6827 TypeAliasTemplateDecl *OldDecl = 0;
6828 TemplateParameterList *OldTemplateParams = 0;
6829
6830 if (TemplateParamLists.size() != 1) {
6831 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6832 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6833 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6834 }
6835 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6836
6837 // Only consider previous declarations in the same scope.
6838 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6839 /*ExplicitInstantiationOrSpecialization*/false);
6840 if (!Previous.empty()) {
6841 Redeclaration = true;
6842
6843 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6844 if (!OldDecl && !Invalid) {
6845 Diag(UsingLoc, diag::err_redefinition_different_kind)
6846 << Name.Identifier;
6847
6848 NamedDecl *OldD = Previous.getRepresentativeDecl();
6849 if (OldD->getLocation().isValid())
6850 Diag(OldD->getLocation(), diag::note_previous_definition);
6851
6852 Invalid = true;
6853 }
6854
6855 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6856 if (TemplateParameterListsAreEqual(TemplateParams,
6857 OldDecl->getTemplateParameters(),
6858 /*Complain=*/true,
6859 TPL_TemplateMatch))
6860 OldTemplateParams = OldDecl->getTemplateParameters();
6861 else
6862 Invalid = true;
6863
6864 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6865 if (!Invalid &&
6866 !Context.hasSameType(OldTD->getUnderlyingType(),
6867 NewTD->getUnderlyingType())) {
6868 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6869 // but we can't reasonably accept it.
6870 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6871 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6872 if (OldTD->getLocation().isValid())
6873 Diag(OldTD->getLocation(), diag::note_previous_definition);
6874 Invalid = true;
6875 }
6876 }
6877 }
6878
6879 // Merge any previous default template arguments into our parameters,
6880 // and check the parameter list.
6881 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6882 TPC_TypeAliasTemplate))
6883 return 0;
6884
6885 TypeAliasTemplateDecl *NewDecl =
6886 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6887 Name.Identifier, TemplateParams,
6888 NewTD);
6889
6890 NewDecl->setAccess(AS);
6891
6892 if (Invalid)
6893 NewDecl->setInvalidDecl();
6894 else if (OldDecl)
6895 NewDecl->setPreviousDeclaration(OldDecl);
6896
6897 NewND = NewDecl;
6898 } else {
6899 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6900 NewND = NewTD;
6901 }
Richard Smith162e1c12011-04-15 14:24:37 +00006902
6903 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006904 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006905
Richard Smith3e4c6c42011-05-05 21:57:07 +00006906 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006907}
6908
John McCalld226f652010-08-21 09:40:31 +00006909Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006910 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006911 SourceLocation AliasLoc,
6912 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006913 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006914 SourceLocation IdentLoc,
6915 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006916
Anders Carlsson81c85c42009-03-28 23:53:49 +00006917 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006918 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6919 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006920
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006921 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006922 NamedDecl *PrevDecl
6923 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6924 ForRedeclaration);
6925 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6926 PrevDecl = 0;
6927
6928 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006929 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006930 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006931 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006932 // FIXME: At some point, we'll want to create the (redundant)
6933 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006934 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006935 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006936 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006937 }
Mike Stump1eb44332009-09-09 15:08:12 +00006938
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006939 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6940 diag::err_redefinition_different_kind;
6941 Diag(AliasLoc, DiagID) << Alias;
6942 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006943 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006944 }
6945
John McCalla24dc2e2009-11-17 02:14:36 +00006946 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006947 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006948
John McCallf36e02d2009-10-09 21:13:30 +00006949 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006950 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006951 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006952 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006953 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006954 }
Mike Stump1eb44332009-09-09 15:08:12 +00006955
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006956 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006957 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006958 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006959 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006960
John McCall3dbd3d52010-02-16 06:53:13 +00006961 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006962 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006963}
6964
Douglas Gregor39957dc2010-05-01 15:04:51 +00006965namespace {
6966 /// \brief Scoped object used to handle the state changes required in Sema
6967 /// to implicitly define the body of a C++ member function;
6968 class ImplicitlyDefinedFunctionScope {
6969 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006970 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006971
6972 public:
6973 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006974 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006975 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006976 S.PushFunctionScope();
6977 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6978 }
6979
6980 ~ImplicitlyDefinedFunctionScope() {
6981 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006982 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006983 }
6984 };
6985}
6986
Sean Hunt001cad92011-05-10 00:49:42 +00006987Sema::ImplicitExceptionSpecification
6988Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006989 // C++ [except.spec]p14:
6990 // An implicitly declared special member function (Clause 12) shall have an
6991 // exception-specification. [...]
6992 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006993 if (ClassDecl->isInvalidDecl())
6994 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006995
Sebastian Redl60618fa2011-03-12 11:50:43 +00006996 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006997 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6998 BEnd = ClassDecl->bases_end();
6999 B != BEnd; ++B) {
7000 if (B->isVirtual()) // Handled below.
7001 continue;
7002
Douglas Gregor18274032010-07-03 00:47:00 +00007003 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7004 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007005 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7006 // If this is a deleted function, add it anyway. This might be conformant
7007 // with the standard. This might not. I'm not sure. It might not matter.
7008 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007009 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007010 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007011 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007012
7013 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007014 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7015 BEnd = ClassDecl->vbases_end();
7016 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007017 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7018 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007019 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7020 // If this is a deleted function, add it anyway. This might be conformant
7021 // with the standard. This might not. I'm not sure. It might not matter.
7022 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007023 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007024 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007025 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007026
7027 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007028 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7029 FEnd = ClassDecl->field_end();
7030 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007031 if (F->hasInClassInitializer()) {
7032 if (Expr *E = F->getInClassInitializer())
7033 ExceptSpec.CalledExpr(E);
7034 else if (!F->isInvalidDecl())
7035 ExceptSpec.SetDelayed();
7036 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007037 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007038 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7039 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7040 // If this is a deleted function, add it anyway. This might be conformant
7041 // with the standard. This might not. I'm not sure. It might not matter.
7042 // In particular, the problem is that this function never gets called. It
7043 // might just be ill-formed because this function attempts to refer to
7044 // a deleted function here.
7045 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007046 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007047 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007048 }
John McCalle23cf432010-12-14 08:05:40 +00007049
Sean Hunt001cad92011-05-10 00:49:42 +00007050 return ExceptSpec;
7051}
7052
7053CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7054 CXXRecordDecl *ClassDecl) {
7055 // C++ [class.ctor]p5:
7056 // A default constructor for a class X is a constructor of class X
7057 // that can be called without an argument. If there is no
7058 // user-declared constructor for class X, a default constructor is
7059 // implicitly declared. An implicitly-declared default constructor
7060 // is an inline public member of its class.
7061 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7062 "Should not build implicit default constructor!");
7063
7064 ImplicitExceptionSpecification Spec =
7065 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7066 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00007067
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007068 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007069 CanQualType ClassType
7070 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007071 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007072 DeclarationName Name
7073 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007074 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007075 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7076 Context, ClassDecl, ClassLoc, NameInfo,
7077 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7078 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7079 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7080 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007081 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007082 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007083 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00007084 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00007085
7086 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007087 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7088
Douglas Gregor23c94db2010-07-02 17:43:08 +00007089 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007090 PushOnScopeChains(DefaultCon, S, false);
7091 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007092
Sean Hunte16da072011-10-10 06:18:57 +00007093 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007094 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00007095
Douglas Gregor32df23e2010-07-01 22:02:46 +00007096 return DefaultCon;
7097}
7098
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007099void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7100 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007101 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007102 !Constructor->doesThisDeclarationHaveABody() &&
7103 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007104 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007105
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007106 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007107 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007108
Douglas Gregor39957dc2010-05-01 15:04:51 +00007109 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007110 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007111 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007112 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007113 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007114 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007115 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007116 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007117 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007118
7119 SourceLocation Loc = Constructor->getLocation();
7120 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7121
7122 Constructor->setUsed();
7123 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007124
7125 if (ASTMutationListener *L = getASTMutationListener()) {
7126 L->CompletedImplicitDefinition(Constructor);
7127 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007128}
7129
Richard Smith7a614d82011-06-11 17:19:42 +00007130/// Get any existing defaulted default constructor for the given class. Do not
7131/// implicitly define one if it does not exist.
7132static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7133 CXXRecordDecl *D) {
7134 ASTContext &Context = Self.Context;
7135 QualType ClassType = Context.getTypeDeclType(D);
7136 DeclarationName ConstructorName
7137 = Context.DeclarationNames.getCXXConstructorName(
7138 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7139
7140 DeclContext::lookup_const_iterator Con, ConEnd;
7141 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7142 Con != ConEnd; ++Con) {
7143 // A function template cannot be defaulted.
7144 if (isa<FunctionTemplateDecl>(*Con))
7145 continue;
7146
7147 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7148 if (Constructor->isDefaultConstructor())
7149 return Constructor->isDefaulted() ? Constructor : 0;
7150 }
7151 return 0;
7152}
7153
7154void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7155 if (!D) return;
7156 AdjustDeclIfTemplate(D);
7157
7158 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7159 CXXConstructorDecl *CtorDecl
7160 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7161
7162 if (!CtorDecl) return;
7163
7164 // Compute the exception specification for the default constructor.
7165 const FunctionProtoType *CtorTy =
7166 CtorDecl->getType()->castAs<FunctionProtoType>();
7167 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7168 ImplicitExceptionSpecification Spec =
7169 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7170 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7171 assert(EPI.ExceptionSpecType != EST_Delayed);
7172
7173 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7174 }
7175
7176 // If the default constructor is explicitly defaulted, checking the exception
7177 // specification is deferred until now.
7178 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7179 !ClassDecl->isDependentType())
7180 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7181}
7182
Sebastian Redlf677ea32011-02-05 19:23:19 +00007183void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7184 // We start with an initial pass over the base classes to collect those that
7185 // inherit constructors from. If there are none, we can forgo all further
7186 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007187 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007188 BasesVector BasesToInheritFrom;
7189 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7190 BaseE = ClassDecl->bases_end();
7191 BaseIt != BaseE; ++BaseIt) {
7192 if (BaseIt->getInheritConstructors()) {
7193 QualType Base = BaseIt->getType();
7194 if (Base->isDependentType()) {
7195 // If we inherit constructors from anything that is dependent, just
7196 // abort processing altogether. We'll get another chance for the
7197 // instantiations.
7198 return;
7199 }
7200 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7201 }
7202 }
7203 if (BasesToInheritFrom.empty())
7204 return;
7205
7206 // Now collect the constructors that we already have in the current class.
7207 // Those take precedence over inherited constructors.
7208 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7209 // unless there is a user-declared constructor with the same signature in
7210 // the class where the using-declaration appears.
7211 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7212 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7213 CtorE = ClassDecl->ctor_end();
7214 CtorIt != CtorE; ++CtorIt) {
7215 ExistingConstructors.insert(
7216 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7217 }
7218
7219 Scope *S = getScopeForContext(ClassDecl);
7220 DeclarationName CreatedCtorName =
7221 Context.DeclarationNames.getCXXConstructorName(
7222 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7223
7224 // Now comes the true work.
7225 // First, we keep a map from constructor types to the base that introduced
7226 // them. Needed for finding conflicting constructors. We also keep the
7227 // actually inserted declarations in there, for pretty diagnostics.
7228 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7229 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7230 ConstructorToSourceMap InheritedConstructors;
7231 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7232 BaseE = BasesToInheritFrom.end();
7233 BaseIt != BaseE; ++BaseIt) {
7234 const RecordType *Base = *BaseIt;
7235 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7236 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7237 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7238 CtorE = BaseDecl->ctor_end();
7239 CtorIt != CtorE; ++CtorIt) {
7240 // Find the using declaration for inheriting this base's constructors.
7241 DeclarationName Name =
7242 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7243 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7244 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7245 SourceLocation UsingLoc = UD ? UD->getLocation() :
7246 ClassDecl->getLocation();
7247
7248 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7249 // from the class X named in the using-declaration consists of actual
7250 // constructors and notional constructors that result from the
7251 // transformation of defaulted parameters as follows:
7252 // - all non-template default constructors of X, and
7253 // - for each non-template constructor of X that has at least one
7254 // parameter with a default argument, the set of constructors that
7255 // results from omitting any ellipsis parameter specification and
7256 // successively omitting parameters with a default argument from the
7257 // end of the parameter-type-list.
7258 CXXConstructorDecl *BaseCtor = *CtorIt;
7259 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7260 const FunctionProtoType *BaseCtorType =
7261 BaseCtor->getType()->getAs<FunctionProtoType>();
7262
7263 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7264 maxParams = BaseCtor->getNumParams();
7265 params <= maxParams; ++params) {
7266 // Skip default constructors. They're never inherited.
7267 if (params == 0)
7268 continue;
7269 // Skip copy and move constructors for the same reason.
7270 if (CanBeCopyOrMove && params == 1)
7271 continue;
7272
7273 // Build up a function type for this particular constructor.
7274 // FIXME: The working paper does not consider that the exception spec
7275 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007276 // source. This code doesn't yet, either. When it does, this code will
7277 // need to be delayed until after exception specifications and in-class
7278 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007279 const Type *NewCtorType;
7280 if (params == maxParams)
7281 NewCtorType = BaseCtorType;
7282 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007283 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007284 for (unsigned i = 0; i < params; ++i) {
7285 Args.push_back(BaseCtorType->getArgType(i));
7286 }
7287 FunctionProtoType::ExtProtoInfo ExtInfo =
7288 BaseCtorType->getExtProtoInfo();
7289 ExtInfo.Variadic = false;
7290 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7291 Args.data(), params, ExtInfo)
7292 .getTypePtr();
7293 }
7294 const Type *CanonicalNewCtorType =
7295 Context.getCanonicalType(NewCtorType);
7296
7297 // Now that we have the type, first check if the class already has a
7298 // constructor with this signature.
7299 if (ExistingConstructors.count(CanonicalNewCtorType))
7300 continue;
7301
7302 // Then we check if we have already declared an inherited constructor
7303 // with this signature.
7304 std::pair<ConstructorToSourceMap::iterator, bool> result =
7305 InheritedConstructors.insert(std::make_pair(
7306 CanonicalNewCtorType,
7307 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7308 if (!result.second) {
7309 // Already in the map. If it came from a different class, that's an
7310 // error. Not if it's from the same.
7311 CanQualType PreviousBase = result.first->second.first;
7312 if (CanonicalBase != PreviousBase) {
7313 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7314 const CXXConstructorDecl *PrevBaseCtor =
7315 PrevCtor->getInheritedConstructor();
7316 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7317
7318 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7319 Diag(BaseCtor->getLocation(),
7320 diag::note_using_decl_constructor_conflict_current_ctor);
7321 Diag(PrevBaseCtor->getLocation(),
7322 diag::note_using_decl_constructor_conflict_previous_ctor);
7323 Diag(PrevCtor->getLocation(),
7324 diag::note_using_decl_constructor_conflict_previous_using);
7325 }
7326 continue;
7327 }
7328
7329 // OK, we're there, now add the constructor.
7330 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007331 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007332 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7333 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007334 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7335 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007336 /*ImplicitlyDeclared=*/true,
7337 // FIXME: Due to a defect in the standard, we treat inherited
7338 // constructors as constexpr even if that makes them ill-formed.
7339 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007340 NewCtor->setAccess(BaseCtor->getAccess());
7341
7342 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007343 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007344 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007345 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7346 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007347 /*IdentifierInfo=*/0,
7348 BaseCtorType->getArgType(i),
7349 /*TInfo=*/0, SC_None,
7350 SC_None, /*DefaultArg=*/0));
7351 }
David Blaikie4278c652011-09-21 18:16:56 +00007352 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007353 NewCtor->setInheritedConstructor(BaseCtor);
7354
7355 PushOnScopeChains(NewCtor, S, false);
7356 ClassDecl->addDecl(NewCtor);
7357 result.first->second.second = NewCtor;
7358 }
7359 }
7360 }
7361}
7362
Sean Huntcb45a0f2011-05-12 22:46:25 +00007363Sema::ImplicitExceptionSpecification
7364Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007365 // C++ [except.spec]p14:
7366 // An implicitly declared special member function (Clause 12) shall have
7367 // an exception-specification.
7368 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007369 if (ClassDecl->isInvalidDecl())
7370 return ExceptSpec;
7371
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007372 // Direct base-class destructors.
7373 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7374 BEnd = ClassDecl->bases_end();
7375 B != BEnd; ++B) {
7376 if (B->isVirtual()) // Handled below.
7377 continue;
7378
7379 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7380 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007381 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007382 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007383
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007384 // Virtual base-class destructors.
7385 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7386 BEnd = ClassDecl->vbases_end();
7387 B != BEnd; ++B) {
7388 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7389 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007390 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007391 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007392
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007393 // Field destructors.
7394 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7395 FEnd = ClassDecl->field_end();
7396 F != FEnd; ++F) {
7397 if (const RecordType *RecordTy
7398 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7399 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007400 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007401 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007402
Sean Huntcb45a0f2011-05-12 22:46:25 +00007403 return ExceptSpec;
7404}
7405
7406CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7407 // C++ [class.dtor]p2:
7408 // If a class has no user-declared destructor, a destructor is
7409 // declared implicitly. An implicitly-declared destructor is an
7410 // inline public member of its class.
7411
7412 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007413 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007414 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7415
Douglas Gregor4923aa22010-07-02 20:37:36 +00007416 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007417 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007418
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007419 CanQualType ClassType
7420 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007421 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007422 DeclarationName Name
7423 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007424 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007425 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007426 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7427 /*isInline=*/true,
7428 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007429 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007430 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007431 Destructor->setImplicit();
7432 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007433
7434 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007435 ++ASTContext::NumImplicitDestructorsDeclared;
7436
7437 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007438 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007439 PushOnScopeChains(Destructor, S, false);
7440 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007441
7442 // This could be uniqued if it ever proves significant.
7443 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007444
7445 if (ShouldDeleteDestructor(Destructor))
7446 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007447
7448 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007449
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007450 return Destructor;
7451}
7452
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007453void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007454 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007455 assert((Destructor->isDefaulted() &&
7456 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007457 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007458 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007459 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007460
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007461 if (Destructor->isInvalidDecl())
7462 return;
7463
Douglas Gregor39957dc2010-05-01 15:04:51 +00007464 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007465
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007466 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007467 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7468 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007469
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007470 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007471 Diag(CurrentLocation, diag::note_member_synthesized_at)
7472 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7473
7474 Destructor->setInvalidDecl();
7475 return;
7476 }
7477
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007478 SourceLocation Loc = Destructor->getLocation();
7479 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007480 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007481 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007482 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007483
7484 if (ASTMutationListener *L = getASTMutationListener()) {
7485 L->CompletedImplicitDefinition(Destructor);
7486 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007487}
7488
Sebastian Redl0ee33912011-05-19 05:13:44 +00007489void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7490 CXXDestructorDecl *destructor) {
7491 // C++11 [class.dtor]p3:
7492 // A declaration of a destructor that does not have an exception-
7493 // specification is implicitly considered to have the same exception-
7494 // specification as an implicit declaration.
7495 const FunctionProtoType *dtorType = destructor->getType()->
7496 getAs<FunctionProtoType>();
7497 if (dtorType->hasExceptionSpec())
7498 return;
7499
7500 ImplicitExceptionSpecification exceptSpec =
7501 ComputeDefaultedDtorExceptionSpec(classDecl);
7502
Chandler Carruth3f224b22011-09-20 04:55:26 +00007503 // Replace the destructor's type, building off the existing one. Fortunately,
7504 // the only thing of interest in the destructor type is its extended info.
7505 // The return and arguments are fixed.
7506 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007507 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7508 epi.NumExceptions = exceptSpec.size();
7509 epi.Exceptions = exceptSpec.data();
7510 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7511
7512 destructor->setType(ty);
7513
7514 // FIXME: If the destructor has a body that could throw, and the newly created
7515 // spec doesn't allow exceptions, we should emit a warning, because this
7516 // change in behavior can break conforming C++03 programs at runtime.
7517 // However, we don't have a body yet, so it needs to be done somewhere else.
7518}
7519
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007520/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007521/// \c To.
7522///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007523/// This routine is used to copy/move the members of a class with an
7524/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007525/// copied are arrays, this routine builds for loops to copy them.
7526///
7527/// \param S The Sema object used for type-checking.
7528///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007529/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007530///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007531/// \param T The type of the expressions being copied/moved. Both expressions
7532/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007533///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007534/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007535///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007536/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007537///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007538/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007539/// Otherwise, it's a non-static member subobject.
7540///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007541/// \param Copying Whether we're copying or moving.
7542///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007543/// \param Depth Internal parameter recording the depth of the recursion.
7544///
7545/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007546static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007547BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007548 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007549 bool CopyingBaseSubobject, bool Copying,
7550 unsigned Depth = 0) {
7551 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007552 // Each subobject is assigned in the manner appropriate to its type:
7553 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007554 // - if the subobject is of class type, as if by a call to operator= with
7555 // the subobject as the object expression and the corresponding
7556 // subobject of x as a single function argument (as if by explicit
7557 // qualification; that is, ignoring any possible virtual overriding
7558 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007559 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7560 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7561
7562 // Look for operator=.
7563 DeclarationName Name
7564 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7565 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7566 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7567
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007568 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007569 LookupResult::Filter F = OpLookup.makeFilter();
7570 while (F.hasNext()) {
7571 NamedDecl *D = F.next();
7572 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007573 if (Copying ? Method->isCopyAssignmentOperator() :
7574 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007575 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007576
Douglas Gregor06a9f362010-05-01 20:49:11 +00007577 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007578 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007579 F.done();
7580
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007581 // Suppress the protected check (C++ [class.protected]) for each of the
7582 // assignment operators we found. This strange dance is required when
7583 // we're assigning via a base classes's copy-assignment operator. To
7584 // ensure that we're getting the right base class subobject (without
7585 // ambiguities), we need to cast "this" to that subobject type; to
7586 // ensure that we don't go through the virtual call mechanism, we need
7587 // to qualify the operator= name with the base class (see below). However,
7588 // this means that if the base class has a protected copy assignment
7589 // operator, the protected member access check will fail. So, we
7590 // rewrite "protected" access to "public" access in this case, since we
7591 // know by construction that we're calling from a derived class.
7592 if (CopyingBaseSubobject) {
7593 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7594 L != LEnd; ++L) {
7595 if (L.getAccess() == AS_protected)
7596 L.setAccess(AS_public);
7597 }
7598 }
7599
Douglas Gregor06a9f362010-05-01 20:49:11 +00007600 // Create the nested-name-specifier that will be used to qualify the
7601 // reference to operator=; this is required to suppress the virtual
7602 // call mechanism.
7603 CXXScopeSpec SS;
Douglas Gregorc34348a2011-02-24 17:54:50 +00007604 SS.MakeTrivial(S.Context,
7605 NestedNameSpecifier::Create(S.Context, 0, false,
7606 T.getTypePtr()),
7607 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007608
7609 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007610 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007611 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007612 /*TemplateKWLoc=*/SourceLocation(),
7613 /*FirstQualifierInScope=*/0,
7614 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007615 /*TemplateArgs=*/0,
7616 /*SuppressQualifierCheck=*/true);
7617 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007618 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007619
7620 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007621
John McCall60d7b3a2010-08-24 06:29:42 +00007622 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007623 OpEqualRef.takeAs<Expr>(),
7624 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007625 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007626 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007627
7628 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007629 }
John McCallb0207482010-03-16 06:11:48 +00007630
Douglas Gregor06a9f362010-05-01 20:49:11 +00007631 // - if the subobject is of scalar type, the built-in assignment
7632 // operator is used.
7633 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7634 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007635 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007636 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007637 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007638
7639 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007640 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007641
7642 // - if the subobject is an array, each element is assigned, in the
7643 // manner appropriate to the element type;
7644
7645 // Construct a loop over the array bounds, e.g.,
7646 //
7647 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7648 //
7649 // that will copy each of the array elements.
7650 QualType SizeType = S.Context.getSizeType();
7651
7652 // Create the iteration variable.
7653 IdentifierInfo *IterationVarName = 0;
7654 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007655 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007656 llvm::raw_svector_ostream OS(Str);
7657 OS << "__i" << Depth;
7658 IterationVarName = &S.Context.Idents.get(OS.str());
7659 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007660 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007661 IterationVarName, SizeType,
7662 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007663 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007664
7665 // Initialize the iteration variable to zero.
7666 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007667 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007668
7669 // Create a reference to the iteration variable; we'll use this several
7670 // times throughout.
7671 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007672 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007673 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007674 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7675 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7676
Douglas Gregor06a9f362010-05-01 20:49:11 +00007677 // Create the DeclStmt that holds the iteration variable.
7678 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7679
7680 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007681 llvm::APInt Upper
7682 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007683 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007684 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007685 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7686 BO_NE, S.Context.BoolTy,
7687 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007688
7689 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007690 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007691 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7692 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007693
7694 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007695 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007696 IterationVarRefRVal,
7697 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007698 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007699 IterationVarRefRVal,
7700 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007701 if (!Copying) // Cast to rvalue
7702 From = CastForMoving(S, From);
7703
7704 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007705 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7706 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007707 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007708 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007709 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007710
7711 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007712 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007713 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007714 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007715 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007716}
7717
Sean Hunt30de05c2011-05-14 05:23:20 +00007718std::pair<Sema::ImplicitExceptionSpecification, bool>
7719Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7720 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007721 if (ClassDecl->isInvalidDecl())
7722 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7723
Douglas Gregord3c35902010-07-01 16:36:15 +00007724 // C++ [class.copy]p10:
7725 // If the class definition does not explicitly declare a copy
7726 // assignment operator, one is declared implicitly.
7727 // The implicitly-defined copy assignment operator for a class X
7728 // will have the form
7729 //
7730 // X& X::operator=(const X&)
7731 //
7732 // if
7733 bool HasConstCopyAssignment = true;
7734
7735 // -- each direct base class B of X has a copy assignment operator
7736 // whose parameter is of type const B&, const volatile B& or B,
7737 // and
7738 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7739 BaseEnd = ClassDecl->bases_end();
7740 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007741 // We'll handle this below
7742 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7743 continue;
7744
Douglas Gregord3c35902010-07-01 16:36:15 +00007745 assert(!Base->getType()->isDependentType() &&
7746 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007747 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7748 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7749 &HasConstCopyAssignment);
7750 }
7751
Richard Smithebaf0e62011-10-18 20:49:44 +00007752 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007753 if (LangOpts.CPlusPlus0x) {
7754 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7755 BaseEnd = ClassDecl->vbases_end();
7756 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7757 assert(!Base->getType()->isDependentType() &&
7758 "Cannot generate implicit members for class with dependent bases.");
7759 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7760 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7761 &HasConstCopyAssignment);
7762 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007763 }
7764
7765 // -- for all the nonstatic data members of X that are of a class
7766 // type M (or array thereof), each such class type has a copy
7767 // assignment operator whose parameter is of type const M&,
7768 // const volatile M& or M.
7769 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7770 FieldEnd = ClassDecl->field_end();
7771 HasConstCopyAssignment && Field != FieldEnd;
7772 ++Field) {
7773 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007774 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7775 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7776 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007777 }
7778 }
7779
7780 // Otherwise, the implicitly declared copy assignment operator will
7781 // have the form
7782 //
7783 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007784
Douglas Gregorb87786f2010-07-01 17:48:08 +00007785 // C++ [except.spec]p14:
7786 // An implicitly declared special member function (Clause 12) shall have an
7787 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007788
7789 // It is unspecified whether or not an implicit copy assignment operator
7790 // attempts to deduplicate calls to assignment operators of virtual bases are
7791 // made. As such, this exception specification is effectively unspecified.
7792 // Based on a similar decision made for constness in C++0x, we're erring on
7793 // the side of assuming such calls to be made regardless of whether they
7794 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007795 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007796 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007797 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7798 BaseEnd = ClassDecl->bases_end();
7799 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007800 if (Base->isVirtual())
7801 continue;
7802
Douglas Gregora376d102010-07-02 21:50:04 +00007803 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007804 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007805 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7806 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007807 ExceptSpec.CalledDecl(CopyAssign);
7808 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007809
7810 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7811 BaseEnd = ClassDecl->vbases_end();
7812 Base != BaseEnd; ++Base) {
7813 CXXRecordDecl *BaseClassDecl
7814 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7815 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7816 ArgQuals, false, 0))
7817 ExceptSpec.CalledDecl(CopyAssign);
7818 }
7819
Douglas Gregorb87786f2010-07-01 17:48:08 +00007820 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7821 FieldEnd = ClassDecl->field_end();
7822 Field != FieldEnd;
7823 ++Field) {
7824 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007825 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7826 if (CXXMethodDecl *CopyAssign =
7827 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7828 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007829 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007830 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007831
Sean Hunt30de05c2011-05-14 05:23:20 +00007832 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7833}
7834
7835CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7836 // Note: The following rules are largely analoguous to the copy
7837 // constructor rules. Note that virtual bases are not taken into account
7838 // for determining the argument type of the operator. Note also that
7839 // operators taking an object instead of a reference are allowed.
7840
7841 ImplicitExceptionSpecification Spec(Context);
7842 bool Const;
7843 llvm::tie(Spec, Const) =
7844 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7845
7846 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7847 QualType RetType = Context.getLValueReferenceType(ArgType);
7848 if (Const)
7849 ArgType = ArgType.withConst();
7850 ArgType = Context.getLValueReferenceType(ArgType);
7851
Douglas Gregord3c35902010-07-01 16:36:15 +00007852 // An implicitly-declared copy assignment operator is an inline public
7853 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007854 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007855 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007856 SourceLocation ClassLoc = ClassDecl->getLocation();
7857 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007858 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007859 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007860 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007861 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007862 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007863 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007864 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007865 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007866 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007867 CopyAssignment->setImplicit();
7868 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007869
7870 // Add the parameter to the operator.
7871 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007872 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007873 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007874 SC_None,
7875 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007876 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007877
Douglas Gregora376d102010-07-02 21:50:04 +00007878 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007879 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007880
Douglas Gregor23c94db2010-07-02 17:43:08 +00007881 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007882 PushOnScopeChains(CopyAssignment, S, false);
7883 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007884
Nico Weberafcc96a2012-01-23 03:19:29 +00007885 // C++0x [class.copy]p19:
7886 // .... If the class definition does not explicitly declare a copy
7887 // assignment operator, there is no user-declared move constructor, and
7888 // there is no user-declared move assignment operator, a copy assignment
7889 // operator is implicitly declared as defaulted.
7890 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber28976602012-01-23 04:01:33 +00007891 !getLangOptions().MicrosoftMode) ||
7892 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Hunt1ccbc542011-06-22 01:05:13 +00007893 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007894 CopyAssignment->setDeletedAsWritten();
7895
Douglas Gregord3c35902010-07-01 16:36:15 +00007896 AddOverriddenMethods(ClassDecl, CopyAssignment);
7897 return CopyAssignment;
7898}
7899
Douglas Gregor06a9f362010-05-01 20:49:11 +00007900void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7901 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007902 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007903 CopyAssignOperator->isOverloadedOperator() &&
7904 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007905 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007906 "DefineImplicitCopyAssignment called for wrong function");
7907
7908 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7909
7910 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7911 CopyAssignOperator->setInvalidDecl();
7912 return;
7913 }
7914
7915 CopyAssignOperator->setUsed();
7916
7917 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007918 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007919
7920 // C++0x [class.copy]p30:
7921 // The implicitly-defined or explicitly-defaulted copy assignment operator
7922 // for a non-union class X performs memberwise copy assignment of its
7923 // subobjects. The direct base classes of X are assigned first, in the
7924 // order of their declaration in the base-specifier-list, and then the
7925 // immediate non-static data members of X are assigned, in the order in
7926 // which they were declared in the class definition.
7927
7928 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007929 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007930
7931 // The parameter for the "other" object, which we are copying from.
7932 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7933 Qualifiers OtherQuals = Other->getType().getQualifiers();
7934 QualType OtherRefType = Other->getType();
7935 if (const LValueReferenceType *OtherRef
7936 = OtherRefType->getAs<LValueReferenceType>()) {
7937 OtherRefType = OtherRef->getPointeeType();
7938 OtherQuals = OtherRefType.getQualifiers();
7939 }
7940
7941 // Our location for everything implicitly-generated.
7942 SourceLocation Loc = CopyAssignOperator->getLocation();
7943
7944 // Construct a reference to the "other" object. We'll be using this
7945 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007946 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007947 assert(OtherRef && "Reference to parameter cannot fail!");
7948
7949 // Construct the "this" pointer. We'll be using this throughout the generated
7950 // ASTs.
7951 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7952 assert(This && "Reference to this cannot fail!");
7953
7954 // Assign base classes.
7955 bool Invalid = false;
7956 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7957 E = ClassDecl->bases_end(); Base != E; ++Base) {
7958 // Form the assignment:
7959 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7960 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007961 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007962 Invalid = true;
7963 continue;
7964 }
7965
John McCallf871d0c2010-08-07 06:22:56 +00007966 CXXCastPath BasePath;
7967 BasePath.push_back(Base);
7968
Douglas Gregor06a9f362010-05-01 20:49:11 +00007969 // Construct the "from" expression, which is an implicit cast to the
7970 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007971 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007972 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7973 CK_UncheckedDerivedToBase,
7974 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007975
7976 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007977 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007978
7979 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007980 To = ImpCastExprToType(To.take(),
7981 Context.getCVRQualifiedType(BaseType,
7982 CopyAssignOperator->getTypeQualifiers()),
7983 CK_UncheckedDerivedToBase,
7984 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007985
7986 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007987 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007988 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007989 /*CopyingBaseSubobject=*/true,
7990 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007991 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007992 Diag(CurrentLocation, diag::note_member_synthesized_at)
7993 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7994 CopyAssignOperator->setInvalidDecl();
7995 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007996 }
7997
7998 // Success! Record the copy.
7999 Statements.push_back(Copy.takeAs<Expr>());
8000 }
8001
8002 // \brief Reference to the __builtin_memcpy function.
8003 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008004 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008005 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008006
8007 // Assign non-static members.
8008 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8009 FieldEnd = ClassDecl->field_end();
8010 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008011 if (Field->isUnnamedBitfield())
8012 continue;
8013
Douglas Gregor06a9f362010-05-01 20:49:11 +00008014 // Check for members of reference type; we can't copy those.
8015 if (Field->getType()->isReferenceType()) {
8016 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8017 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8018 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008019 Diag(CurrentLocation, diag::note_member_synthesized_at)
8020 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008021 Invalid = true;
8022 continue;
8023 }
8024
8025 // Check for members of const-qualified, non-class type.
8026 QualType BaseType = Context.getBaseElementType(Field->getType());
8027 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8028 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8029 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8030 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008031 Diag(CurrentLocation, diag::note_member_synthesized_at)
8032 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008033 Invalid = true;
8034 continue;
8035 }
John McCallb77115d2011-06-17 00:18:42 +00008036
8037 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008038 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8039 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008040
8041 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008042 if (FieldType->isIncompleteArrayType()) {
8043 assert(ClassDecl->hasFlexibleArrayMember() &&
8044 "Incomplete array type is not valid");
8045 continue;
8046 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008047
8048 // Build references to the field in the object we're copying from and to.
8049 CXXScopeSpec SS; // Intentionally empty
8050 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8051 LookupMemberName);
8052 MemberLookup.addDecl(*Field);
8053 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008054 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008055 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008056 SS, SourceLocation(), 0,
8057 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008058 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008059 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008060 SS, SourceLocation(), 0,
8061 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008062 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8063 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8064
8065 // If the field should be copied with __builtin_memcpy rather than via
8066 // explicit assignments, do so. This optimization only applies for arrays
8067 // of scalars and arrays of class type with trivial copy-assignment
8068 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00008069 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008070 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008071 // Compute the size of the memory buffer to be copied.
8072 QualType SizeType = Context.getSizeType();
8073 llvm::APInt Size(Context.getTypeSize(SizeType),
8074 Context.getTypeSizeInChars(BaseType).getQuantity());
8075 for (const ConstantArrayType *Array
8076 = Context.getAsConstantArrayType(FieldType);
8077 Array;
8078 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00008079 llvm::APInt ArraySize
8080 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008081 Size *= ArraySize;
8082 }
8083
8084 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00008085 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8086 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008087
8088 bool NeedsCollectableMemCpy =
8089 (BaseType->isRecordType() &&
8090 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8091
8092 if (NeedsCollectableMemCpy) {
8093 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008094 // Create a reference to the __builtin_objc_memmove_collectable function.
8095 LookupResult R(*this,
8096 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008097 Loc, LookupOrdinaryName);
8098 LookupName(R, TUScope, true);
8099
8100 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8101 if (!CollectableMemCpy) {
8102 // Something went horribly wrong earlier, and we will have
8103 // complained about it.
8104 Invalid = true;
8105 continue;
8106 }
8107
8108 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8109 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008110 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008111 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8112 }
8113 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008114 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008115 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008116 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8117 LookupOrdinaryName);
8118 LookupName(R, TUScope, true);
8119
8120 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8121 if (!BuiltinMemCpy) {
8122 // Something went horribly wrong earlier, and we will have complained
8123 // about it.
8124 Invalid = true;
8125 continue;
8126 }
8127
8128 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8129 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008130 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008131 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8132 }
8133
John McCallca0408f2010-08-23 06:44:23 +00008134 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008135 CallArgs.push_back(To.takeAs<Expr>());
8136 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008137 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00008138 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008139 if (NeedsCollectableMemCpy)
8140 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008141 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008142 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008143 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008144 else
8145 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008146 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008147 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008148 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008149
Douglas Gregor06a9f362010-05-01 20:49:11 +00008150 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8151 Statements.push_back(Call.takeAs<Expr>());
8152 continue;
8153 }
8154
8155 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00008156 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008157 To.get(), From.get(),
8158 /*CopyingBaseSubobject=*/false,
8159 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008160 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008161 Diag(CurrentLocation, diag::note_member_synthesized_at)
8162 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8163 CopyAssignOperator->setInvalidDecl();
8164 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008165 }
8166
8167 // Success! Record the copy.
8168 Statements.push_back(Copy.takeAs<Stmt>());
8169 }
8170
8171 if (!Invalid) {
8172 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008173 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008174
John McCall60d7b3a2010-08-24 06:29:42 +00008175 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008176 if (Return.isInvalid())
8177 Invalid = true;
8178 else {
8179 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008180
8181 if (Trap.hasErrorOccurred()) {
8182 Diag(CurrentLocation, diag::note_member_synthesized_at)
8183 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8184 Invalid = true;
8185 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008186 }
8187 }
8188
8189 if (Invalid) {
8190 CopyAssignOperator->setInvalidDecl();
8191 return;
8192 }
8193
John McCall60d7b3a2010-08-24 06:29:42 +00008194 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008195 /*isStmtExpr=*/false);
8196 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8197 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008198
8199 if (ASTMutationListener *L = getASTMutationListener()) {
8200 L->CompletedImplicitDefinition(CopyAssignOperator);
8201 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008202}
8203
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008204Sema::ImplicitExceptionSpecification
8205Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8206 ImplicitExceptionSpecification ExceptSpec(Context);
8207
8208 if (ClassDecl->isInvalidDecl())
8209 return ExceptSpec;
8210
8211 // C++0x [except.spec]p14:
8212 // An implicitly declared special member function (Clause 12) shall have an
8213 // exception-specification. [...]
8214
8215 // It is unspecified whether or not an implicit move assignment operator
8216 // attempts to deduplicate calls to assignment operators of virtual bases are
8217 // made. As such, this exception specification is effectively unspecified.
8218 // Based on a similar decision made for constness in C++0x, we're erring on
8219 // the side of assuming such calls to be made regardless of whether they
8220 // actually happen.
8221 // Note that a move constructor is not implicitly declared when there are
8222 // virtual bases, but it can still be user-declared and explicitly defaulted.
8223 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8224 BaseEnd = ClassDecl->bases_end();
8225 Base != BaseEnd; ++Base) {
8226 if (Base->isVirtual())
8227 continue;
8228
8229 CXXRecordDecl *BaseClassDecl
8230 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8231 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8232 false, 0))
8233 ExceptSpec.CalledDecl(MoveAssign);
8234 }
8235
8236 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8237 BaseEnd = ClassDecl->vbases_end();
8238 Base != BaseEnd; ++Base) {
8239 CXXRecordDecl *BaseClassDecl
8240 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8241 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8242 false, 0))
8243 ExceptSpec.CalledDecl(MoveAssign);
8244 }
8245
8246 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8247 FieldEnd = ClassDecl->field_end();
8248 Field != FieldEnd;
8249 ++Field) {
8250 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8251 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8252 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8253 false, 0))
8254 ExceptSpec.CalledDecl(MoveAssign);
8255 }
8256 }
8257
8258 return ExceptSpec;
8259}
8260
8261CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8262 // Note: The following rules are largely analoguous to the move
8263 // constructor rules.
8264
8265 ImplicitExceptionSpecification Spec(
8266 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8267
8268 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8269 QualType RetType = Context.getLValueReferenceType(ArgType);
8270 ArgType = Context.getRValueReferenceType(ArgType);
8271
8272 // An implicitly-declared move assignment operator is an inline public
8273 // member of its class.
8274 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8275 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8276 SourceLocation ClassLoc = ClassDecl->getLocation();
8277 DeclarationNameInfo NameInfo(Name, ClassLoc);
8278 CXXMethodDecl *MoveAssignment
8279 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8280 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8281 /*TInfo=*/0, /*isStatic=*/false,
8282 /*StorageClassAsWritten=*/SC_None,
8283 /*isInline=*/true,
8284 /*isConstexpr=*/false,
8285 SourceLocation());
8286 MoveAssignment->setAccess(AS_public);
8287 MoveAssignment->setDefaulted();
8288 MoveAssignment->setImplicit();
8289 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8290
8291 // Add the parameter to the operator.
8292 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8293 ClassLoc, ClassLoc, /*Id=*/0,
8294 ArgType, /*TInfo=*/0,
8295 SC_None,
8296 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008297 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008298
8299 // Note that we have added this copy-assignment operator.
8300 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8301
8302 // C++0x [class.copy]p9:
8303 // If the definition of a class X does not explicitly declare a move
8304 // assignment operator, one will be implicitly declared as defaulted if and
8305 // only if:
8306 // [...]
8307 // - the move assignment operator would not be implicitly defined as
8308 // deleted.
8309 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8310 // Cache this result so that we don't try to generate this over and over
8311 // on every lookup, leaking memory and wasting time.
8312 ClassDecl->setFailedImplicitMoveAssignment();
8313 return 0;
8314 }
8315
8316 if (Scope *S = getScopeForContext(ClassDecl))
8317 PushOnScopeChains(MoveAssignment, S, false);
8318 ClassDecl->addDecl(MoveAssignment);
8319
8320 AddOverriddenMethods(ClassDecl, MoveAssignment);
8321 return MoveAssignment;
8322}
8323
8324void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8325 CXXMethodDecl *MoveAssignOperator) {
8326 assert((MoveAssignOperator->isDefaulted() &&
8327 MoveAssignOperator->isOverloadedOperator() &&
8328 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8329 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8330 "DefineImplicitMoveAssignment called for wrong function");
8331
8332 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8333
8334 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8335 MoveAssignOperator->setInvalidDecl();
8336 return;
8337 }
8338
8339 MoveAssignOperator->setUsed();
8340
8341 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8342 DiagnosticErrorTrap Trap(Diags);
8343
8344 // C++0x [class.copy]p28:
8345 // The implicitly-defined or move assignment operator for a non-union class
8346 // X performs memberwise move assignment of its subobjects. The direct base
8347 // classes of X are assigned first, in the order of their declaration in the
8348 // base-specifier-list, and then the immediate non-static data members of X
8349 // are assigned, in the order in which they were declared in the class
8350 // definition.
8351
8352 // The statements that form the synthesized function body.
8353 ASTOwningVector<Stmt*> Statements(*this);
8354
8355 // The parameter for the "other" object, which we are move from.
8356 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8357 QualType OtherRefType = Other->getType()->
8358 getAs<RValueReferenceType>()->getPointeeType();
8359 assert(OtherRefType.getQualifiers() == 0 &&
8360 "Bad argument type of defaulted move assignment");
8361
8362 // Our location for everything implicitly-generated.
8363 SourceLocation Loc = MoveAssignOperator->getLocation();
8364
8365 // Construct a reference to the "other" object. We'll be using this
8366 // throughout the generated ASTs.
8367 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8368 assert(OtherRef && "Reference to parameter cannot fail!");
8369 // Cast to rvalue.
8370 OtherRef = CastForMoving(*this, OtherRef);
8371
8372 // Construct the "this" pointer. We'll be using this throughout the generated
8373 // ASTs.
8374 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8375 assert(This && "Reference to this cannot fail!");
8376
8377 // Assign base classes.
8378 bool Invalid = false;
8379 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8380 E = ClassDecl->bases_end(); Base != E; ++Base) {
8381 // Form the assignment:
8382 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8383 QualType BaseType = Base->getType().getUnqualifiedType();
8384 if (!BaseType->isRecordType()) {
8385 Invalid = true;
8386 continue;
8387 }
8388
8389 CXXCastPath BasePath;
8390 BasePath.push_back(Base);
8391
8392 // Construct the "from" expression, which is an implicit cast to the
8393 // appropriately-qualified base type.
8394 Expr *From = OtherRef;
8395 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008396 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008397
8398 // Dereference "this".
8399 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8400
8401 // Implicitly cast "this" to the appropriately-qualified base type.
8402 To = ImpCastExprToType(To.take(),
8403 Context.getCVRQualifiedType(BaseType,
8404 MoveAssignOperator->getTypeQualifiers()),
8405 CK_UncheckedDerivedToBase,
8406 VK_LValue, &BasePath);
8407
8408 // Build the move.
8409 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8410 To.get(), From,
8411 /*CopyingBaseSubobject=*/true,
8412 /*Copying=*/false);
8413 if (Move.isInvalid()) {
8414 Diag(CurrentLocation, diag::note_member_synthesized_at)
8415 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8416 MoveAssignOperator->setInvalidDecl();
8417 return;
8418 }
8419
8420 // Success! Record the move.
8421 Statements.push_back(Move.takeAs<Expr>());
8422 }
8423
8424 // \brief Reference to the __builtin_memcpy function.
8425 Expr *BuiltinMemCpyRef = 0;
8426 // \brief Reference to the __builtin_objc_memmove_collectable function.
8427 Expr *CollectableMemCpyRef = 0;
8428
8429 // Assign non-static members.
8430 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8431 FieldEnd = ClassDecl->field_end();
8432 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008433 if (Field->isUnnamedBitfield())
8434 continue;
8435
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008436 // Check for members of reference type; we can't move those.
8437 if (Field->getType()->isReferenceType()) {
8438 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8439 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8440 Diag(Field->getLocation(), diag::note_declared_at);
8441 Diag(CurrentLocation, diag::note_member_synthesized_at)
8442 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8443 Invalid = true;
8444 continue;
8445 }
8446
8447 // Check for members of const-qualified, non-class type.
8448 QualType BaseType = Context.getBaseElementType(Field->getType());
8449 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8450 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8451 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8452 Diag(Field->getLocation(), diag::note_declared_at);
8453 Diag(CurrentLocation, diag::note_member_synthesized_at)
8454 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8455 Invalid = true;
8456 continue;
8457 }
8458
8459 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008460 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8461 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008462
8463 QualType FieldType = Field->getType().getNonReferenceType();
8464 if (FieldType->isIncompleteArrayType()) {
8465 assert(ClassDecl->hasFlexibleArrayMember() &&
8466 "Incomplete array type is not valid");
8467 continue;
8468 }
8469
8470 // Build references to the field in the object we're copying from and to.
8471 CXXScopeSpec SS; // Intentionally empty
8472 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8473 LookupMemberName);
8474 MemberLookup.addDecl(*Field);
8475 MemberLookup.resolveKind();
8476 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8477 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008478 SS, SourceLocation(), 0,
8479 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008480 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8481 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008482 SS, SourceLocation(), 0,
8483 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008484 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8485 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8486
8487 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8488 "Member reference with rvalue base must be rvalue except for reference "
8489 "members, which aren't allowed for move assignment.");
8490
8491 // If the field should be copied with __builtin_memcpy rather than via
8492 // explicit assignments, do so. This optimization only applies for arrays
8493 // of scalars and arrays of class type with trivial move-assignment
8494 // operators.
8495 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8496 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8497 // Compute the size of the memory buffer to be copied.
8498 QualType SizeType = Context.getSizeType();
8499 llvm::APInt Size(Context.getTypeSize(SizeType),
8500 Context.getTypeSizeInChars(BaseType).getQuantity());
8501 for (const ConstantArrayType *Array
8502 = Context.getAsConstantArrayType(FieldType);
8503 Array;
8504 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8505 llvm::APInt ArraySize
8506 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8507 Size *= ArraySize;
8508 }
8509
Douglas Gregor45d3d712011-09-01 02:09:07 +00008510 // Take the address of the field references for "from" and "to". We
8511 // directly construct UnaryOperators here because semantic analysis
8512 // does not permit us to take the address of an xvalue.
8513 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8514 Context.getPointerType(From.get()->getType()),
8515 VK_RValue, OK_Ordinary, Loc);
8516 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8517 Context.getPointerType(To.get()->getType()),
8518 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008519
8520 bool NeedsCollectableMemCpy =
8521 (BaseType->isRecordType() &&
8522 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8523
8524 if (NeedsCollectableMemCpy) {
8525 if (!CollectableMemCpyRef) {
8526 // Create a reference to the __builtin_objc_memmove_collectable function.
8527 LookupResult R(*this,
8528 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8529 Loc, LookupOrdinaryName);
8530 LookupName(R, TUScope, true);
8531
8532 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8533 if (!CollectableMemCpy) {
8534 // Something went horribly wrong earlier, and we will have
8535 // complained about it.
8536 Invalid = true;
8537 continue;
8538 }
8539
8540 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8541 CollectableMemCpy->getType(),
8542 VK_LValue, Loc, 0).take();
8543 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8544 }
8545 }
8546 // Create a reference to the __builtin_memcpy builtin function.
8547 else if (!BuiltinMemCpyRef) {
8548 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8549 LookupOrdinaryName);
8550 LookupName(R, TUScope, true);
8551
8552 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8553 if (!BuiltinMemCpy) {
8554 // Something went horribly wrong earlier, and we will have complained
8555 // about it.
8556 Invalid = true;
8557 continue;
8558 }
8559
8560 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8561 BuiltinMemCpy->getType(),
8562 VK_LValue, Loc, 0).take();
8563 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8564 }
8565
8566 ASTOwningVector<Expr*> CallArgs(*this);
8567 CallArgs.push_back(To.takeAs<Expr>());
8568 CallArgs.push_back(From.takeAs<Expr>());
8569 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8570 ExprResult Call = ExprError();
8571 if (NeedsCollectableMemCpy)
8572 Call = ActOnCallExpr(/*Scope=*/0,
8573 CollectableMemCpyRef,
8574 Loc, move_arg(CallArgs),
8575 Loc);
8576 else
8577 Call = ActOnCallExpr(/*Scope=*/0,
8578 BuiltinMemCpyRef,
8579 Loc, move_arg(CallArgs),
8580 Loc);
8581
8582 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8583 Statements.push_back(Call.takeAs<Expr>());
8584 continue;
8585 }
8586
8587 // Build the move of this field.
8588 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8589 To.get(), From.get(),
8590 /*CopyingBaseSubobject=*/false,
8591 /*Copying=*/false);
8592 if (Move.isInvalid()) {
8593 Diag(CurrentLocation, diag::note_member_synthesized_at)
8594 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8595 MoveAssignOperator->setInvalidDecl();
8596 return;
8597 }
8598
8599 // Success! Record the copy.
8600 Statements.push_back(Move.takeAs<Stmt>());
8601 }
8602
8603 if (!Invalid) {
8604 // Add a "return *this;"
8605 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8606
8607 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8608 if (Return.isInvalid())
8609 Invalid = true;
8610 else {
8611 Statements.push_back(Return.takeAs<Stmt>());
8612
8613 if (Trap.hasErrorOccurred()) {
8614 Diag(CurrentLocation, diag::note_member_synthesized_at)
8615 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8616 Invalid = true;
8617 }
8618 }
8619 }
8620
8621 if (Invalid) {
8622 MoveAssignOperator->setInvalidDecl();
8623 return;
8624 }
8625
8626 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8627 /*isStmtExpr=*/false);
8628 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8629 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8630
8631 if (ASTMutationListener *L = getASTMutationListener()) {
8632 L->CompletedImplicitDefinition(MoveAssignOperator);
8633 }
8634}
8635
Sean Hunt49634cf2011-05-13 06:10:58 +00008636std::pair<Sema::ImplicitExceptionSpecification, bool>
8637Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008638 if (ClassDecl->isInvalidDecl())
8639 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8640
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008641 // C++ [class.copy]p5:
8642 // The implicitly-declared copy constructor for a class X will
8643 // have the form
8644 //
8645 // X::X(const X&)
8646 //
8647 // if
Sean Huntc530d172011-06-10 04:44:37 +00008648 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008649 bool HasConstCopyConstructor = true;
8650
8651 // -- each direct or virtual base class B of X has a copy
8652 // constructor whose first parameter is of type const B& or
8653 // const volatile B&, and
8654 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8655 BaseEnd = ClassDecl->bases_end();
8656 HasConstCopyConstructor && Base != BaseEnd;
8657 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008658 // Virtual bases are handled below.
8659 if (Base->isVirtual())
8660 continue;
8661
Douglas Gregor22584312010-07-02 23:41:54 +00008662 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008663 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008664 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8665 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008666 }
8667
8668 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8669 BaseEnd = ClassDecl->vbases_end();
8670 HasConstCopyConstructor && Base != BaseEnd;
8671 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008672 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008673 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008674 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8675 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008676 }
8677
8678 // -- for all the nonstatic data members of X that are of a
8679 // class type M (or array thereof), each such class type
8680 // has a copy constructor whose first parameter is of type
8681 // const M& or const volatile M&.
8682 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8683 FieldEnd = ClassDecl->field_end();
8684 HasConstCopyConstructor && Field != FieldEnd;
8685 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008686 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008687 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008688 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8689 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008690 }
8691 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008692 // Otherwise, the implicitly declared copy constructor will have
8693 // the form
8694 //
8695 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008696
Douglas Gregor0d405db2010-07-01 20:59:04 +00008697 // C++ [except.spec]p14:
8698 // An implicitly declared special member function (Clause 12) shall have an
8699 // exception-specification. [...]
8700 ImplicitExceptionSpecification ExceptSpec(Context);
8701 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8702 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8703 BaseEnd = ClassDecl->bases_end();
8704 Base != BaseEnd;
8705 ++Base) {
8706 // Virtual bases are handled below.
8707 if (Base->isVirtual())
8708 continue;
8709
Douglas Gregor22584312010-07-02 23:41:54 +00008710 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008711 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008712 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008713 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008714 ExceptSpec.CalledDecl(CopyConstructor);
8715 }
8716 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8717 BaseEnd = ClassDecl->vbases_end();
8718 Base != BaseEnd;
8719 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008720 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008721 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008722 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008723 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008724 ExceptSpec.CalledDecl(CopyConstructor);
8725 }
8726 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8727 FieldEnd = ClassDecl->field_end();
8728 Field != FieldEnd;
8729 ++Field) {
8730 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008731 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8732 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008733 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008734 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008735 }
8736 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008737
Sean Hunt49634cf2011-05-13 06:10:58 +00008738 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8739}
8740
8741CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8742 CXXRecordDecl *ClassDecl) {
8743 // C++ [class.copy]p4:
8744 // If the class definition does not explicitly declare a copy
8745 // constructor, one is declared implicitly.
8746
8747 ImplicitExceptionSpecification Spec(Context);
8748 bool Const;
8749 llvm::tie(Spec, Const) =
8750 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8751
8752 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8753 QualType ArgType = ClassType;
8754 if (Const)
8755 ArgType = ArgType.withConst();
8756 ArgType = Context.getLValueReferenceType(ArgType);
8757
8758 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8759
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008760 DeclarationName Name
8761 = Context.DeclarationNames.getCXXConstructorName(
8762 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008763 SourceLocation ClassLoc = ClassDecl->getLocation();
8764 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008765
8766 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008767 // member of its class.
8768 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8769 Context, ClassDecl, ClassLoc, NameInfo,
8770 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8771 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8772 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8773 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008774 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008775 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008776 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008777
Douglas Gregor22584312010-07-02 23:41:54 +00008778 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008779 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8780
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008781 // Add the parameter to the constructor.
8782 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008783 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008784 /*IdentifierInfo=*/0,
8785 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008786 SC_None,
8787 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008788 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008789
Douglas Gregor23c94db2010-07-02 17:43:08 +00008790 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008791 PushOnScopeChains(CopyConstructor, S, false);
8792 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008793
Nico Weberafcc96a2012-01-23 03:19:29 +00008794 // C++11 [class.copy]p8:
8795 // ... If the class definition does not explicitly declare a copy
8796 // constructor, there is no user-declared move constructor, and there is no
8797 // user-declared move assignment operator, a copy constructor is implicitly
8798 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008799 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008800 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber28976602012-01-23 04:01:33 +00008801 !getLangOptions().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008802 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008803 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008804
8805 return CopyConstructor;
8806}
8807
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008808void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008809 CXXConstructorDecl *CopyConstructor) {
8810 assert((CopyConstructor->isDefaulted() &&
8811 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008812 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008813 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008814
Anders Carlsson63010a72010-04-23 16:24:12 +00008815 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008816 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008817
Douglas Gregor39957dc2010-05-01 15:04:51 +00008818 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008819 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008820
Sean Huntcbb67482011-01-08 20:30:50 +00008821 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008822 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008823 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008824 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008825 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008826 } else {
8827 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8828 CopyConstructor->getLocation(),
8829 MultiStmtArg(*this, 0, 0),
8830 /*isStmtExpr=*/false)
8831 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008832 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008833 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008834
8835 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008836 if (ASTMutationListener *L = getASTMutationListener()) {
8837 L->CompletedImplicitDefinition(CopyConstructor);
8838 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008839}
8840
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008841Sema::ImplicitExceptionSpecification
8842Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8843 // C++ [except.spec]p14:
8844 // An implicitly declared special member function (Clause 12) shall have an
8845 // exception-specification. [...]
8846 ImplicitExceptionSpecification ExceptSpec(Context);
8847 if (ClassDecl->isInvalidDecl())
8848 return ExceptSpec;
8849
8850 // Direct base-class constructors.
8851 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8852 BEnd = ClassDecl->bases_end();
8853 B != BEnd; ++B) {
8854 if (B->isVirtual()) // Handled below.
8855 continue;
8856
8857 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8858 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8859 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8860 // If this is a deleted function, add it anyway. This might be conformant
8861 // with the standard. This might not. I'm not sure. It might not matter.
8862 if (Constructor)
8863 ExceptSpec.CalledDecl(Constructor);
8864 }
8865 }
8866
8867 // Virtual base-class constructors.
8868 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8869 BEnd = ClassDecl->vbases_end();
8870 B != BEnd; ++B) {
8871 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8872 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8873 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8874 // If this is a deleted function, add it anyway. This might be conformant
8875 // with the standard. This might not. I'm not sure. It might not matter.
8876 if (Constructor)
8877 ExceptSpec.CalledDecl(Constructor);
8878 }
8879 }
8880
8881 // Field constructors.
8882 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8883 FEnd = ClassDecl->field_end();
8884 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008885 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008886 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8887 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8888 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8889 // If this is a deleted function, add it anyway. This might be conformant
8890 // with the standard. This might not. I'm not sure. It might not matter.
8891 // In particular, the problem is that this function never gets called. It
8892 // might just be ill-formed because this function attempts to refer to
8893 // a deleted function here.
8894 if (Constructor)
8895 ExceptSpec.CalledDecl(Constructor);
8896 }
8897 }
8898
8899 return ExceptSpec;
8900}
8901
8902CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8903 CXXRecordDecl *ClassDecl) {
8904 ImplicitExceptionSpecification Spec(
8905 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8906
8907 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8908 QualType ArgType = Context.getRValueReferenceType(ClassType);
8909
8910 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8911
8912 DeclarationName Name
8913 = Context.DeclarationNames.getCXXConstructorName(
8914 Context.getCanonicalType(ClassType));
8915 SourceLocation ClassLoc = ClassDecl->getLocation();
8916 DeclarationNameInfo NameInfo(Name, ClassLoc);
8917
8918 // C++0x [class.copy]p11:
8919 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008920 // member of its class.
8921 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8922 Context, ClassDecl, ClassLoc, NameInfo,
8923 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8924 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8925 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8926 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008927 MoveConstructor->setAccess(AS_public);
8928 MoveConstructor->setDefaulted();
8929 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008930
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008931 // Add the parameter to the constructor.
8932 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8933 ClassLoc, ClassLoc,
8934 /*IdentifierInfo=*/0,
8935 ArgType, /*TInfo=*/0,
8936 SC_None,
8937 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008938 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008939
8940 // C++0x [class.copy]p9:
8941 // If the definition of a class X does not explicitly declare a move
8942 // constructor, one will be implicitly declared as defaulted if and only if:
8943 // [...]
8944 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008945 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008946 // Cache this result so that we don't try to generate this over and over
8947 // on every lookup, leaking memory and wasting time.
8948 ClassDecl->setFailedImplicitMoveConstructor();
8949 return 0;
8950 }
8951
8952 // Note that we have declared this constructor.
8953 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8954
8955 if (Scope *S = getScopeForContext(ClassDecl))
8956 PushOnScopeChains(MoveConstructor, S, false);
8957 ClassDecl->addDecl(MoveConstructor);
8958
8959 return MoveConstructor;
8960}
8961
8962void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8963 CXXConstructorDecl *MoveConstructor) {
8964 assert((MoveConstructor->isDefaulted() &&
8965 MoveConstructor->isMoveConstructor() &&
8966 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8967 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8968
8969 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8970 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8971
8972 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8973 DiagnosticErrorTrap Trap(Diags);
8974
8975 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8976 Trap.hasErrorOccurred()) {
8977 Diag(CurrentLocation, diag::note_member_synthesized_at)
8978 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8979 MoveConstructor->setInvalidDecl();
8980 } else {
8981 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8982 MoveConstructor->getLocation(),
8983 MultiStmtArg(*this, 0, 0),
8984 /*isStmtExpr=*/false)
8985 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008986 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008987 }
8988
8989 MoveConstructor->setUsed();
8990
8991 if (ASTMutationListener *L = getASTMutationListener()) {
8992 L->CompletedImplicitDefinition(MoveConstructor);
8993 }
8994}
8995
John McCall60d7b3a2010-08-24 06:29:42 +00008996ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008997Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008998 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008999 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009000 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009001 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009002 unsigned ConstructKind,
9003 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009004 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009005
Douglas Gregor2f599792010-04-02 18:24:57 +00009006 // C++0x [class.copy]p34:
9007 // When certain criteria are met, an implementation is allowed to
9008 // omit the copy/move construction of a class object, even if the
9009 // copy/move constructor and/or destructor for the object have
9010 // side effects. [...]
9011 // - when a temporary class object that has not been bound to a
9012 // reference (12.2) would be copied/moved to a class object
9013 // with the same cv-unqualified type, the copy/move operation
9014 // can be omitted by constructing the temporary object
9015 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009016 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00009017 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009018 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009019 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009020 }
Mike Stump1eb44332009-09-09 15:08:12 +00009021
9022 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009023 Elidable, move(ExprArgs), HadMultipleCandidates,
9024 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009025}
9026
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009027/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9028/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009029ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009030Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9031 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009032 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009033 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009034 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009035 unsigned ConstructKind,
9036 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009037 unsigned NumExprs = ExprArgs.size();
9038 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009039
Nick Lewycky909a70d2011-03-25 01:44:32 +00009040 for (specific_attr_iterator<NonNullAttr>
9041 i = Constructor->specific_attr_begin<NonNullAttr>(),
9042 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9043 const NonNullAttr *NonNull = *i;
9044 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9045 }
9046
Eli Friedman5f2987c2012-02-02 03:46:19 +00009047 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009048 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009049 Constructor, Elidable, Exprs, NumExprs,
9050 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009051 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9052 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009053}
9054
Mike Stump1eb44332009-09-09 15:08:12 +00009055bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009056 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009057 MultiExprArg Exprs,
9058 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009059 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009060 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009061 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009062 move(Exprs), HadMultipleCandidates, false,
9063 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009064 if (TempResult.isInvalid())
9065 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009066
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009067 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009068 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009069 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009070 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009071 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009072
Anders Carlssonfe2de492009-08-25 05:18:00 +00009073 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009074}
9075
John McCall68c6c9a2010-02-02 09:10:11 +00009076void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009077 if (VD->isInvalidDecl()) return;
9078
John McCall68c6c9a2010-02-02 09:10:11 +00009079 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009080 if (ClassDecl->isInvalidDecl()) return;
9081 if (ClassDecl->hasTrivialDestructor()) return;
9082 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009083
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009084 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009085 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009086 CheckDestructorAccess(VD->getLocation(), Destructor,
9087 PDiag(diag::err_access_dtor_var)
9088 << VD->getDeclName()
9089 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009090
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009091 if (!VD->hasGlobalStorage()) return;
9092
9093 // Emit warning for non-trivial dtor in global scope (a real global,
9094 // class-static, function-static).
9095 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9096
9097 // TODO: this should be re-enabled for static locals by !CXAAtExit
9098 if (!VD->isStaticLocal())
9099 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009100}
9101
Mike Stump1eb44332009-09-09 15:08:12 +00009102/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009103/// ActOnDeclarator, when a C++ direct initializer is present.
9104/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00009105void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00009106 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009107 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00009108 SourceLocation RParenLoc,
9109 bool TypeMayContainAuto) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009110 // If there is no declaration, there was an error parsing it. Just ignore
9111 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00009112 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009113 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009114
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009115 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9116 if (!VDecl) {
9117 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9118 RealDecl->setInvalidDecl();
9119 return;
9120 }
9121
Eli Friedman6aeaa602012-01-05 22:34:08 +00009122 // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith34b41d92011-02-20 03:19:35 +00009123 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Eli Friedman6aeaa602012-01-05 22:34:08 +00009124 if (Exprs.size() == 0) {
9125 // It isn't possible to write this directly, but it is possible to
9126 // end up in this situation with "auto x(some_pack...);"
9127 Diag(LParenLoc, diag::err_auto_var_init_no_expression)
9128 << VDecl->getDeclName() << VDecl->getType()
9129 << VDecl->getSourceRange();
9130 RealDecl->setInvalidDecl();
9131 return;
9132 }
9133
Richard Smith34b41d92011-02-20 03:19:35 +00009134 if (Exprs.size() > 1) {
9135 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9136 diag::err_auto_var_init_multiple_expressions)
9137 << VDecl->getDeclName() << VDecl->getType()
9138 << VDecl->getSourceRange();
9139 RealDecl->setInvalidDecl();
9140 return;
9141 }
9142
9143 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00009144 TypeSourceInfo *DeducedType = 0;
Sebastian Redlb832f6d2012-01-23 22:09:39 +00009145 if (DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType) ==
9146 DAR_Failed)
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00009147 DiagnoseAutoDeductionFailure(VDecl, Init);
Richard Smitha085da82011-03-17 16:11:59 +00009148 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00009149 RealDecl->setInvalidDecl();
9150 return;
9151 }
Richard Smitha085da82011-03-17 16:11:59 +00009152 VDecl->setTypeSourceInfo(DeducedType);
9153 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00009154
John McCallf85e1932011-06-15 23:02:42 +00009155 // In ARC, infer lifetime.
9156 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9157 VDecl->setInvalidDecl();
9158
Richard Smith34b41d92011-02-20 03:19:35 +00009159 // If this is a redeclaration, check that the type we just deduced matches
9160 // the previously declared type.
Douglas Gregoref96ee02012-01-14 16:38:05 +00009161 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith34b41d92011-02-20 03:19:35 +00009162 MergeVarDeclTypes(VDecl, Old);
9163 }
9164
Douglas Gregor83ddad32009-08-26 21:14:46 +00009165 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009166 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009167 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9168 //
9169 // Clients that want to distinguish between the two forms, can check for
9170 // direct initializer using VarDecl::hasCXXDirectInitializer().
9171 // A major benefit is that clients that don't particularly care about which
9172 // exactly form was it (like the CodeGen) can handle both cases without
9173 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009174
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009175 // C++ 8.5p11:
9176 // The form of initialization (using parentheses or '=') is generally
9177 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009178 // class type.
9179
Douglas Gregor4dffad62010-02-11 22:55:30 +00009180 if (!VDecl->getType()->isDependentType() &&
Douglas Gregord24c3062011-10-10 16:05:18 +00009181 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor4dffad62010-02-11 22:55:30 +00009182 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00009183 diag::err_typecheck_decl_incomplete_type)) {
9184 VDecl->setInvalidDecl();
9185 return;
9186 }
9187
Douglas Gregor90f93822009-12-22 22:17:25 +00009188 // The variable can not have an abstract class type.
9189 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9190 diag::err_abstract_type_in_decl,
9191 AbstractVariableType))
9192 VDecl->setInvalidDecl();
9193
Sebastian Redl31310a22010-02-01 20:16:42 +00009194 const VarDecl *Def;
9195 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00009196 Diag(VDecl->getLocation(), diag::err_redefinition)
9197 << VDecl->getDeclName();
9198 Diag(Def->getLocation(), diag::note_previous_definition);
9199 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009200 return;
9201 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00009202
Douglas Gregor3a91abf2010-08-24 05:27:49 +00009203 // C++ [class.static.data]p4
9204 // If a static data member is of const integral or const
9205 // enumeration type, its declaration in the class definition can
9206 // specify a constant-initializer which shall be an integral
9207 // constant expression (5.19). In that case, the member can appear
9208 // in integral constant expressions. The member shall still be
9209 // defined in a namespace scope if it is used in the program and the
9210 // namespace scope definition shall not contain an initializer.
9211 //
9212 // We already performed a redefinition check above, but for static
9213 // data members we also need to check whether there was an in-class
9214 // declaration with an initializer.
9215 const VarDecl* PrevInit = 0;
9216 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9217 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9218 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9219 return;
9220 }
9221
Douglas Gregora31040f2010-12-16 01:31:22 +00009222 bool IsDependent = false;
9223 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9224 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9225 VDecl->setInvalidDecl();
9226 return;
9227 }
9228
9229 if (Exprs.get()[I]->isTypeDependent())
9230 IsDependent = true;
9231 }
9232
Douglas Gregor4dffad62010-02-11 22:55:30 +00009233 // If either the declaration has a dependent type or if any of the
9234 // expressions is type-dependent, we represent the initialization
9235 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00009236 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00009237 // Let clients know that initialization was done with a direct initializer.
9238 VDecl->setCXXDirectInitializer(true);
9239
9240 // Store the initialization expressions as a ParenListExpr.
9241 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00009242 VDecl->setInit(new (Context) ParenListExpr(
9243 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9244 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00009245 return;
9246 }
Douglas Gregor90f93822009-12-22 22:17:25 +00009247
9248 // Capture the variable that is being initialized and the style of
9249 // initialization.
9250 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9251
9252 // FIXME: Poor source location information.
9253 InitializationKind Kind
9254 = InitializationKind::CreateDirect(VDecl->getLocation(),
9255 LParenLoc, RParenLoc);
9256
Douglas Gregord24c3062011-10-10 16:05:18 +00009257 QualType T = VDecl->getType();
Douglas Gregor90f93822009-12-22 22:17:25 +00009258 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00009259 Exprs.get(), Exprs.size());
Douglas Gregord24c3062011-10-10 16:05:18 +00009260 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregor90f93822009-12-22 22:17:25 +00009261 if (Result.isInvalid()) {
9262 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009263 return;
Douglas Gregord24c3062011-10-10 16:05:18 +00009264 } else if (T != VDecl->getType()) {
9265 VDecl->setType(T);
9266 Result.get()->setType(T);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009267 }
John McCallb4eb64d2010-10-08 02:01:28 +00009268
Douglas Gregord24c3062011-10-10 16:05:18 +00009269
Richard Smithc6d990a2011-09-29 19:11:37 +00009270 Expr *Init = Result.get();
9271 CheckImplicitConversions(Init, LParenLoc);
Richard Smithc6d990a2011-09-29 19:11:37 +00009272
9273 Init = MaybeCreateExprWithCleanups(Init);
9274 VDecl->setInit(Init);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009275 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009276
John McCall2998d6b2011-01-19 11:48:09 +00009277 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009278}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00009279
Douglas Gregor39da0b82009-09-09 23:08:42 +00009280/// \brief Given a constructor and the set of arguments provided for the
9281/// constructor, convert the arguments and add any required default arguments
9282/// to form a proper call to this constructor.
9283///
9284/// \returns true if an error occurred, false otherwise.
9285bool
9286Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9287 MultiExprArg ArgsPtr,
9288 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009289 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009290 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9291 unsigned NumArgs = ArgsPtr.size();
9292 Expr **Args = (Expr **)ArgsPtr.get();
9293
9294 const FunctionProtoType *Proto
9295 = Constructor->getType()->getAs<FunctionProtoType>();
9296 assert(Proto && "Constructor without a prototype?");
9297 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009298
9299 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009300 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009301 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009302 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009303 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009304
9305 VariadicCallType CallType =
9306 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009307 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009308 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9309 Proto, 0, Args, NumArgs, AllArgs,
9310 CallType);
9311 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9312 ConvertedArgs.push_back(AllArgs[i]);
9313 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009314}
9315
Anders Carlsson20d45d22009-12-12 00:32:00 +00009316static inline bool
9317CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9318 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009319 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009320 if (isa<NamespaceDecl>(DC)) {
9321 return SemaRef.Diag(FnDecl->getLocation(),
9322 diag::err_operator_new_delete_declared_in_namespace)
9323 << FnDecl->getDeclName();
9324 }
9325
9326 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009327 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009328 return SemaRef.Diag(FnDecl->getLocation(),
9329 diag::err_operator_new_delete_declared_static)
9330 << FnDecl->getDeclName();
9331 }
9332
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009333 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009334}
9335
Anders Carlsson156c78e2009-12-13 17:53:43 +00009336static inline bool
9337CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9338 CanQualType ExpectedResultType,
9339 CanQualType ExpectedFirstParamType,
9340 unsigned DependentParamTypeDiag,
9341 unsigned InvalidParamTypeDiag) {
9342 QualType ResultType =
9343 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9344
9345 // Check that the result type is not dependent.
9346 if (ResultType->isDependentType())
9347 return SemaRef.Diag(FnDecl->getLocation(),
9348 diag::err_operator_new_delete_dependent_result_type)
9349 << FnDecl->getDeclName() << ExpectedResultType;
9350
9351 // Check that the result type is what we expect.
9352 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9353 return SemaRef.Diag(FnDecl->getLocation(),
9354 diag::err_operator_new_delete_invalid_result_type)
9355 << FnDecl->getDeclName() << ExpectedResultType;
9356
9357 // A function template must have at least 2 parameters.
9358 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9359 return SemaRef.Diag(FnDecl->getLocation(),
9360 diag::err_operator_new_delete_template_too_few_parameters)
9361 << FnDecl->getDeclName();
9362
9363 // The function decl must have at least 1 parameter.
9364 if (FnDecl->getNumParams() == 0)
9365 return SemaRef.Diag(FnDecl->getLocation(),
9366 diag::err_operator_new_delete_too_few_parameters)
9367 << FnDecl->getDeclName();
9368
9369 // Check the the first parameter type is not dependent.
9370 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9371 if (FirstParamType->isDependentType())
9372 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9373 << FnDecl->getDeclName() << ExpectedFirstParamType;
9374
9375 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009376 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009377 ExpectedFirstParamType)
9378 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9379 << FnDecl->getDeclName() << ExpectedFirstParamType;
9380
9381 return false;
9382}
9383
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009384static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009385CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009386 // C++ [basic.stc.dynamic.allocation]p1:
9387 // A program is ill-formed if an allocation function is declared in a
9388 // namespace scope other than global scope or declared static in global
9389 // scope.
9390 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9391 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009392
9393 CanQualType SizeTy =
9394 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9395
9396 // C++ [basic.stc.dynamic.allocation]p1:
9397 // The return type shall be void*. The first parameter shall have type
9398 // std::size_t.
9399 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9400 SizeTy,
9401 diag::err_operator_new_dependent_param_type,
9402 diag::err_operator_new_param_type))
9403 return true;
9404
9405 // C++ [basic.stc.dynamic.allocation]p1:
9406 // The first parameter shall not have an associated default argument.
9407 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009408 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009409 diag::err_operator_new_default_arg)
9410 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9411
9412 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009413}
9414
9415static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009416CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9417 // C++ [basic.stc.dynamic.deallocation]p1:
9418 // A program is ill-formed if deallocation functions are declared in a
9419 // namespace scope other than global scope or declared static in global
9420 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009421 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9422 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009423
9424 // C++ [basic.stc.dynamic.deallocation]p2:
9425 // Each deallocation function shall return void and its first parameter
9426 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009427 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9428 SemaRef.Context.VoidPtrTy,
9429 diag::err_operator_delete_dependent_param_type,
9430 diag::err_operator_delete_param_type))
9431 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009432
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009433 return false;
9434}
9435
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009436/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9437/// of this overloaded operator is well-formed. If so, returns false;
9438/// otherwise, emits appropriate diagnostics and returns true.
9439bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009440 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009441 "Expected an overloaded operator declaration");
9442
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009443 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9444
Mike Stump1eb44332009-09-09 15:08:12 +00009445 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009446 // The allocation and deallocation functions, operator new,
9447 // operator new[], operator delete and operator delete[], are
9448 // described completely in 3.7.3. The attributes and restrictions
9449 // found in the rest of this subclause do not apply to them unless
9450 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009451 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009452 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009453
Anders Carlssona3ccda52009-12-12 00:26:23 +00009454 if (Op == OO_New || Op == OO_Array_New)
9455 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009456
9457 // C++ [over.oper]p6:
9458 // An operator function shall either be a non-static member
9459 // function or be a non-member function and have at least one
9460 // parameter whose type is a class, a reference to a class, an
9461 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009462 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9463 if (MethodDecl->isStatic())
9464 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009465 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009466 } else {
9467 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009468 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9469 ParamEnd = FnDecl->param_end();
9470 Param != ParamEnd; ++Param) {
9471 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009472 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9473 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009474 ClassOrEnumParam = true;
9475 break;
9476 }
9477 }
9478
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009479 if (!ClassOrEnumParam)
9480 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009481 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009482 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009483 }
9484
9485 // C++ [over.oper]p8:
9486 // An operator function cannot have default arguments (8.3.6),
9487 // except where explicitly stated below.
9488 //
Mike Stump1eb44332009-09-09 15:08:12 +00009489 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009490 // (C++ [over.call]p1).
9491 if (Op != OO_Call) {
9492 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9493 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009494 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009495 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009496 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009497 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009498 }
9499 }
9500
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009501 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9502 { false, false, false }
9503#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9504 , { Unary, Binary, MemberOnly }
9505#include "clang/Basic/OperatorKinds.def"
9506 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009507
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009508 bool CanBeUnaryOperator = OperatorUses[Op][0];
9509 bool CanBeBinaryOperator = OperatorUses[Op][1];
9510 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009511
9512 // C++ [over.oper]p8:
9513 // [...] Operator functions cannot have more or fewer parameters
9514 // than the number required for the corresponding operator, as
9515 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009516 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009517 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009518 if (Op != OO_Call &&
9519 ((NumParams == 1 && !CanBeUnaryOperator) ||
9520 (NumParams == 2 && !CanBeBinaryOperator) ||
9521 (NumParams < 1) || (NumParams > 2))) {
9522 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009523 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009524 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009525 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009526 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009527 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009528 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009529 assert(CanBeBinaryOperator &&
9530 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009531 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009532 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009533
Chris Lattner416e46f2008-11-21 07:57:12 +00009534 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009535 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009536 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009537
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009538 // Overloaded operators other than operator() cannot be variadic.
9539 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009540 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009541 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009542 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009543 }
9544
9545 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009546 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9547 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009548 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009549 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009550 }
9551
9552 // C++ [over.inc]p1:
9553 // The user-defined function called operator++ implements the
9554 // prefix and postfix ++ operator. If this function is a member
9555 // function with no parameters, or a non-member function with one
9556 // parameter of class or enumeration type, it defines the prefix
9557 // increment operator ++ for objects of that type. If the function
9558 // is a member function with one parameter (which shall be of type
9559 // int) or a non-member function with two parameters (the second
9560 // of which shall be of type int), it defines the postfix
9561 // increment operator ++ for objects of that type.
9562 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9563 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9564 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009565 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009566 ParamIsInt = BT->getKind() == BuiltinType::Int;
9567
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009568 if (!ParamIsInt)
9569 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009570 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009571 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009572 }
9573
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009574 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009575}
Chris Lattner5a003a42008-12-17 07:09:26 +00009576
Sean Hunta6c058d2010-01-13 09:01:02 +00009577/// CheckLiteralOperatorDeclaration - Check whether the declaration
9578/// of this literal operator function is well-formed. If so, returns
9579/// false; otherwise, emits appropriate diagnostics and returns true.
9580bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9581 DeclContext *DC = FnDecl->getDeclContext();
9582 Decl::Kind Kind = DC->getDeclKind();
9583 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9584 Kind != Decl::LinkageSpec) {
9585 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9586 << FnDecl->getDeclName();
9587 return true;
9588 }
9589
9590 bool Valid = false;
9591
Sean Hunt216c2782010-04-07 23:11:06 +00009592 // template <char...> type operator "" name() is the only valid template
9593 // signature, and the only valid signature with no parameters.
9594 if (FnDecl->param_size() == 0) {
9595 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9596 // Must have only one template parameter
9597 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9598 if (Params->size() == 1) {
9599 NonTypeTemplateParmDecl *PmDecl =
9600 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009601
Sean Hunt216c2782010-04-07 23:11:06 +00009602 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009603 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9604 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9605 Valid = true;
9606 }
9607 }
9608 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009609 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009610 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9611
Sean Hunta6c058d2010-01-13 09:01:02 +00009612 QualType T = (*Param)->getType();
9613
Sean Hunt30019c02010-04-07 22:57:35 +00009614 // unsigned long long int, long double, and any character type are allowed
9615 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009616 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9617 Context.hasSameType(T, Context.LongDoubleTy) ||
9618 Context.hasSameType(T, Context.CharTy) ||
9619 Context.hasSameType(T, Context.WCharTy) ||
9620 Context.hasSameType(T, Context.Char16Ty) ||
9621 Context.hasSameType(T, Context.Char32Ty)) {
9622 if (++Param == FnDecl->param_end())
9623 Valid = true;
9624 goto FinishedParams;
9625 }
9626
Sean Hunt30019c02010-04-07 22:57:35 +00009627 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009628 const PointerType *PT = T->getAs<PointerType>();
9629 if (!PT)
9630 goto FinishedParams;
9631 T = PT->getPointeeType();
9632 if (!T.isConstQualified())
9633 goto FinishedParams;
9634 T = T.getUnqualifiedType();
9635
9636 // Move on to the second parameter;
9637 ++Param;
9638
9639 // If there is no second parameter, the first must be a const char *
9640 if (Param == FnDecl->param_end()) {
9641 if (Context.hasSameType(T, Context.CharTy))
9642 Valid = true;
9643 goto FinishedParams;
9644 }
9645
9646 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9647 // are allowed as the first parameter to a two-parameter function
9648 if (!(Context.hasSameType(T, Context.CharTy) ||
9649 Context.hasSameType(T, Context.WCharTy) ||
9650 Context.hasSameType(T, Context.Char16Ty) ||
9651 Context.hasSameType(T, Context.Char32Ty)))
9652 goto FinishedParams;
9653
9654 // The second and final parameter must be an std::size_t
9655 T = (*Param)->getType().getUnqualifiedType();
9656 if (Context.hasSameType(T, Context.getSizeType()) &&
9657 ++Param == FnDecl->param_end())
9658 Valid = true;
9659 }
9660
9661 // FIXME: This diagnostic is absolutely terrible.
9662FinishedParams:
9663 if (!Valid) {
9664 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9665 << FnDecl->getDeclName();
9666 return true;
9667 }
9668
Douglas Gregor1155c422011-08-30 22:40:35 +00009669 StringRef LiteralName
9670 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9671 if (LiteralName[0] != '_') {
9672 // C++0x [usrlit.suffix]p1:
9673 // Literal suffix identifiers that do not start with an underscore are
9674 // reserved for future standardization.
9675 bool IsHexFloat = true;
9676 if (LiteralName.size() > 1 &&
9677 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9678 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9679 if (!isdigit(LiteralName[I])) {
9680 IsHexFloat = false;
9681 break;
9682 }
9683 }
9684 }
9685
9686 if (IsHexFloat)
9687 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9688 << LiteralName;
9689 else
9690 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9691 }
9692
Sean Hunta6c058d2010-01-13 09:01:02 +00009693 return false;
9694}
9695
Douglas Gregor074149e2009-01-05 19:45:36 +00009696/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9697/// linkage specification, including the language and (if present)
9698/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9699/// the location of the language string literal, which is provided
9700/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9701/// the '{' brace. Otherwise, this linkage specification does not
9702/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009703Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9704 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009705 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009706 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009707 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009708 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009709 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009710 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009711 Language = LinkageSpecDecl::lang_cxx;
9712 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009713 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009714 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009715 }
Mike Stump1eb44332009-09-09 15:08:12 +00009716
Chris Lattnercc98eac2008-12-17 07:13:27 +00009717 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009718
Douglas Gregor074149e2009-01-05 19:45:36 +00009719 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009720 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009721 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009722 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009723 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009724}
9725
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009726/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009727/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9728/// valid, it's the position of the closing '}' brace in a linkage
9729/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009730Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009731 Decl *LinkageSpec,
9732 SourceLocation RBraceLoc) {
9733 if (LinkageSpec) {
9734 if (RBraceLoc.isValid()) {
9735 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9736 LSDecl->setRBraceLoc(RBraceLoc);
9737 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009738 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009739 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009740 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009741}
9742
Douglas Gregord308e622009-05-18 20:51:54 +00009743/// \brief Perform semantic analysis for the variable declaration that
9744/// occurs within a C++ catch clause, returning the newly-created
9745/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009746VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009747 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009748 SourceLocation StartLoc,
9749 SourceLocation Loc,
9750 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009751 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009752 QualType ExDeclType = TInfo->getType();
9753
Sebastian Redl4b07b292008-12-22 19:15:10 +00009754 // Arrays and functions decay.
9755 if (ExDeclType->isArrayType())
9756 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9757 else if (ExDeclType->isFunctionType())
9758 ExDeclType = Context.getPointerType(ExDeclType);
9759
9760 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9761 // The exception-declaration shall not denote a pointer or reference to an
9762 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009763 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009764 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009765 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009766 Invalid = true;
9767 }
Douglas Gregord308e622009-05-18 20:51:54 +00009768
Sebastian Redl4b07b292008-12-22 19:15:10 +00009769 QualType BaseType = ExDeclType;
9770 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009771 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009772 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009773 BaseType = Ptr->getPointeeType();
9774 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009775 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009776 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009777 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009778 BaseType = Ref->getPointeeType();
9779 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009780 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009781 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009782 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009783 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009784 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009785
Mike Stump1eb44332009-09-09 15:08:12 +00009786 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009787 RequireNonAbstractType(Loc, ExDeclType,
9788 diag::err_abstract_type_in_decl,
9789 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009790 Invalid = true;
9791
John McCall5a180392010-07-24 00:37:23 +00009792 // Only the non-fragile NeXT runtime currently supports C++ catches
9793 // of ObjC types, and no runtime supports catching ObjC types by value.
9794 if (!Invalid && getLangOptions().ObjC1) {
9795 QualType T = ExDeclType;
9796 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9797 T = RT->getPointeeType();
9798
9799 if (T->isObjCObjectType()) {
9800 Diag(Loc, diag::err_objc_object_catch);
9801 Invalid = true;
9802 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009803 if (!getLangOptions().ObjCNonFragileABI)
9804 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009805 }
9806 }
9807
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009808 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9809 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009810 ExDecl->setExceptionVariable(true);
9811
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009812 // In ARC, infer 'retaining' for variables of retainable type.
9813 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9814 Invalid = true;
9815
Douglas Gregorc41b8782011-07-06 18:14:43 +00009816 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009817 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009818 // C++ [except.handle]p16:
9819 // The object declared in an exception-declaration or, if the
9820 // exception-declaration does not specify a name, a temporary (12.2) is
9821 // copy-initialized (8.5) from the exception object. [...]
9822 // The object is destroyed when the handler exits, after the destruction
9823 // of any automatic objects initialized within the handler.
9824 //
9825 // We just pretend to initialize the object with itself, then make sure
9826 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009827 QualType initType = ExDeclType;
9828
9829 InitializedEntity entity =
9830 InitializedEntity::InitializeVariable(ExDecl);
9831 InitializationKind initKind =
9832 InitializationKind::CreateCopy(Loc, SourceLocation());
9833
9834 Expr *opaqueValue =
9835 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9836 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9837 ExprResult result = sequence.Perform(*this, entity, initKind,
9838 MultiExprArg(&opaqueValue, 1));
9839 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009840 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009841 else {
9842 // If the constructor used was non-trivial, set this as the
9843 // "initializer".
9844 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9845 if (!construct->getConstructor()->isTrivial()) {
9846 Expr *init = MaybeCreateExprWithCleanups(construct);
9847 ExDecl->setInit(init);
9848 }
9849
9850 // And make sure it's destructable.
9851 FinalizeVarWithDestructor(ExDecl, recordType);
9852 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009853 }
9854 }
9855
Douglas Gregord308e622009-05-18 20:51:54 +00009856 if (Invalid)
9857 ExDecl->setInvalidDecl();
9858
9859 return ExDecl;
9860}
9861
9862/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9863/// handler.
John McCalld226f652010-08-21 09:40:31 +00009864Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009865 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009866 bool Invalid = D.isInvalidType();
9867
9868 // Check for unexpanded parameter packs.
9869 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9870 UPPC_ExceptionType)) {
9871 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9872 D.getIdentifierLoc());
9873 Invalid = true;
9874 }
9875
Sebastian Redl4b07b292008-12-22 19:15:10 +00009876 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009877 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009878 LookupOrdinaryName,
9879 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009880 // The scope should be freshly made just for us. There is just no way
9881 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009882 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009883 if (PrevDecl->isTemplateParameter()) {
9884 // Maybe we will complain about the shadowed template parameter.
9885 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009886 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009887 }
9888 }
9889
Chris Lattnereaaebc72009-04-25 08:06:05 +00009890 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009891 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9892 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009893 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009894 }
9895
Douglas Gregor83cb9422010-09-09 17:09:21 +00009896 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009897 D.getSourceRange().getBegin(),
9898 D.getIdentifierLoc(),
9899 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009900 if (Invalid)
9901 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009902
Sebastian Redl4b07b292008-12-22 19:15:10 +00009903 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009904 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009905 PushOnScopeChains(ExDecl, S);
9906 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009907 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009908
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009909 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009910 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009911}
Anders Carlssonfb311762009-03-14 00:25:26 +00009912
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009913Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009914 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009915 Expr *AssertMessageExpr_,
9916 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009917 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009918
Anders Carlssonc3082412009-03-14 00:33:21 +00009919 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009920 // In a static_assert-declaration, the constant-expression shall be a
9921 // constant expression that can be contextually converted to bool.
9922 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9923 if (Converted.isInvalid())
9924 return 0;
9925
Richard Smithdaaefc52011-12-14 23:32:26 +00009926 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009927 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9928 PDiag(diag::err_static_assert_expression_is_not_constant),
9929 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009930 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009931
Richard Smithdaaefc52011-12-14 23:32:26 +00009932 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009933 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009934 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009935 }
Mike Stump1eb44332009-09-09 15:08:12 +00009936
Douglas Gregor399ad972010-12-15 23:55:21 +00009937 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9938 return 0;
9939
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009940 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9941 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009942
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009943 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009944 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009945}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009946
Douglas Gregor1d869352010-04-07 16:53:43 +00009947/// \brief Perform semantic analysis of the given friend type declaration.
9948///
9949/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009950FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9951 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009952 TypeSourceInfo *TSInfo) {
9953 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9954
9955 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009956 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009957
Richard Smith6b130222011-10-18 21:39:00 +00009958 // C++03 [class.friend]p2:
9959 // An elaborated-type-specifier shall be used in a friend declaration
9960 // for a class.*
9961 //
9962 // * The class-key of the elaborated-type-specifier is required.
9963 if (!ActiveTemplateInstantiations.empty()) {
9964 // Do not complain about the form of friend template types during
9965 // template instantiation; we will already have complained when the
9966 // template was declared.
9967 } else if (!T->isElaboratedTypeSpecifier()) {
9968 // If we evaluated the type to a record type, suggest putting
9969 // a tag in front.
9970 if (const RecordType *RT = T->getAs<RecordType>()) {
9971 RecordDecl *RD = RT->getDecl();
9972
9973 std::string InsertionText = std::string(" ") + RD->getKindName();
9974
9975 Diag(TypeRange.getBegin(),
9976 getLangOptions().CPlusPlus0x ?
9977 diag::warn_cxx98_compat_unelaborated_friend_type :
9978 diag::ext_unelaborated_friend_type)
9979 << (unsigned) RD->getTagKind()
9980 << T
9981 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9982 InsertionText);
9983 } else {
9984 Diag(FriendLoc,
9985 getLangOptions().CPlusPlus0x ?
9986 diag::warn_cxx98_compat_nonclass_type_friend :
9987 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009988 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009989 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009990 }
Richard Smith6b130222011-10-18 21:39:00 +00009991 } else if (T->getAs<EnumType>()) {
9992 Diag(FriendLoc,
9993 getLangOptions().CPlusPlus0x ?
9994 diag::warn_cxx98_compat_enum_friend :
9995 diag::ext_enum_friend)
9996 << T
9997 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009998 }
9999
Douglas Gregor06245bf2010-04-07 17:57:12 +000010000 // C++0x [class.friend]p3:
10001 // If the type specifier in a friend declaration designates a (possibly
10002 // cv-qualified) class type, that class is declared as a friend; otherwise,
10003 // the friend declaration is ignored.
10004
10005 // FIXME: C++0x has some syntactic restrictions on friend type declarations
10006 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +000010007
Abramo Bagnara0216df82011-10-29 20:52:52 +000010008 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010009}
10010
John McCall9a34edb2010-10-19 01:40:49 +000010011/// Handle a friend tag declaration where the scope specifier was
10012/// templated.
10013Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10014 unsigned TagSpec, SourceLocation TagLoc,
10015 CXXScopeSpec &SS,
10016 IdentifierInfo *Name, SourceLocation NameLoc,
10017 AttributeList *Attr,
10018 MultiTemplateParamsArg TempParamLists) {
10019 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10020
10021 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010022 bool Invalid = false;
10023
10024 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010025 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +000010026 TempParamLists.get(),
10027 TempParamLists.size(),
10028 /*friend*/ true,
10029 isExplicitSpecialization,
10030 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010031 if (TemplateParams->size() > 0) {
10032 // This is a declaration of a class template.
10033 if (Invalid)
10034 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010035
Eric Christopher4110e132011-07-21 05:34:24 +000010036 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10037 SS, Name, NameLoc, Attr,
10038 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010039 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010040 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010041 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010042 } else {
10043 // The "template<>" header is extraneous.
10044 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10045 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10046 isExplicitSpecialization = true;
10047 }
10048 }
10049
10050 if (Invalid) return 0;
10051
John McCall9a34edb2010-10-19 01:40:49 +000010052 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010053 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +000010054 if (TempParamLists.get()[I]->size()) {
10055 isAllExplicitSpecializations = false;
10056 break;
10057 }
10058 }
10059
10060 // FIXME: don't ignore attributes.
10061
10062 // If it's explicit specializations all the way down, just forget
10063 // about the template header and build an appropriate non-templated
10064 // friend. TODO: for source fidelity, remember the headers.
10065 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010066 if (SS.isEmpty()) {
10067 bool Owned = false;
10068 bool IsDependent = false;
10069 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10070 Attr, AS_public,
10071 /*ModulePrivateLoc=*/SourceLocation(),
10072 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010073 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010074 /*ScopedEnumUsesClassTag=*/false,
10075 /*UnderlyingType=*/TypeResult());
10076 }
10077
Douglas Gregor2494dd02011-03-01 01:34:45 +000010078 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010079 ElaboratedTypeKeyword Keyword
10080 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010081 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010082 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010083 if (T.isNull())
10084 return 0;
10085
10086 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10087 if (isa<DependentNameType>(T)) {
10088 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10089 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010090 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010091 TL.setNameLoc(NameLoc);
10092 } else {
10093 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
10094 TL.setKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010095 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010096 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10097 }
10098
10099 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10100 TSI, FriendLoc);
10101 Friend->setAccess(AS_public);
10102 CurContext->addDecl(Friend);
10103 return Friend;
10104 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010105
10106 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10107
10108
John McCall9a34edb2010-10-19 01:40:49 +000010109
10110 // Handle the case of a templated-scope friend class. e.g.
10111 // template <class T> class A<T>::B;
10112 // FIXME: we don't support these right now.
10113 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10114 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10115 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10116 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10117 TL.setKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010118 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010119 TL.setNameLoc(NameLoc);
10120
10121 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10122 TSI, FriendLoc);
10123 Friend->setAccess(AS_public);
10124 Friend->setUnsupportedFriend(true);
10125 CurContext->addDecl(Friend);
10126 return Friend;
10127}
10128
10129
John McCalldd4a3b02009-09-16 22:47:08 +000010130/// Handle a friend type declaration. This works in tandem with
10131/// ActOnTag.
10132///
10133/// Notes on friend class templates:
10134///
10135/// We generally treat friend class declarations as if they were
10136/// declaring a class. So, for example, the elaborated type specifier
10137/// in a friend declaration is required to obey the restrictions of a
10138/// class-head (i.e. no typedefs in the scope chain), template
10139/// parameters are required to match up with simple template-ids, &c.
10140/// However, unlike when declaring a template specialization, it's
10141/// okay to refer to a template specialization without an empty
10142/// template parameter declaration, e.g.
10143/// friend class A<T>::B<unsigned>;
10144/// We permit this as a special case; if there are any template
10145/// parameters present at all, require proper matching, i.e.
10146/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010147Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010148 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +000010149 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +000010150
10151 assert(DS.isFriendSpecified());
10152 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10153
John McCalldd4a3b02009-09-16 22:47:08 +000010154 // Try to convert the decl specifier to a type. This works for
10155 // friend templates because ActOnTag never produces a ClassTemplateDecl
10156 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010157 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010158 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10159 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010160 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010161 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010162
Douglas Gregor6ccab972010-12-16 01:14:37 +000010163 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10164 return 0;
10165
John McCalldd4a3b02009-09-16 22:47:08 +000010166 // This is definitely an error in C++98. It's probably meant to
10167 // be forbidden in C++0x, too, but the specification is just
10168 // poorly written.
10169 //
10170 // The problem is with declarations like the following:
10171 // template <T> friend A<T>::foo;
10172 // where deciding whether a class C is a friend or not now hinges
10173 // on whether there exists an instantiation of A that causes
10174 // 'foo' to equal C. There are restrictions on class-heads
10175 // (which we declare (by fiat) elaborated friend declarations to
10176 // be) that makes this tractable.
10177 //
10178 // FIXME: handle "template <> friend class A<T>;", which
10179 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010180 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010181 Diag(Loc, diag::err_tagless_friend_type_template)
10182 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010183 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010184 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010185
John McCall02cace72009-08-28 07:59:38 +000010186 // C++98 [class.friend]p1: A friend of a class is a function
10187 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010188 // This is fixed in DR77, which just barely didn't make the C++03
10189 // deadline. It's also a very silly restriction that seriously
10190 // affects inner classes and which nobody else seems to implement;
10191 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010192 //
10193 // But note that we could warn about it: it's always useless to
10194 // friend one of your own members (it's not, however, worthless to
10195 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010196
John McCalldd4a3b02009-09-16 22:47:08 +000010197 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010198 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010199 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010200 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010201 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010202 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010203 DS.getFriendSpecLoc());
10204 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010205 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010206
10207 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010208 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010209
John McCalldd4a3b02009-09-16 22:47:08 +000010210 D->setAccess(AS_public);
10211 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010212
John McCalld226f652010-08-21 09:40:31 +000010213 return D;
John McCall02cace72009-08-28 07:59:38 +000010214}
10215
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010216Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010217 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010218 const DeclSpec &DS = D.getDeclSpec();
10219
10220 assert(DS.isFriendSpecified());
10221 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10222
10223 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010224 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010225
10226 // C++ [class.friend]p1
10227 // A friend of a class is a function or class....
10228 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010229 // It *doesn't* see through dependent types, which is correct
10230 // according to [temp.arg.type]p3:
10231 // If a declaration acquires a function type through a
10232 // type dependent on a template-parameter and this causes
10233 // a declaration that does not use the syntactic form of a
10234 // function declarator to have a function type, the program
10235 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010236 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010237 Diag(Loc, diag::err_unexpected_friend);
10238
10239 // It might be worthwhile to try to recover by creating an
10240 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010241 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010242 }
10243
10244 // C++ [namespace.memdef]p3
10245 // - If a friend declaration in a non-local class first declares a
10246 // class or function, the friend class or function is a member
10247 // of the innermost enclosing namespace.
10248 // - The name of the friend is not found by simple name lookup
10249 // until a matching declaration is provided in that namespace
10250 // scope (either before or after the class declaration granting
10251 // friendship).
10252 // - If a friend function is called, its name may be found by the
10253 // name lookup that considers functions from namespaces and
10254 // classes associated with the types of the function arguments.
10255 // - When looking for a prior declaration of a class or a function
10256 // declared as a friend, scopes outside the innermost enclosing
10257 // namespace scope are not considered.
10258
John McCall337ec3d2010-10-12 23:13:28 +000010259 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010260 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10261 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010262 assert(Name);
10263
Douglas Gregor6ccab972010-12-16 01:14:37 +000010264 // Check for unexpanded parameter packs.
10265 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10266 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10267 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10268 return 0;
10269
John McCall67d1a672009-08-06 02:15:43 +000010270 // The context we found the declaration in, or in which we should
10271 // create the declaration.
10272 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010273 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010274 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010275 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010276
John McCall337ec3d2010-10-12 23:13:28 +000010277 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010278
John McCall337ec3d2010-10-12 23:13:28 +000010279 // There are four cases here.
10280 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010281 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010282 // there as appropriate.
10283 // Recover from invalid scope qualifiers as if they just weren't there.
10284 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010285 // C++0x [namespace.memdef]p3:
10286 // If the name in a friend declaration is neither qualified nor
10287 // a template-id and the declaration is a function or an
10288 // elaborated-type-specifier, the lookup to determine whether
10289 // the entity has been previously declared shall not consider
10290 // any scopes outside the innermost enclosing namespace.
10291 // C++0x [class.friend]p11:
10292 // If a friend declaration appears in a local class and the name
10293 // specified is an unqualified name, a prior declaration is
10294 // looked up without considering scopes that are outside the
10295 // innermost enclosing non-class scope. For a friend function
10296 // declaration, if there is no prior declaration, the program is
10297 // ill-formed.
10298 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010299 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010300
John McCall29ae6e52010-10-13 05:45:15 +000010301 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010302 DC = CurContext;
10303 while (true) {
10304 // Skip class contexts. If someone can cite chapter and verse
10305 // for this behavior, that would be nice --- it's what GCC and
10306 // EDG do, and it seems like a reasonable intent, but the spec
10307 // really only says that checks for unqualified existing
10308 // declarations should stop at the nearest enclosing namespace,
10309 // not that they should only consider the nearest enclosing
10310 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010311 while (DC->isRecord())
10312 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010313
John McCall68263142009-11-18 22:49:29 +000010314 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010315
10316 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010317 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010318 break;
John McCall29ae6e52010-10-13 05:45:15 +000010319
John McCall8a407372010-10-14 22:22:28 +000010320 if (isTemplateId) {
10321 if (isa<TranslationUnitDecl>(DC)) break;
10322 } else {
10323 if (DC->isFileContext()) break;
10324 }
John McCall67d1a672009-08-06 02:15:43 +000010325 DC = DC->getParent();
10326 }
10327
10328 // C++ [class.friend]p1: A friend of a class is a function or
10329 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010330 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010331 // Most C++ 98 compilers do seem to give an error here, so
10332 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010333 if (!Previous.empty() && DC->Equals(CurContext))
10334 Diag(DS.getFriendSpecLoc(),
10335 getLangOptions().CPlusPlus0x ?
10336 diag::warn_cxx98_compat_friend_is_member :
10337 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010338
John McCall380aaa42010-10-13 06:22:15 +000010339 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010340
Douglas Gregor883af832011-10-10 01:11:59 +000010341 // C++ [class.friend]p6:
10342 // A function can be defined in a friend declaration of a class if and
10343 // only if the class is a non-local class (9.8), the function name is
10344 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010345 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010346 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10347 }
10348
John McCall337ec3d2010-10-12 23:13:28 +000010349 // - There's a non-dependent scope specifier, in which case we
10350 // compute it and do a previous lookup there for a function
10351 // or function template.
10352 } else if (!SS.getScopeRep()->isDependent()) {
10353 DC = computeDeclContext(SS);
10354 if (!DC) return 0;
10355
10356 if (RequireCompleteDeclContext(SS, DC)) return 0;
10357
10358 LookupQualifiedName(Previous, DC);
10359
10360 // Ignore things found implicitly in the wrong scope.
10361 // TODO: better diagnostics for this case. Suggesting the right
10362 // qualified scope would be nice...
10363 LookupResult::Filter F = Previous.makeFilter();
10364 while (F.hasNext()) {
10365 NamedDecl *D = F.next();
10366 if (!DC->InEnclosingNamespaceSetOf(
10367 D->getDeclContext()->getRedeclContext()))
10368 F.erase();
10369 }
10370 F.done();
10371
10372 if (Previous.empty()) {
10373 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010374 Diag(Loc, diag::err_qualified_friend_not_found)
10375 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010376 return 0;
10377 }
10378
10379 // C++ [class.friend]p1: A friend of a class is a function or
10380 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010381 if (DC->Equals(CurContext))
10382 Diag(DS.getFriendSpecLoc(),
10383 getLangOptions().CPlusPlus0x ?
10384 diag::warn_cxx98_compat_friend_is_member :
10385 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010386
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010387 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010388 // C++ [class.friend]p6:
10389 // A function can be defined in a friend declaration of a class if and
10390 // only if the class is a non-local class (9.8), the function name is
10391 // unqualified, and the function has namespace scope.
10392 SemaDiagnosticBuilder DB
10393 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10394
10395 DB << SS.getScopeRep();
10396 if (DC->isFileContext())
10397 DB << FixItHint::CreateRemoval(SS.getRange());
10398 SS.clear();
10399 }
John McCall337ec3d2010-10-12 23:13:28 +000010400
10401 // - There's a scope specifier that does not match any template
10402 // parameter lists, in which case we use some arbitrary context,
10403 // create a method or method template, and wait for instantiation.
10404 // - There's a scope specifier that does match some template
10405 // parameter lists, which we don't handle right now.
10406 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010407 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010408 // C++ [class.friend]p6:
10409 // A function can be defined in a friend declaration of a class if and
10410 // only if the class is a non-local class (9.8), the function name is
10411 // unqualified, and the function has namespace scope.
10412 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10413 << SS.getScopeRep();
10414 }
10415
John McCall337ec3d2010-10-12 23:13:28 +000010416 DC = CurContext;
10417 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010418 }
Douglas Gregor883af832011-10-10 01:11:59 +000010419
John McCall29ae6e52010-10-13 05:45:15 +000010420 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010421 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010422 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10423 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10424 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010425 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010426 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10427 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010428 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010429 }
John McCall67d1a672009-08-06 02:15:43 +000010430 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010431
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010432 // FIXME: This is an egregious hack to cope with cases where the scope stack
10433 // does not contain the declaration context, i.e., in an out-of-line
10434 // definition of a class.
10435 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10436 if (!DCScope) {
10437 FakeDCScope.setEntity(DC);
10438 DCScope = &FakeDCScope;
10439 }
10440
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010441 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010442 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10443 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010444 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010445
Douglas Gregor182ddf02009-09-28 00:08:27 +000010446 assert(ND->getDeclContext() == DC);
10447 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010448
John McCallab88d972009-08-31 22:39:49 +000010449 // Add the function declaration to the appropriate lookup tables,
10450 // adjusting the redeclarations list as necessary. We don't
10451 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010452 //
John McCallab88d972009-08-31 22:39:49 +000010453 // Also update the scope-based lookup if the target context's
10454 // lookup context is in lexical scope.
10455 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010456 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010457 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010458 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010459 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010460 }
John McCall02cace72009-08-28 07:59:38 +000010461
10462 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010463 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010464 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010465 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010466 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010467
John McCall337ec3d2010-10-12 23:13:28 +000010468 if (ND->isInvalidDecl())
10469 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010470 else {
10471 FunctionDecl *FD;
10472 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10473 FD = FTD->getTemplatedDecl();
10474 else
10475 FD = cast<FunctionDecl>(ND);
10476
10477 // Mark templated-scope function declarations as unsupported.
10478 if (FD->getNumTemplateParameterLists())
10479 FrD->setUnsupportedFriend(true);
10480 }
John McCall337ec3d2010-10-12 23:13:28 +000010481
John McCalld226f652010-08-21 09:40:31 +000010482 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010483}
10484
John McCalld226f652010-08-21 09:40:31 +000010485void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10486 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010487
Sebastian Redl50de12f2009-03-24 22:27:57 +000010488 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10489 if (!Fn) {
10490 Diag(DelLoc, diag::err_deleted_non_function);
10491 return;
10492 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010493 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010494 Diag(DelLoc, diag::err_deleted_decl_not_first);
10495 Diag(Prev->getLocation(), diag::note_previous_declaration);
10496 // If the declaration wasn't the first, we delete the function anyway for
10497 // recovery.
10498 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010499 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010500}
Sebastian Redl13e88542009-04-27 21:33:24 +000010501
Sean Hunte4246a62011-05-12 06:15:49 +000010502void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10503 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10504
10505 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010506 if (MD->getParent()->isDependentType()) {
10507 MD->setDefaulted();
10508 MD->setExplicitlyDefaulted();
10509 return;
10510 }
10511
Sean Hunte4246a62011-05-12 06:15:49 +000010512 CXXSpecialMember Member = getSpecialMember(MD);
10513 if (Member == CXXInvalid) {
10514 Diag(DefaultLoc, diag::err_default_special_members);
10515 return;
10516 }
10517
10518 MD->setDefaulted();
10519 MD->setExplicitlyDefaulted();
10520
Sean Huntcd10dec2011-05-23 23:14:04 +000010521 // If this definition appears within the record, do the checking when
10522 // the record is complete.
10523 const FunctionDecl *Primary = MD;
10524 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10525 // Find the uninstantiated declaration that actually had the '= default'
10526 // on it.
10527 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10528
10529 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010530 return;
10531
10532 switch (Member) {
10533 case CXXDefaultConstructor: {
10534 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10535 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010536 if (!CD->isInvalidDecl())
10537 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10538 break;
10539 }
10540
10541 case CXXCopyConstructor: {
10542 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10543 CheckExplicitlyDefaultedCopyConstructor(CD);
10544 if (!CD->isInvalidDecl())
10545 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010546 break;
10547 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010548
Sean Hunt2b188082011-05-14 05:23:28 +000010549 case CXXCopyAssignment: {
10550 CheckExplicitlyDefaultedCopyAssignment(MD);
10551 if (!MD->isInvalidDecl())
10552 DefineImplicitCopyAssignment(DefaultLoc, MD);
10553 break;
10554 }
10555
Sean Huntcb45a0f2011-05-12 22:46:25 +000010556 case CXXDestructor: {
10557 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10558 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010559 if (!DD->isInvalidDecl())
10560 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010561 break;
10562 }
10563
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010564 case CXXMoveConstructor: {
10565 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10566 CheckExplicitlyDefaultedMoveConstructor(CD);
10567 if (!CD->isInvalidDecl())
10568 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010569 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010570 }
Sean Hunt82713172011-05-25 23:16:36 +000010571
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010572 case CXXMoveAssignment: {
10573 CheckExplicitlyDefaultedMoveAssignment(MD);
10574 if (!MD->isInvalidDecl())
10575 DefineImplicitMoveAssignment(DefaultLoc, MD);
10576 break;
10577 }
10578
10579 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010580 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010581 }
10582 } else {
10583 Diag(DefaultLoc, diag::err_default_special_members);
10584 }
10585}
10586
Sebastian Redl13e88542009-04-27 21:33:24 +000010587static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010588 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010589 Stmt *SubStmt = *CI;
10590 if (!SubStmt)
10591 continue;
10592 if (isa<ReturnStmt>(SubStmt))
10593 Self.Diag(SubStmt->getSourceRange().getBegin(),
10594 diag::err_return_in_constructor_handler);
10595 if (!isa<Expr>(SubStmt))
10596 SearchForReturnInStmt(Self, SubStmt);
10597 }
10598}
10599
10600void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10601 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10602 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10603 SearchForReturnInStmt(*this, Handler);
10604 }
10605}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010606
Mike Stump1eb44332009-09-09 15:08:12 +000010607bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010608 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010609 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10610 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010611
Chandler Carruth73857792010-02-15 11:53:20 +000010612 if (Context.hasSameType(NewTy, OldTy) ||
10613 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010614 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010615
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010616 // Check if the return types are covariant
10617 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010618
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010619 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010620 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10621 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010622 NewClassTy = NewPT->getPointeeType();
10623 OldClassTy = OldPT->getPointeeType();
10624 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010625 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10626 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10627 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10628 NewClassTy = NewRT->getPointeeType();
10629 OldClassTy = OldRT->getPointeeType();
10630 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010631 }
10632 }
Mike Stump1eb44332009-09-09 15:08:12 +000010633
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010634 // The return types aren't either both pointers or references to a class type.
10635 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010636 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010637 diag::err_different_return_type_for_overriding_virtual_function)
10638 << New->getDeclName() << NewTy << OldTy;
10639 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010640
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010641 return true;
10642 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010643
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010644 // C++ [class.virtual]p6:
10645 // If the return type of D::f differs from the return type of B::f, the
10646 // class type in the return type of D::f shall be complete at the point of
10647 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010648 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10649 if (!RT->isBeingDefined() &&
10650 RequireCompleteType(New->getLocation(), NewClassTy,
10651 PDiag(diag::err_covariant_return_incomplete)
10652 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010653 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010654 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010655
Douglas Gregora4923eb2009-11-16 21:35:15 +000010656 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010657 // Check if the new class derives from the old class.
10658 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10659 Diag(New->getLocation(),
10660 diag::err_covariant_return_not_derived)
10661 << New->getDeclName() << NewTy << OldTy;
10662 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10663 return true;
10664 }
Mike Stump1eb44332009-09-09 15:08:12 +000010665
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010666 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010667 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010668 diag::err_covariant_return_inaccessible_base,
10669 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10670 // FIXME: Should this point to the return type?
10671 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010672 // FIXME: this note won't trigger for delayed access control
10673 // diagnostics, and it's impossible to get an undelayed error
10674 // here from access control during the original parse because
10675 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010676 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10677 return true;
10678 }
10679 }
Mike Stump1eb44332009-09-09 15:08:12 +000010680
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010681 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010682 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010683 Diag(New->getLocation(),
10684 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010685 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010686 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10687 return true;
10688 };
Mike Stump1eb44332009-09-09 15:08:12 +000010689
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010690
10691 // The new class type must have the same or less qualifiers as the old type.
10692 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10693 Diag(New->getLocation(),
10694 diag::err_covariant_return_type_class_type_more_qualified)
10695 << New->getDeclName() << NewTy << OldTy;
10696 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10697 return true;
10698 };
Mike Stump1eb44332009-09-09 15:08:12 +000010699
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010700 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010701}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010702
Douglas Gregor4ba31362009-12-01 17:24:26 +000010703/// \brief Mark the given method pure.
10704///
10705/// \param Method the method to be marked pure.
10706///
10707/// \param InitRange the source range that covers the "0" initializer.
10708bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010709 SourceLocation EndLoc = InitRange.getEnd();
10710 if (EndLoc.isValid())
10711 Method->setRangeEnd(EndLoc);
10712
Douglas Gregor4ba31362009-12-01 17:24:26 +000010713 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10714 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010715 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010716 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010717
10718 if (!Method->isInvalidDecl())
10719 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10720 << Method->getDeclName() << InitRange;
10721 return true;
10722}
10723
John McCall731ad842009-12-19 09:28:58 +000010724/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10725/// an initializer for the out-of-line declaration 'Dcl'. The scope
10726/// is a fresh scope pushed for just this purpose.
10727///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010728/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10729/// static data member of class X, names should be looked up in the scope of
10730/// class X.
John McCalld226f652010-08-21 09:40:31 +000010731void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010732 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010733 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010734
John McCall731ad842009-12-19 09:28:58 +000010735 // We should only get called for declarations with scope specifiers, like:
10736 // int foo::bar;
10737 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010738 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010739}
10740
10741/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010742/// initializer for the out-of-line declaration 'D'.
10743void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010744 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010745 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010746
John McCall731ad842009-12-19 09:28:58 +000010747 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010748 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010749}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010750
10751/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10752/// C++ if/switch/while/for statement.
10753/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010754DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010755 // C++ 6.4p2:
10756 // The declarator shall not specify a function or an array.
10757 // The type-specifier-seq shall not contain typedef and shall not declare a
10758 // new class or enumeration.
10759 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10760 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010761
10762 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010763 if (!Dcl)
10764 return true;
10765
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010766 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10767 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010768 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010769 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010770 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010771
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010772 return Dcl;
10773}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010774
Douglas Gregordfe65432011-07-28 19:11:31 +000010775void Sema::LoadExternalVTableUses() {
10776 if (!ExternalSource)
10777 return;
10778
10779 SmallVector<ExternalVTableUse, 4> VTables;
10780 ExternalSource->ReadUsedVTables(VTables);
10781 SmallVector<VTableUse, 4> NewUses;
10782 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10783 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10784 = VTablesUsed.find(VTables[I].Record);
10785 // Even if a definition wasn't required before, it may be required now.
10786 if (Pos != VTablesUsed.end()) {
10787 if (!Pos->second && VTables[I].DefinitionRequired)
10788 Pos->second = true;
10789 continue;
10790 }
10791
10792 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10793 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10794 }
10795
10796 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10797}
10798
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010799void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10800 bool DefinitionRequired) {
10801 // Ignore any vtable uses in unevaluated operands or for classes that do
10802 // not have a vtable.
10803 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10804 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010805 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010806 return;
10807
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010808 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010809 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010810 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10811 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10812 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10813 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010814 // If we already had an entry, check to see if we are promoting this vtable
10815 // to required a definition. If so, we need to reappend to the VTableUses
10816 // list, since we may have already processed the first entry.
10817 if (DefinitionRequired && !Pos.first->second) {
10818 Pos.first->second = true;
10819 } else {
10820 // Otherwise, we can early exit.
10821 return;
10822 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010823 }
10824
10825 // Local classes need to have their virtual members marked
10826 // immediately. For all other classes, we mark their virtual members
10827 // at the end of the translation unit.
10828 if (Class->isLocalClass())
10829 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010830 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010831 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010832}
10833
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010834bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010835 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010836 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010837 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010838
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010839 // Note: The VTableUses vector could grow as a result of marking
10840 // the members of a class as "used", so we check the size each
10841 // time through the loop and prefer indices (with are stable) to
10842 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010843 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010844 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010845 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010846 if (!Class)
10847 continue;
10848
10849 SourceLocation Loc = VTableUses[I].second;
10850
10851 // If this class has a key function, but that key function is
10852 // defined in another translation unit, we don't need to emit the
10853 // vtable even though we're using it.
10854 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010855 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010856 switch (KeyFunction->getTemplateSpecializationKind()) {
10857 case TSK_Undeclared:
10858 case TSK_ExplicitSpecialization:
10859 case TSK_ExplicitInstantiationDeclaration:
10860 // The key function is in another translation unit.
10861 continue;
10862
10863 case TSK_ExplicitInstantiationDefinition:
10864 case TSK_ImplicitInstantiation:
10865 // We will be instantiating the key function.
10866 break;
10867 }
10868 } else if (!KeyFunction) {
10869 // If we have a class with no key function that is the subject
10870 // of an explicit instantiation declaration, suppress the
10871 // vtable; it will live with the explicit instantiation
10872 // definition.
10873 bool IsExplicitInstantiationDeclaration
10874 = Class->getTemplateSpecializationKind()
10875 == TSK_ExplicitInstantiationDeclaration;
10876 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10877 REnd = Class->redecls_end();
10878 R != REnd; ++R) {
10879 TemplateSpecializationKind TSK
10880 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10881 if (TSK == TSK_ExplicitInstantiationDeclaration)
10882 IsExplicitInstantiationDeclaration = true;
10883 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10884 IsExplicitInstantiationDeclaration = false;
10885 break;
10886 }
10887 }
10888
10889 if (IsExplicitInstantiationDeclaration)
10890 continue;
10891 }
10892
10893 // Mark all of the virtual members of this class as referenced, so
10894 // that we can build a vtable. Then, tell the AST consumer that a
10895 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010896 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010897 MarkVirtualMembersReferenced(Loc, Class);
10898 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10899 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10900
10901 // Optionally warn if we're emitting a weak vtable.
10902 if (Class->getLinkage() == ExternalLinkage &&
10903 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010904 const FunctionDecl *KeyFunctionDef = 0;
10905 if (!KeyFunction ||
10906 (KeyFunction->hasBody(KeyFunctionDef) &&
10907 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010908 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10909 TSK_ExplicitInstantiationDefinition
10910 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10911 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010912 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010913 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010914 VTableUses.clear();
10915
Douglas Gregor78844032011-04-22 22:25:37 +000010916 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010917}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010918
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010919void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10920 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010921 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10922 e = RD->method_end(); i != e; ++i) {
10923 CXXMethodDecl *MD = *i;
10924
10925 // C++ [basic.def.odr]p2:
10926 // [...] A virtual member function is used if it is not pure. [...]
10927 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010928 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010929 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010930
10931 // Only classes that have virtual bases need a VTT.
10932 if (RD->getNumVBases() == 0)
10933 return;
10934
10935 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10936 e = RD->bases_end(); i != e; ++i) {
10937 const CXXRecordDecl *Base =
10938 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010939 if (Base->getNumVBases() == 0)
10940 continue;
10941 MarkVirtualMembersReferenced(Loc, Base);
10942 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010943}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010944
10945/// SetIvarInitializers - This routine builds initialization ASTs for the
10946/// Objective-C implementation whose ivars need be initialized.
10947void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10948 if (!getLangOptions().CPlusPlus)
10949 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010950 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010951 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010952 CollectIvarsToConstructOrDestruct(OID, ivars);
10953 if (ivars.empty())
10954 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010955 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010956 for (unsigned i = 0; i < ivars.size(); i++) {
10957 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010958 if (Field->isInvalidDecl())
10959 continue;
10960
Sean Huntcbb67482011-01-08 20:30:50 +000010961 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010962 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10963 InitializationKind InitKind =
10964 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10965
10966 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010967 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010968 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010969 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010970 // Note, MemberInit could actually come back empty if no initialization
10971 // is required (e.g., because it would call a trivial default constructor)
10972 if (!MemberInit.get() || MemberInit.isInvalid())
10973 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010974
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010975 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010976 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10977 SourceLocation(),
10978 MemberInit.takeAs<Expr>(),
10979 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010980 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010981
10982 // Be sure that the destructor is accessible and is marked as referenced.
10983 if (const RecordType *RecordTy
10984 = Context.getBaseElementType(Field->getType())
10985 ->getAs<RecordType>()) {
10986 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010987 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010988 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010989 CheckDestructorAccess(Field->getLocation(), Destructor,
10990 PDiag(diag::err_access_dtor_ivar)
10991 << Context.getBaseElementType(Field->getType()));
10992 }
10993 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010994 }
10995 ObjCImplementation->setIvarInitializers(Context,
10996 AllToInit.data(), AllToInit.size());
10997 }
10998}
Sean Huntfe57eef2011-05-04 05:57:24 +000010999
Sean Huntebcbe1d2011-05-04 23:29:54 +000011000static
11001void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11002 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11003 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11004 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11005 Sema &S) {
11006 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11007 CE = Current.end();
11008 if (Ctor->isInvalidDecl())
11009 return;
11010
11011 const FunctionDecl *FNTarget = 0;
11012 CXXConstructorDecl *Target;
11013
11014 // We ignore the result here since if we don't have a body, Target will be
11015 // null below.
11016 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
11017 Target
11018= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
11019
11020 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11021 // Avoid dereferencing a null pointer here.
11022 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11023
11024 if (!Current.insert(Canonical))
11025 return;
11026
11027 // We know that beyond here, we aren't chaining into a cycle.
11028 if (!Target || !Target->isDelegatingConstructor() ||
11029 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11030 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11031 Valid.insert(*CI);
11032 Current.clear();
11033 // We've hit a cycle.
11034 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11035 Current.count(TCanonical)) {
11036 // If we haven't diagnosed this cycle yet, do so now.
11037 if (!Invalid.count(TCanonical)) {
11038 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011039 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011040 << Ctor;
11041
11042 // Don't add a note for a function delegating directo to itself.
11043 if (TCanonical != Canonical)
11044 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11045
11046 CXXConstructorDecl *C = Target;
11047 while (C->getCanonicalDecl() != Canonical) {
11048 (void)C->getTargetConstructor()->hasBody(FNTarget);
11049 assert(FNTarget && "Ctor cycle through bodiless function");
11050
11051 C
11052 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11053 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11054 }
11055 }
11056
11057 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11058 Invalid.insert(*CI);
11059 Current.clear();
11060 } else {
11061 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11062 }
11063}
11064
11065
Sean Huntfe57eef2011-05-04 05:57:24 +000011066void Sema::CheckDelegatingCtorCycles() {
11067 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11068
Sean Huntebcbe1d2011-05-04 23:29:54 +000011069 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11070 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011071
Douglas Gregor0129b562011-07-27 21:57:17 +000011072 for (DelegatingCtorDeclsType::iterator
11073 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011074 E = DelegatingCtorDecls.end();
11075 I != E; ++I) {
11076 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000011077 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011078
11079 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11080 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011081}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011082
11083/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11084Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11085 // Implicitly declared functions (e.g. copy constructors) are
11086 // __host__ __device__
11087 if (D->isImplicit())
11088 return CFT_HostDevice;
11089
11090 if (D->hasAttr<CUDAGlobalAttr>())
11091 return CFT_Global;
11092
11093 if (D->hasAttr<CUDADeviceAttr>()) {
11094 if (D->hasAttr<CUDAHostAttr>())
11095 return CFT_HostDevice;
11096 else
11097 return CFT_Device;
11098 }
11099
11100 return CFT_Host;
11101}
11102
11103bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11104 CUDAFunctionTarget CalleeTarget) {
11105 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11106 // Callable from the device only."
11107 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11108 return true;
11109
11110 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11111 // Callable from the host only."
11112 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11113 // Callable from the host only."
11114 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11115 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11116 return true;
11117
11118 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11119 return true;
11120
11121 return false;
11122}