blob: ca64af644f6f8813f58aee3a3cf28ea32b12e1c9 [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.
Richard Smith745f5142012-01-27 01:14:48 +0000987 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith925d8e72012-02-08 06:14:53 +0000988 if (!IsInstantiation && !Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith745f5142012-01-27 01:14:48 +0000989 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
990 << isa<CXXConstructorDecl>(Dcl);
991 for (size_t I = 0, N = Diags.size(); I != N; ++I)
992 Diag(Diags[I].first, Diags[I].second);
993 return false;
994 }
995
Richard Smith9f569cc2011-10-01 02:31:28 +0000996 return true;
997}
998
Douglas Gregorb48fe382008-10-31 09:07:45 +0000999/// isCurrentClassName - Determine whether the identifier II is the
1000/// name of the class type currently being defined. In the case of
1001/// nested classes, this will only return true if II is the name of
1002/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001003bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1004 const CXXScopeSpec *SS) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +00001005 assert(getLangOptions().CPlusPlus && "No class names in C!");
1006
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001007 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +00001008 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +00001009 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001010 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1011 } else
1012 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1013
Douglas Gregor6f7a17b2010-02-05 06:12:42 +00001014 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregorb48fe382008-10-31 09:07:45 +00001015 return &II == CurDecl->getIdentifier();
1016 else
1017 return false;
1018}
1019
Mike Stump1eb44332009-09-09 15:08:12 +00001020/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001021///
1022/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1023/// and returns NULL otherwise.
1024CXXBaseSpecifier *
1025Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1026 SourceRange SpecifierRange,
1027 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001028 TypeSourceInfo *TInfo,
1029 SourceLocation EllipsisLoc) {
Nick Lewycky56062202010-07-26 16:56:01 +00001030 QualType BaseType = TInfo->getType();
1031
Douglas Gregor2943aed2009-03-03 04:44:36 +00001032 // C++ [class.union]p1:
1033 // A union shall not have base classes.
1034 if (Class->isUnion()) {
1035 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1036 << SpecifierRange;
1037 return 0;
1038 }
1039
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001040 if (EllipsisLoc.isValid() &&
1041 !TInfo->getType()->containsUnexpandedParameterPack()) {
1042 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1043 << TInfo->getTypeLoc().getSourceRange();
1044 EllipsisLoc = SourceLocation();
1045 }
1046
Douglas Gregor2943aed2009-03-03 04:44:36 +00001047 if (BaseType->isDependentType())
Mike Stump1eb44332009-09-09 15:08:12 +00001048 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001049 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001050 Access, TInfo, EllipsisLoc);
Nick Lewycky56062202010-07-26 16:56:01 +00001051
1052 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001053
1054 // Base specifiers must be record types.
1055 if (!BaseType->isRecordType()) {
1056 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1057 return 0;
1058 }
1059
1060 // C++ [class.union]p1:
1061 // A union shall not be used as a base class.
1062 if (BaseType->isUnionType()) {
1063 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1064 return 0;
1065 }
1066
1067 // C++ [class.derived]p2:
1068 // The class-name in a base-specifier shall not be an incompletely
1069 // defined class.
Mike Stump1eb44332009-09-09 15:08:12 +00001070 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001071 PDiag(diag::err_incomplete_base_class)
John McCall572fc622010-08-17 07:23:57 +00001072 << SpecifierRange)) {
1073 Class->setInvalidDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001074 return 0;
John McCall572fc622010-08-17 07:23:57 +00001075 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001076
Eli Friedman1d954f62009-08-15 21:55:26 +00001077 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +00001078 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001079 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor952b0172010-02-11 01:04:33 +00001080 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor2943aed2009-03-03 04:44:36 +00001081 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +00001082 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1083 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedmand0137332009-12-05 23:03:49 +00001084
Anders Carlsson1d209272011-03-25 14:55:14 +00001085 // C++ [class]p3:
1086 // If a class is marked final and it appears as a base-type-specifier in
1087 // base-clause, the program is ill-formed.
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001088 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssondfc2f102011-01-22 17:51:53 +00001089 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1090 << CXXBaseDecl->getDeclName();
1091 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1092 << CXXBaseDecl->getDeclName();
1093 return 0;
1094 }
1095
John McCall572fc622010-08-17 07:23:57 +00001096 if (BaseDecl->isInvalidDecl())
1097 Class->setInvalidDecl();
Anders Carlsson51f94042009-12-03 17:49:57 +00001098
1099 // Create the base specifier.
Anders Carlsson51f94042009-12-03 17:49:57 +00001100 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky56062202010-07-26 16:56:01 +00001101 Class->getTagKind() == TTK_Class,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001102 Access, TInfo, EllipsisLoc);
Anders Carlsson51f94042009-12-03 17:49:57 +00001103}
1104
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001105/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1106/// one entry in the base class list of a class specifier, for
Mike Stump1eb44332009-09-09 15:08:12 +00001107/// example:
1108/// class foo : public bar, virtual private baz {
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001109/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallf312b1e2010-08-26 23:41:50 +00001110BaseResult
John McCalld226f652010-08-21 09:40:31 +00001111Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001112 bool Virtual, AccessSpecifier Access,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001113 ParsedType basetype, SourceLocation BaseLoc,
1114 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001115 if (!classdecl)
1116 return true;
1117
Douglas Gregor40808ce2009-03-09 23:48:35 +00001118 AdjustDeclIfTemplate(classdecl);
John McCalld226f652010-08-21 09:40:31 +00001119 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregor5fe8c042010-02-27 00:25:28 +00001120 if (!Class)
1121 return true;
1122
Nick Lewycky56062202010-07-26 16:56:01 +00001123 TypeSourceInfo *TInfo = 0;
1124 GetTypeFromParser(basetype, &TInfo);
Douglas Gregord0937222010-12-13 22:49:22 +00001125
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001126 if (EllipsisLoc.isInvalid() &&
1127 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregord0937222010-12-13 22:49:22 +00001128 UPPC_BaseType))
1129 return true;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001130
Douglas Gregor2943aed2009-03-03 04:44:36 +00001131 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001132 Virtual, Access, TInfo,
1133 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001134 return BaseSpec;
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Douglas Gregor2943aed2009-03-03 04:44:36 +00001136 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001137}
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001138
Douglas Gregor2943aed2009-03-03 04:44:36 +00001139/// \brief Performs the actual work of attaching the given base class
1140/// specifiers to a C++ class.
1141bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1142 unsigned NumBases) {
1143 if (NumBases == 0)
1144 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001145
1146 // Used to keep track of which base types we have already seen, so
1147 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +00001148 // that the key is always the unqualified canonical type of the base
1149 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001150 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1151
1152 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +00001153 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +00001154 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +00001155 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001156 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +00001157 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregora4923eb2009-11-16 21:35:15 +00001158 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001159 if (KnownBaseTypes[NewBaseType]) {
1160 // C++ [class.mi]p3:
1161 // A class shall not be specified as a direct base class of a
1162 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001163 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001164 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +00001165 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +00001166 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +00001167
1168 // Delete the duplicate base class specifier; we're going to
1169 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001170 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001171
1172 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001173 } else {
1174 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001175 KnownBaseTypes[NewBaseType] = Bases[idx];
1176 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian91589022011-10-24 17:30:45 +00001177 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian13c7fcc2011-10-21 22:27:12 +00001178 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1179 if (RD->hasAttr<WeakAttr>())
1180 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001181 }
1182 }
1183
1184 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2d5b7032010-02-11 01:30:34 +00001185 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +00001186
1187 // Delete the remaining (good) base class specifiers, since their
1188 // data has been copied into the CXXRecordDecl.
1189 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +00001190 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001191
1192 return Invalid;
1193}
1194
1195/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1196/// class, after checking whether there are any duplicate base
1197/// classes.
Richard Trieu90ab75b2011-09-09 03:18:59 +00001198void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001199 unsigned NumBases) {
1200 if (!ClassDecl || !Bases || !NumBases)
1201 return;
1202
1203 AdjustDeclIfTemplate(ClassDecl);
John McCalld226f652010-08-21 09:40:31 +00001204 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001205 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +00001206}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001207
John McCall3cb0ebd2010-03-10 03:28:59 +00001208static CXXRecordDecl *GetClassForType(QualType T) {
1209 if (const RecordType *RT = T->getAs<RecordType>())
1210 return cast<CXXRecordDecl>(RT->getDecl());
1211 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1212 return ICT->getDecl();
1213 else
1214 return 0;
1215}
1216
Douglas Gregora8f32e02009-10-06 17:59:45 +00001217/// \brief Determine whether the type \p Derived is a C++ class that is
1218/// derived from the type \p Base.
1219bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1220 if (!getLangOptions().CPlusPlus)
1221 return false;
John McCall3cb0ebd2010-03-10 03:28:59 +00001222
1223 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1224 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001225 return false;
1226
John McCall3cb0ebd2010-03-10 03:28:59 +00001227 CXXRecordDecl *BaseRD = GetClassForType(Base);
1228 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001229 return false;
1230
John McCall86ff3082010-02-04 22:26:26 +00001231 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1232 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001233}
1234
1235/// \brief Determine whether the type \p Derived is a C++ class that is
1236/// derived from the type \p Base.
1237bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1238 if (!getLangOptions().CPlusPlus)
1239 return false;
1240
John McCall3cb0ebd2010-03-10 03:28:59 +00001241 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1242 if (!DerivedRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001243 return false;
1244
John McCall3cb0ebd2010-03-10 03:28:59 +00001245 CXXRecordDecl *BaseRD = GetClassForType(Base);
1246 if (!BaseRD)
Douglas Gregora8f32e02009-10-06 17:59:45 +00001247 return false;
1248
Douglas Gregora8f32e02009-10-06 17:59:45 +00001249 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1250}
1251
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001252void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallf871d0c2010-08-07 06:22:56 +00001253 CXXCastPath &BasePathArray) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001254 assert(BasePathArray.empty() && "Base path array must be empty!");
1255 assert(Paths.isRecordingPaths() && "Must record paths!");
1256
1257 const CXXBasePath &Path = Paths.front();
1258
1259 // We first go backward and check if we have a virtual base.
1260 // FIXME: It would be better if CXXBasePath had the base specifier for
1261 // the nearest virtual base.
1262 unsigned Start = 0;
1263 for (unsigned I = Path.size(); I != 0; --I) {
1264 if (Path[I - 1].Base->isVirtual()) {
1265 Start = I - 1;
1266 break;
1267 }
1268 }
1269
1270 // Now add all bases.
1271 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallf871d0c2010-08-07 06:22:56 +00001272 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001273}
1274
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001275/// \brief Determine whether the given base path includes a virtual
1276/// base class.
John McCallf871d0c2010-08-07 06:22:56 +00001277bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1278 for (CXXCastPath::const_iterator B = BasePath.begin(),
1279 BEnd = BasePath.end();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001280 B != BEnd; ++B)
1281 if ((*B)->isVirtual())
1282 return true;
1283
1284 return false;
1285}
1286
Douglas Gregora8f32e02009-10-06 17:59:45 +00001287/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1288/// conversion (where Derived and Base are class types) is
1289/// well-formed, meaning that the conversion is unambiguous (and
1290/// that all of the base classes are accessible). Returns true
1291/// and emits a diagnostic if the code is ill-formed, returns false
1292/// otherwise. Loc is the location where this routine should point to
1293/// if there is an error, and Range is the source range to highlight
1294/// if there is an error.
1295bool
1296Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall58e6f342010-03-16 05:22:47 +00001297 unsigned InaccessibleBaseID,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001298 unsigned AmbigiousBaseConvID,
1299 SourceLocation Loc, SourceRange Range,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001300 DeclarationName Name,
John McCallf871d0c2010-08-07 06:22:56 +00001301 CXXCastPath *BasePath) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001302 // First, determine whether the path from Derived to Base is
1303 // ambiguous. This is slightly more expensive than checking whether
1304 // the Derived to Base conversion exists, because here we need to
1305 // explore multiple paths to determine if there is an ambiguity.
1306 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1307 /*DetectVirtual=*/false);
1308 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1309 assert(DerivationOkay &&
1310 "Can only be used with a derived-to-base conversion");
1311 (void)DerivationOkay;
1312
1313 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001314 if (InaccessibleBaseID) {
1315 // Check that the base class can be accessed.
1316 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1317 InaccessibleBaseID)) {
1318 case AR_inaccessible:
1319 return true;
1320 case AR_accessible:
1321 case AR_dependent:
1322 case AR_delayed:
1323 break;
Anders Carlssone25a96c2010-04-24 17:11:09 +00001324 }
John McCall6b2accb2010-02-10 09:31:12 +00001325 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001326
1327 // Build a base path if necessary.
1328 if (BasePath)
1329 BuildBasePathArray(Paths, *BasePath);
1330 return false;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001331 }
1332
1333 // We know that the derived-to-base conversion is ambiguous, and
1334 // we're going to produce a diagnostic. Perform the derived-to-base
1335 // search just one more time to compute all of the possible paths so
1336 // that we can print them out. This is more expensive than any of
1337 // the previous derived-to-base checks we've done, but at this point
1338 // performance isn't as much of an issue.
1339 Paths.clear();
1340 Paths.setRecordingPaths(true);
1341 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1342 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1343 (void)StillOkay;
1344
1345 // Build up a textual representation of the ambiguous paths, e.g.,
1346 // D -> B -> A, that will be used to illustrate the ambiguous
1347 // conversions in the diagnostic. We only print one of the paths
1348 // to each base class subobject.
1349 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1350
1351 Diag(Loc, AmbigiousBaseConvID)
1352 << Derived << Base << PathDisplayStr << Range << Name;
1353 return true;
1354}
1355
1356bool
1357Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001358 SourceLocation Loc, SourceRange Range,
John McCallf871d0c2010-08-07 06:22:56 +00001359 CXXCastPath *BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001360 bool IgnoreAccess) {
Douglas Gregora8f32e02009-10-06 17:59:45 +00001361 return CheckDerivedToBaseConversion(Derived, Base,
John McCall58e6f342010-03-16 05:22:47 +00001362 IgnoreAccess ? 0
1363 : diag::err_upcast_to_inaccessible_base,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001364 diag::err_ambiguous_derived_to_base_conv,
Anders Carlssone25a96c2010-04-24 17:11:09 +00001365 Loc, Range, DeclarationName(),
1366 BasePath);
Douglas Gregora8f32e02009-10-06 17:59:45 +00001367}
1368
1369
1370/// @brief Builds a string representing ambiguous paths from a
1371/// specific derived class to different subobjects of the same base
1372/// class.
1373///
1374/// This function builds a string that can be used in error messages
1375/// to show the different paths that one can take through the
1376/// inheritance hierarchy to go from the derived class to different
1377/// subobjects of a base class. The result looks something like this:
1378/// @code
1379/// struct D -> struct B -> struct A
1380/// struct D -> struct C -> struct A
1381/// @endcode
1382std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1383 std::string PathDisplayStr;
1384 std::set<unsigned> DisplayedPaths;
1385 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1386 Path != Paths.end(); ++Path) {
1387 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1388 // We haven't displayed a path to this particular base
1389 // class subobject yet.
1390 PathDisplayStr += "\n ";
1391 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1392 for (CXXBasePath::const_iterator Element = Path->begin();
1393 Element != Path->end(); ++Element)
1394 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1395 }
1396 }
1397
1398 return PathDisplayStr;
1399}
1400
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001401//===----------------------------------------------------------------------===//
1402// C++ class member Handling
1403//===----------------------------------------------------------------------===//
1404
Abramo Bagnara6206d532010-06-05 05:09:32 +00001405/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001406bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1407 SourceLocation ASLoc,
1408 SourceLocation ColonLoc,
1409 AttributeList *Attrs) {
Abramo Bagnara6206d532010-06-05 05:09:32 +00001410 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCalld226f652010-08-21 09:40:31 +00001411 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnara6206d532010-06-05 05:09:32 +00001412 ASLoc, ColonLoc);
1413 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggen5f1c8222011-10-13 09:41:32 +00001414 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnara6206d532010-06-05 05:09:32 +00001415}
1416
Anders Carlsson9e682d92011-01-20 05:57:14 +00001417/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001418void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001419 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001420 if (!MD || !MD->isVirtual())
1421 return;
1422
Anders Carlsson3ffe1832011-01-20 06:33:26 +00001423 if (MD->isDependentContext())
1424 return;
1425
Anders Carlsson9e682d92011-01-20 05:57:14 +00001426 // C++0x [class.virtual]p3:
1427 // If a virtual function is marked with the virt-specifier override and does
1428 // not override a member function of a base class,
1429 // the program is ill-formed.
1430 bool HasOverriddenMethods =
1431 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001432 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001433 Diag(MD->getLocation(),
Anders Carlsson9e682d92011-01-20 05:57:14 +00001434 diag::err_function_marked_override_not_overriding)
1435 << MD->getDeclName();
1436 return;
1437 }
1438}
1439
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001440/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1441/// function overrides a virtual member function marked 'final', according to
1442/// C++0x [class.virtual]p3.
1443bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1444 const CXXMethodDecl *Old) {
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001445 if (!Old->hasAttr<FinalAttr>())
Anders Carlssonf89e0422011-01-23 21:07:30 +00001446 return false;
1447
1448 Diag(New->getLocation(), diag::err_final_function_overridden)
1449 << New->getDeclName();
1450 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1451 return true;
Anders Carlsson2e1c7302011-01-20 16:25:36 +00001452}
1453
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001454/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1455/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith7a614d82011-06-11 17:19:42 +00001456/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1457/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1458/// present but parsing it has been deferred.
John McCalld226f652010-08-21 09:40:31 +00001459Decl *
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001460Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +00001461 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001462 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001463 bool HasDeferredInit) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001464 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +00001465 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1466 DeclarationName Name = NameInfo.getName();
1467 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor90ba6d52010-11-09 03:31:16 +00001468
1469 // For anonymous bitfields, the location should point to the type.
1470 if (Loc.isInvalid())
1471 Loc = D.getSourceRange().getBegin();
1472
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001473 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001474
John McCall4bde1e12010-06-04 08:34:12 +00001475 assert(isa<CXXRecordDecl>(CurContext));
John McCall67d1a672009-08-06 02:15:43 +00001476 assert(!DS.isFriendSpecified());
1477
Richard Smith1ab0d902011-06-25 02:28:38 +00001478 bool isFunc = D.isDeclarationOfFunction();
John McCall4bde1e12010-06-04 08:34:12 +00001479
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001480 // C++ 9.2p6: A member shall not be declared to have automatic storage
1481 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001482 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1483 // data members and cannot be applied to names declared const or static,
1484 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001485 switch (DS.getStorageClassSpec()) {
1486 case DeclSpec::SCS_unspecified:
1487 case DeclSpec::SCS_typedef:
1488 case DeclSpec::SCS_static:
1489 // FALL THROUGH.
1490 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001491 case DeclSpec::SCS_mutable:
1492 if (isFunc) {
1493 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001494 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +00001495 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001496 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Sebastian Redla11f42f2008-11-17 23:24:37 +00001498 // FIXME: It would be nicer if the keyword was ignored only for this
1499 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +00001500 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redl669d5d72008-11-14 23:42:31 +00001501 }
1502 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001503 default:
1504 if (DS.getStorageClassSpecLoc().isValid())
1505 Diag(DS.getStorageClassSpecLoc(),
1506 diag::err_storageclass_invalid_for_member);
1507 else
1508 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1509 D.getMutableDeclSpec().ClearStorageClassSpecs();
1510 }
1511
Sebastian Redl669d5d72008-11-14 23:42:31 +00001512 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1513 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +00001514 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001515
1516 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +00001517 if (isInstField) {
Douglas Gregor922fff22010-10-13 22:19:53 +00001518 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorb5a01872011-10-09 18:55:59 +00001519
1520 // Data members must have identifiers for names.
1521 if (Name.getNameKind() != DeclarationName::Identifier) {
1522 Diag(Loc, diag::err_bad_variable_name)
1523 << Name;
1524 return 0;
1525 }
Douglas Gregor922fff22010-10-13 22:19:53 +00001526
Douglas Gregorf2503652011-09-21 14:40:46 +00001527 IdentifierInfo *II = Name.getAsIdentifierInfo();
1528
1529 // Member field could not be with "template" keyword.
1530 // So TemplateParameterLists should be empty in this case.
1531 if (TemplateParameterLists.size()) {
1532 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1533 if (TemplateParams->size()) {
1534 // There is no such thing as a member field template.
1535 Diag(D.getIdentifierLoc(), diag::err_template_member)
1536 << II
1537 << SourceRange(TemplateParams->getTemplateLoc(),
1538 TemplateParams->getRAngleLoc());
1539 } else {
1540 // There is an extraneous 'template<>' for this member.
1541 Diag(TemplateParams->getTemplateLoc(),
1542 diag::err_template_member_noparams)
1543 << II
1544 << SourceRange(TemplateParams->getTemplateLoc(),
1545 TemplateParams->getRAngleLoc());
1546 }
1547 return 0;
1548 }
1549
Douglas Gregor922fff22010-10-13 22:19:53 +00001550 if (SS.isSet() && !SS.isInvalid()) {
1551 // The user provided a superfluous scope specifier inside a class
1552 // definition:
1553 //
1554 // class X {
1555 // int X::member;
1556 // };
1557 DeclContext *DC = 0;
1558 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1559 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001560 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor922fff22010-10-13 22:19:53 +00001561 else
1562 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1563 << Name << SS.getRange();
Douglas Gregor5d8419c2011-11-01 22:13:30 +00001564
Douglas Gregor922fff22010-10-13 22:19:53 +00001565 SS.clear();
1566 }
Douglas Gregorf2503652011-09-21 14:40:46 +00001567
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001568 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +00001569 HasDeferredInit, AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +00001570 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +00001571 } else {
Richard Smith7a614d82011-06-11 17:19:42 +00001572 assert(!HasDeferredInit);
1573
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001574 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner6f8ce142009-03-05 23:03:49 +00001575 if (!Member) {
John McCalld226f652010-08-21 09:40:31 +00001576 return 0;
Chris Lattner6f8ce142009-03-05 23:03:49 +00001577 }
Chris Lattner8b963ef2009-03-05 23:01:03 +00001578
1579 // Non-instance-fields can't have a bitfield.
1580 if (BitWidth) {
1581 if (Member->isInvalidDecl()) {
1582 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001583 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +00001584 // C++ 9.6p3: A bit-field shall not be a static member.
1585 // "static member 'A' cannot be a bit-field"
1586 Diag(Loc, diag::err_static_not_bitfield)
1587 << Name << BitWidth->getSourceRange();
1588 } else if (isa<TypedefDecl>(Member)) {
1589 // "typedef member 'x' cannot be a bit-field"
1590 Diag(Loc, diag::err_typedef_not_bitfield)
1591 << Name << BitWidth->getSourceRange();
1592 } else {
1593 // A function typedef ("typedef int f(); f a;").
1594 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1595 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump1eb44332009-09-09 15:08:12 +00001596 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor3cf538d2009-03-11 18:59:21 +00001597 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +00001598 }
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Chris Lattner8b963ef2009-03-05 23:01:03 +00001600 BitWidth = 0;
1601 Member->setInvalidDecl();
1602 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +00001603
1604 Member->setAccess(AS);
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Douglas Gregor37b372b2009-08-20 22:52:58 +00001606 // If we have declared a member function template, set the access of the
1607 // templated declaration as well.
1608 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1609 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +00001610 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001611
Anders Carlssonaae5af22011-01-20 04:34:22 +00001612 if (VS.isOverrideSpecified()) {
1613 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1614 if (!MD || !MD->isVirtual()) {
1615 Diag(Member->getLocStart(),
1616 diag::override_keyword_only_allowed_on_virtual_member_functions)
1617 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001618 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001619 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001620 }
1621 if (VS.isFinalSpecified()) {
1622 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1623 if (!MD || !MD->isVirtual()) {
1624 Diag(Member->getLocStart(),
1625 diag::override_keyword_only_allowed_on_virtual_member_functions)
1626 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlsson9e682d92011-01-20 05:57:14 +00001627 } else
Anders Carlssoncb88a1f2011-01-24 16:26:15 +00001628 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlssonaae5af22011-01-20 04:34:22 +00001629 }
Anders Carlsson9e682d92011-01-20 05:57:14 +00001630
Douglas Gregorf5251602011-03-08 17:10:18 +00001631 if (VS.getLastLocation().isValid()) {
1632 // Update the end location of a method that has a virt-specifiers.
1633 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1634 MD->setRangeEnd(VS.getLastLocation());
1635 }
1636
Anders Carlsson4ebf1602011-01-20 06:29:02 +00001637 CheckOverrideControl(Member);
Anders Carlsson9e682d92011-01-20 05:57:14 +00001638
Douglas Gregor10bd3682008-11-17 22:58:34 +00001639 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001640
John McCallb25b2952011-02-15 07:12:36 +00001641 if (isInstField)
Douglas Gregor44b43212008-12-11 16:49:14 +00001642 FieldCollector->Add(cast<FieldDecl>(Member));
John McCalld226f652010-08-21 09:40:31 +00001643 return Member;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001644}
1645
Richard Smith7a614d82011-06-11 17:19:42 +00001646/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001647/// in-class initializer for a non-static C++ class member, and after
1648/// instantiating an in-class initializer in a class template. Such actions
1649/// are deferred until the class is complete.
Richard Smith7a614d82011-06-11 17:19:42 +00001650void
1651Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1652 Expr *InitExpr) {
1653 FieldDecl *FD = cast<FieldDecl>(D);
1654
1655 if (!InitExpr) {
1656 FD->setInvalidDecl();
1657 FD->removeInClassInitializer();
1658 return;
1659 }
1660
Peter Collingbournefef21892011-10-23 18:59:44 +00001661 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1662 FD->setInvalidDecl();
1663 FD->removeInClassInitializer();
1664 return;
1665 }
1666
Richard Smith7a614d82011-06-11 17:19:42 +00001667 ExprResult Init = InitExpr;
1668 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1669 // FIXME: if there is no EqualLoc, this is list-initialization.
1670 Init = PerformCopyInitialization(
1671 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1672 if (Init.isInvalid()) {
1673 FD->setInvalidDecl();
1674 return;
1675 }
1676
1677 CheckImplicitConversions(Init.get(), EqualLoc);
1678 }
1679
1680 // C++0x [class.base.init]p7:
1681 // The initialization of each base and member constitutes a
1682 // full-expression.
1683 Init = MaybeCreateExprWithCleanups(Init);
1684 if (Init.isInvalid()) {
1685 FD->setInvalidDecl();
1686 return;
1687 }
1688
1689 InitExpr = Init.release();
1690
1691 FD->setInClassInitializer(InitExpr);
1692}
1693
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001694/// \brief Find the direct and/or virtual base specifiers that
1695/// correspond to the given base type, for use in base initialization
1696/// within a constructor.
1697static bool FindBaseInitializer(Sema &SemaRef,
1698 CXXRecordDecl *ClassDecl,
1699 QualType BaseType,
1700 const CXXBaseSpecifier *&DirectBaseSpec,
1701 const CXXBaseSpecifier *&VirtualBaseSpec) {
1702 // First, check for a direct base class.
1703 DirectBaseSpec = 0;
1704 for (CXXRecordDecl::base_class_const_iterator Base
1705 = ClassDecl->bases_begin();
1706 Base != ClassDecl->bases_end(); ++Base) {
1707 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1708 // We found a direct base of this type. That's what we're
1709 // initializing.
1710 DirectBaseSpec = &*Base;
1711 break;
1712 }
1713 }
1714
1715 // Check for a virtual base class.
1716 // FIXME: We might be able to short-circuit this if we know in advance that
1717 // there are no virtual bases.
1718 VirtualBaseSpec = 0;
1719 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1720 // We haven't found a base yet; search the class hierarchy for a
1721 // virtual base class.
1722 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1723 /*DetectVirtual=*/false);
1724 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1725 BaseType, Paths)) {
1726 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1727 Path != Paths.end(); ++Path) {
1728 if (Path->back().Base->isVirtual()) {
1729 VirtualBaseSpec = Path->back().Base;
1730 break;
1731 }
1732 }
1733 }
1734 }
1735
1736 return DirectBaseSpec || VirtualBaseSpec;
1737}
1738
Sebastian Redl6df65482011-09-24 17:48:25 +00001739/// \brief Handle a C++ member initializer using braced-init-list syntax.
1740MemInitResult
1741Sema::ActOnMemInitializer(Decl *ConstructorD,
1742 Scope *S,
1743 CXXScopeSpec &SS,
1744 IdentifierInfo *MemberOrBase,
1745 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001746 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001747 SourceLocation IdLoc,
1748 Expr *InitList,
1749 SourceLocation EllipsisLoc) {
1750 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001751 DS, IdLoc, MultiInitializer(InitList),
1752 EllipsisLoc);
Sebastian Redl6df65482011-09-24 17:48:25 +00001753}
1754
1755/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallf312b1e2010-08-26 23:41:50 +00001756MemInitResult
John McCalld226f652010-08-21 09:40:31 +00001757Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001758 Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001759 CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001760 IdentifierInfo *MemberOrBase,
John McCallb3d87482010-08-24 05:47:05 +00001761 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001762 const DeclSpec &DS,
Douglas Gregor7ad83902008-11-05 04:29:56 +00001763 SourceLocation IdLoc,
1764 SourceLocation LParenLoc,
Richard Trieuf81e5a92011-09-09 02:00:50 +00001765 Expr **Args, unsigned NumArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001766 SourceLocation RParenLoc,
1767 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00001768 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001769 DS, IdLoc, MultiInitializer(LParenLoc, Args,
1770 NumArgs, RParenLoc),
Sebastian Redl6df65482011-09-24 17:48:25 +00001771 EllipsisLoc);
1772}
1773
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001774namespace {
1775
Kaelyn Uhraindc98cd02012-01-11 21:17:51 +00001776// Callback to only accept typo corrections that can be a valid C++ member
1777// intializer: either a non-static field member or a base class.
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001778class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1779 public:
1780 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1781 : ClassDecl(ClassDecl) {}
1782
1783 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1784 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1785 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1786 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1787 else
1788 return isa<TypeDecl>(ND);
1789 }
1790 return false;
1791 }
1792
1793 private:
1794 CXXRecordDecl *ClassDecl;
1795};
1796
1797}
1798
Sebastian Redl6df65482011-09-24 17:48:25 +00001799/// \brief Handle a C++ member initializer.
1800MemInitResult
1801Sema::BuildMemInitializer(Decl *ConstructorD,
1802 Scope *S,
1803 CXXScopeSpec &SS,
1804 IdentifierInfo *MemberOrBase,
1805 ParsedType TemplateTypeTy,
David Blaikief2116622012-01-24 06:03:59 +00001806 const DeclSpec &DS,
Sebastian Redl6df65482011-09-24 17:48:25 +00001807 SourceLocation IdLoc,
1808 const MultiInitializer &Args,
1809 SourceLocation EllipsisLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001810 if (!ConstructorD)
1811 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001813 AdjustDeclIfTemplate(ConstructorD);
Mike Stump1eb44332009-09-09 15:08:12 +00001814
1815 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00001816 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001817 if (!Constructor) {
1818 // The user wrote a constructor initializer on a function that is
1819 // not a C++ constructor. Ignore the error for now, because we may
1820 // have more member initializers coming; we'll diagnose it just
1821 // once in ActOnMemInitializers.
1822 return true;
1823 }
1824
1825 CXXRecordDecl *ClassDecl = Constructor->getParent();
1826
1827 // C++ [class.base.init]p2:
1828 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky7663f392010-11-20 01:29:55 +00001829 // constructor's class and, if not found in that scope, are looked
1830 // up in the scope containing the constructor's definition.
1831 // [Note: if the constructor's class contains a member with the
1832 // same name as a direct or virtual base class of the class, a
1833 // mem-initializer-id naming the member or base class and composed
1834 // of a single identifier refers to the class member. A
Douglas Gregor7ad83902008-11-05 04:29:56 +00001835 // mem-initializer-id for the hidden base class may be specified
1836 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +00001837 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001838 // Look for a member, first.
Mike Stump1eb44332009-09-09 15:08:12 +00001839 DeclContext::lookup_result Result
Fariborz Jahanianbcfad542009-06-30 23:26:25 +00001840 = ClassDecl->lookup(MemberOrBase);
Francois Pichet87c2e122010-11-21 06:08:52 +00001841 if (Result.first != Result.second) {
Peter Collingbournedc69be22011-10-23 18:59:37 +00001842 ValueDecl *Member;
1843 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1844 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001845 if (EllipsisLoc.isValid())
1846 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redl6df65482011-09-24 17:48:25 +00001847 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1848
1849 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001850 }
Francois Pichet00eb3f92010-12-04 09:14:42 +00001851 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001852 }
Douglas Gregor7ad83902008-11-05 04:29:56 +00001853 // It didn't name a member, so see if it names a class.
Douglas Gregor802ab452009-12-02 22:36:29 +00001854 QualType BaseType;
John McCalla93c9342009-12-07 02:54:59 +00001855 TypeSourceInfo *TInfo = 0;
John McCall2b194412009-12-21 10:41:20 +00001856
1857 if (TemplateTypeTy) {
John McCalla93c9342009-12-07 02:54:59 +00001858 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikief2116622012-01-24 06:03:59 +00001859 } else if (DS.getTypeSpecType() == TST_decltype) {
1860 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCall2b194412009-12-21 10:41:20 +00001861 } else {
1862 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1863 LookupParsedName(R, S, &SS);
1864
1865 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1866 if (!TyD) {
1867 if (R.isAmbiguous()) return true;
1868
John McCallfd225442010-04-09 19:01:14 +00001869 // We don't want access-control diagnostics here.
1870 R.suppressDiagnostics();
1871
Douglas Gregor7a886e12010-01-19 06:46:48 +00001872 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1873 bool NotUnknownSpecialization = false;
1874 DeclContext *DC = computeDeclContext(SS, false);
1875 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1876 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1877
1878 if (!NotUnknownSpecialization) {
1879 // When the scope specifier can refer to a member of an unknown
1880 // specialization, we take it as a type name.
Douglas Gregore29425b2011-02-28 22:42:13 +00001881 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1882 SS.getWithLocInContext(Context),
1883 *MemberOrBase, IdLoc);
Douglas Gregora50ce322010-03-07 23:26:22 +00001884 if (BaseType.isNull())
1885 return true;
1886
Douglas Gregor7a886e12010-01-19 06:46:48 +00001887 R.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +00001888 R.setLookupName(MemberOrBase);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001889 }
1890 }
1891
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001892 // If no results were found, try to correct typos.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001893 TypoCorrection Corr;
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001894 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001895 if (R.empty() && BaseType.isNull() &&
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001896 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001897 Validator, ClassDecl))) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001898 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1899 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1900 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001901 // We have found a non-static data member with a similar
1902 // name to what was typed; complain and initialize that
1903 // member.
1904 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1905 << MemberOrBase << true << CorrectedQuotedStr
1906 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1907 Diag(Member->getLocation(), diag::note_previous_decl)
1908 << CorrectedQuotedStr;
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001909
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00001910 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001911 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001912 const CXXBaseSpecifier *DirectBaseSpec;
1913 const CXXBaseSpecifier *VirtualBaseSpec;
1914 if (FindBaseInitializer(*this, ClassDecl,
1915 Context.getTypeDeclType(Type),
1916 DirectBaseSpec, VirtualBaseSpec)) {
1917 // We have found a direct or virtual base class with a
1918 // similar name to what was typed; complain and initialize
1919 // that base class.
1920 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001921 << MemberOrBase << false << CorrectedQuotedStr
1922 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor0d535c82010-01-07 00:26:25 +00001923
1924 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1925 : VirtualBaseSpec;
1926 Diag(BaseSpec->getSourceRange().getBegin(),
1927 diag::note_base_class_specified_here)
1928 << BaseSpec->getType()
1929 << BaseSpec->getSourceRange();
1930
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001931 TyD = Type;
1932 }
1933 }
1934 }
1935
Douglas Gregor7a886e12010-01-19 06:46:48 +00001936 if (!TyD && BaseType.isNull()) {
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001937 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redl6df65482011-09-24 17:48:25 +00001938 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregorfe0241e2009-12-31 09:10:24 +00001939 return true;
1940 }
John McCall2b194412009-12-21 10:41:20 +00001941 }
1942
Douglas Gregor7a886e12010-01-19 06:46:48 +00001943 if (BaseType.isNull()) {
1944 BaseType = Context.getTypeDeclType(TyD);
1945 if (SS.isSet()) {
1946 NestedNameSpecifier *Qualifier =
1947 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall2b194412009-12-21 10:41:20 +00001948
Douglas Gregor7a886e12010-01-19 06:46:48 +00001949 // FIXME: preserve source range information
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001950 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregor7a886e12010-01-19 06:46:48 +00001951 }
John McCall2b194412009-12-21 10:41:20 +00001952 }
1953 }
Mike Stump1eb44332009-09-09 15:08:12 +00001954
John McCalla93c9342009-12-07 02:54:59 +00001955 if (!TInfo)
1956 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00001957
Sebastian Redl6df65482011-09-24 17:48:25 +00001958 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman59c04372009-07-29 19:44:27 +00001959}
1960
Chandler Carruth81c64772011-09-03 01:14:15 +00001961/// Checks a member initializer expression for cases where reference (or
1962/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth81c64772011-09-03 01:14:15 +00001963static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1964 Expr *Init,
1965 SourceLocation IdLoc) {
1966 QualType MemberTy = Member->getType();
1967
1968 // We only handle pointers and references currently.
1969 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1970 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1971 return;
1972
1973 const bool IsPointer = MemberTy->isPointerType();
1974 if (IsPointer) {
1975 if (const UnaryOperator *Op
1976 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1977 // The only case we're worried about with pointers requires taking the
1978 // address.
1979 if (Op->getOpcode() != UO_AddrOf)
1980 return;
1981
1982 Init = Op->getSubExpr();
1983 } else {
1984 // We only handle address-of expression initializers for pointers.
1985 return;
1986 }
1987 }
1988
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001989 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1990 // Taking the address of a temporary will be diagnosed as a hard error.
1991 if (IsPointer)
1992 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00001993
Chandler Carruthbf3380a2011-09-03 02:21:57 +00001994 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1995 << Member << Init->getSourceRange();
1996 } else if (const DeclRefExpr *DRE
1997 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1998 // We only warn when referring to a non-reference parameter declaration.
1999 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2000 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth81c64772011-09-03 01:14:15 +00002001 return;
2002
2003 S.Diag(Init->getExprLoc(),
2004 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2005 : diag::warn_bind_ref_member_to_parameter)
2006 << Member << Parameter << Init->getSourceRange();
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002007 } else {
2008 // Other initializers are fine.
2009 return;
Chandler Carruth81c64772011-09-03 01:14:15 +00002010 }
Chandler Carruthbf3380a2011-09-03 02:21:57 +00002011
2012 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2013 << (unsigned)IsPointer;
Chandler Carruth81c64772011-09-03 01:14:15 +00002014}
2015
John McCallb4190042009-11-04 23:02:40 +00002016/// Checks an initializer expression for use of uninitialized fields, such as
2017/// containing the field that is being initialized. Returns true if there is an
2018/// uninitialized field was used an updates the SourceLocation parameter; false
2019/// otherwise.
Nick Lewycky43ad1822010-06-15 07:32:55 +00002020static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichet00eb3f92010-12-04 09:14:42 +00002021 const ValueDecl *LhsField,
Nick Lewycky43ad1822010-06-15 07:32:55 +00002022 SourceLocation *L) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002023 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2024
Nick Lewycky43ad1822010-06-15 07:32:55 +00002025 if (isa<CallExpr>(S)) {
2026 // Do not descend into function calls or constructors, as the use
2027 // of an uninitialized field may be valid. One would have to inspect
2028 // the contents of the function/ctor to determine if it is safe or not.
2029 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2030 // may be safe, depending on what the function/ctor does.
2031 return false;
2032 }
2033 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2034 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002035
2036 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2037 // The member expression points to a static data member.
2038 assert(VD->isStaticDataMember() &&
2039 "Member points to non-static data member!");
Nick Lewyckyedd59112010-10-06 18:37:39 +00002040 (void)VD;
Anders Carlsson175ffbf2010-10-06 02:43:25 +00002041 return false;
2042 }
2043
2044 if (isa<EnumConstantDecl>(RhsField)) {
2045 // The member expression points to an enum.
2046 return false;
2047 }
2048
John McCallb4190042009-11-04 23:02:40 +00002049 if (RhsField == LhsField) {
2050 // Initializing a field with itself. Throw a warning.
2051 // But wait; there are exceptions!
2052 // Exception #1: The field may not belong to this record.
2053 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewycky43ad1822010-06-15 07:32:55 +00002054 const Expr *base = ME->getBase();
John McCallb4190042009-11-04 23:02:40 +00002055 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2056 // Even though the field matches, it does not belong to this record.
2057 return false;
2058 }
2059 // None of the exceptions triggered; return true to indicate an
2060 // uninitialized field was used.
2061 *L = ME->getMemberLoc();
2062 return true;
2063 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002064 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidisff8819b2010-09-21 10:47:20 +00002065 // sizeof/alignof doesn't reference contents, do not warn.
2066 return false;
2067 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2068 // address-of doesn't reference contents (the pointer may be dereferenced
2069 // in the same expression but it would be rare; and weird).
2070 if (UOE->getOpcode() == UO_AddrOf)
2071 return false;
John McCallb4190042009-11-04 23:02:40 +00002072 }
John McCall7502c1d2011-02-13 04:07:26 +00002073 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewycky43ad1822010-06-15 07:32:55 +00002074 if (!*it) {
2075 // An expression such as 'member(arg ?: "")' may trigger this.
John McCallb4190042009-11-04 23:02:40 +00002076 continue;
2077 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002078 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2079 return true;
John McCallb4190042009-11-04 23:02:40 +00002080 }
Nick Lewycky43ad1822010-06-15 07:32:55 +00002081 return false;
John McCallb4190042009-11-04 23:02:40 +00002082}
2083
John McCallf312b1e2010-08-26 23:41:50 +00002084MemInitResult
Sebastian Redl6df65482011-09-24 17:48:25 +00002085Sema::BuildMemberInitializer(ValueDecl *Member,
2086 const MultiInitializer &Args,
2087 SourceLocation IdLoc) {
Chandler Carruth894aed92010-12-06 09:23:57 +00002088 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2089 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2090 assert((DirectMember || IndirectMember) &&
Francois Pichet00eb3f92010-12-04 09:14:42 +00002091 "Member must be a FieldDecl or IndirectFieldDecl");
2092
Peter Collingbournefef21892011-10-23 18:59:44 +00002093 if (Args.DiagnoseUnexpandedParameterPack(*this))
2094 return true;
2095
Douglas Gregor464b2f02010-11-05 22:21:31 +00002096 if (Member->isInvalidDecl())
2097 return true;
Chandler Carruth894aed92010-12-06 09:23:57 +00002098
John McCallb4190042009-11-04 23:02:40 +00002099 // Diagnose value-uses of fields to initialize themselves, e.g.
2100 // foo(foo)
2101 // where foo is not also a parameter to the constructor.
John McCall6aee6212009-11-04 23:13:52 +00002102 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redl6df65482011-09-24 17:48:25 +00002103 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2104 I != E; ++I) {
John McCallb4190042009-11-04 23:02:40 +00002105 SourceLocation L;
Sebastian Redl6df65482011-09-24 17:48:25 +00002106 Expr *Arg = *I;
2107 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2108 Arg = DIE->getInit();
2109 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCallb4190042009-11-04 23:02:40 +00002110 // FIXME: Return true in the case when other fields are used before being
2111 // uninitialized. For example, let this field be the i'th field. When
2112 // initializing the i'th field, throw a warning if any of the >= i'th
2113 // fields are used, as they are not yet initialized.
2114 // Right now we are only handling the case where the i'th field uses
2115 // itself in its initializer.
2116 Diag(L, diag::warn_field_is_uninit);
2117 }
2118 }
2119
Sebastian Redl6df65482011-09-24 17:48:25 +00002120 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002121
Chandler Carruth894aed92010-12-06 09:23:57 +00002122 Expr *Init;
Eli Friedman0f2b97d2010-07-24 21:19:15 +00002123 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002124 // Can't check initialization for a member of dependent type or when
2125 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002126 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002127
John McCallf85e1932011-06-15 23:02:42 +00002128 DiscardCleanupsInEvaluationContext();
Chandler Carruth894aed92010-12-06 09:23:57 +00002129 } else {
2130 // Initialize the member.
2131 InitializedEntity MemberEntity =
2132 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2133 : InitializedEntity::InitializeMember(IndirectMember, 0);
2134 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002135 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2136 Args.getEndLoc());
John McCallb4eb64d2010-10-08 02:01:28 +00002137
Sebastian Redl6df65482011-09-24 17:48:25 +00002138 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruth894aed92010-12-06 09:23:57 +00002139 if (MemberInit.isInvalid())
2140 return true;
2141
Sebastian Redl6df65482011-09-24 17:48:25 +00002142 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002143
2144 // C++0x [class.base.init]p7:
2145 // The initialization of each base and member constitutes a
2146 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002147 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruth894aed92010-12-06 09:23:57 +00002148 if (MemberInit.isInvalid())
2149 return true;
2150
2151 // If we are in a dependent context, template instantiation will
2152 // perform this type-checking again. Just save the arguments that we
2153 // received in a ParenListExpr.
2154 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2155 // of the information that we have about the member
2156 // initializer. However, deconstructing the ASTs is a dicey process,
2157 // and this approach is far more likely to get the corner cases right.
Chandler Carruth81c64772011-09-03 01:14:15 +00002158 if (CurContext->isDependentContext()) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002159 Init = Args.CreateInitExpr(Context,
2160 Member->getType().getNonReferenceType());
Chandler Carruth81c64772011-09-03 01:14:15 +00002161 } else {
Chandler Carruth894aed92010-12-06 09:23:57 +00002162 Init = MemberInit.get();
Chandler Carruth81c64772011-09-03 01:14:15 +00002163 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2164 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002165 }
2166
Chandler Carruth894aed92010-12-06 09:23:57 +00002167 if (DirectMember) {
Sean Huntcbb67482011-01-08 20:30:50 +00002168 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002169 IdLoc, Args.getStartLoc(),
2170 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002171 } else {
Sean Huntcbb67482011-01-08 20:30:50 +00002172 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redl6df65482011-09-24 17:48:25 +00002173 IdLoc, Args.getStartLoc(),
2174 Init, Args.getEndLoc());
Chandler Carruth894aed92010-12-06 09:23:57 +00002175 }
Eli Friedman59c04372009-07-29 19:44:27 +00002176}
2177
John McCallf312b1e2010-08-26 23:41:50 +00002178MemInitResult
Sean Hunt97fcc492011-01-08 19:20:43 +00002179Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002180 const MultiInitializer &Args,
Sean Hunt41717662011-02-26 19:13:13 +00002181 CXXRecordDecl *ClassDecl) {
Douglas Gregor76852c22011-11-01 01:16:03 +00002182 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sean Hunt97fcc492011-01-08 19:20:43 +00002183 if (!LangOpts.CPlusPlus0x)
Douglas Gregor76852c22011-11-01 01:16:03 +00002184 return Diag(NameLoc, diag::err_delegating_ctor)
Sean Hunt97fcc492011-01-08 19:20:43 +00002185 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor76852c22011-11-01 01:16:03 +00002186 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redlf9c32eb2011-03-12 13:53:51 +00002187
Sean Hunt41717662011-02-26 19:13:13 +00002188 // Initialize the object.
2189 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2190 QualType(ClassDecl->getTypeForDecl(), 0));
2191 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002192 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2193 Args.getEndLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002194
Sebastian Redl6df65482011-09-24 17:48:25 +00002195 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Sean Hunt41717662011-02-26 19:13:13 +00002196 if (DelegationInit.isInvalid())
2197 return true;
2198
Matt Beaumont-Gay2eb0ce32011-11-01 18:10:22 +00002199 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2200 "Delegating constructor with no target?");
Sean Hunt41717662011-02-26 19:13:13 +00002201
Sebastian Redl6df65482011-09-24 17:48:25 +00002202 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Sean Hunt41717662011-02-26 19:13:13 +00002203
2204 // C++0x [class.base.init]p7:
2205 // The initialization of each base and member constitutes a
2206 // full-expression.
2207 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2208 if (DelegationInit.isInvalid())
2209 return true;
2210
Douglas Gregor76852c22011-11-01 01:16:03 +00002211 return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
Sean Hunt41717662011-02-26 19:13:13 +00002212 DelegationInit.takeAs<Expr>(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002213 Args.getEndLoc());
Sean Hunt97fcc492011-01-08 19:20:43 +00002214}
2215
2216MemInitResult
John McCalla93c9342009-12-07 02:54:59 +00002217Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002218 const MultiInitializer &Args,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002219 CXXRecordDecl *ClassDecl,
2220 SourceLocation EllipsisLoc) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002221 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman59c04372009-07-29 19:44:27 +00002222
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002223 SourceLocation BaseLoc
2224 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redl6df65482011-09-24 17:48:25 +00002225
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002226 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2227 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2228 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2229
2230 // C++ [class.base.init]p2:
2231 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky7663f392010-11-20 01:29:55 +00002232 // member of the constructor's class or a direct or virtual base
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002233 // of that class, the mem-initializer is ill-formed. A
2234 // mem-initializer-list can initialize a base class using any
2235 // name that denotes that base class type.
2236 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2237
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002238 if (EllipsisLoc.isValid()) {
2239 // This is a pack expansion.
2240 if (!BaseType->containsUnexpandedParameterPack()) {
2241 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redl6df65482011-09-24 17:48:25 +00002242 << SourceRange(BaseLoc, Args.getEndLoc());
2243
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002244 EllipsisLoc = SourceLocation();
2245 }
2246 } else {
2247 // Check for any unexpanded parameter packs.
2248 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2249 return true;
Sebastian Redl6df65482011-09-24 17:48:25 +00002250
2251 if (Args.DiagnoseUnexpandedParameterPack(*this))
2252 return true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002253 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002254
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002255 // Check for direct and virtual base classes.
2256 const CXXBaseSpecifier *DirectBaseSpec = 0;
2257 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2258 if (!Dependent) {
Sean Hunt97fcc492011-01-08 19:20:43 +00002259 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2260 BaseType))
Douglas Gregor76852c22011-11-01 01:16:03 +00002261 return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
Sean Hunt97fcc492011-01-08 19:20:43 +00002262
Douglas Gregor3956b1a2010-06-16 16:03:14 +00002263 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2264 VirtualBaseSpec);
2265
2266 // C++ [base.class.init]p2:
2267 // Unless the mem-initializer-id names a nonstatic data member of the
2268 // constructor's class or a direct or virtual base of that class, the
2269 // mem-initializer is ill-formed.
2270 if (!DirectBaseSpec && !VirtualBaseSpec) {
2271 // If the class has any dependent bases, then it's possible that
2272 // one of those types will resolve to the same type as
2273 // BaseType. Therefore, just treat this as a dependent base
2274 // class initialization. FIXME: Should we try to check the
2275 // initialization anyway? It seems odd.
2276 if (ClassDecl->hasAnyDependentBases())
2277 Dependent = true;
2278 else
2279 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2280 << BaseType << Context.getTypeDeclType(ClassDecl)
2281 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2282 }
2283 }
2284
2285 if (Dependent) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002286 // Can't check initialization for a base of dependent type or when
2287 // any of the arguments are type-dependent expressions.
Sebastian Redl6df65482011-09-24 17:48:25 +00002288 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman59c04372009-07-29 19:44:27 +00002289
John McCallf85e1932011-06-15 23:02:42 +00002290 DiscardCleanupsInEvaluationContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Sebastian Redl6df65482011-09-24 17:48:25 +00002292 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2293 /*IsVirtual=*/false,
2294 Args.getStartLoc(), BaseInit,
2295 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002296 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002297
2298 // C++ [base.class.init]p2:
2299 // If a mem-initializer-id is ambiguous because it designates both
2300 // a direct non-virtual base class and an inherited virtual base
2301 // class, the mem-initializer is ill-formed.
2302 if (DirectBaseSpec && VirtualBaseSpec)
2303 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002304 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002305
2306 CXXBaseSpecifier *BaseSpec
2307 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2308 if (!BaseSpec)
2309 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2310
2311 // Initialize the base.
2312 InitializedEntity BaseEntity =
Anders Carlsson711f34a2010-04-21 19:52:01 +00002313 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002314 InitializationKind Kind =
Sebastian Redl6df65482011-09-24 17:48:25 +00002315 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2316 Args.getEndLoc());
2317
2318 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002319 if (BaseInit.isInvalid())
2320 return true;
John McCallb4eb64d2010-10-08 02:01:28 +00002321
Sebastian Redl6df65482011-09-24 17:48:25 +00002322 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2323
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002324 // C++0x [class.base.init]p7:
2325 // The initialization of each base and member constitutes a
2326 // full-expression.
Douglas Gregor53c374f2010-12-07 00:41:46 +00002327 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002328 if (BaseInit.isInvalid())
2329 return true;
2330
2331 // If we are in a dependent context, template instantiation will
2332 // perform this type-checking again. Just save the arguments that we
2333 // received in a ParenListExpr.
2334 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2335 // of the information that we have about the base
2336 // initializer. However, deconstructing the ASTs is a dicey process,
2337 // and this approach is far more likely to get the corner cases right.
Sebastian Redl6df65482011-09-24 17:48:25 +00002338 if (CurContext->isDependentContext())
2339 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002340
Sean Huntcbb67482011-01-08 20:30:50 +00002341 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redl6df65482011-09-24 17:48:25 +00002342 BaseSpec->isVirtual(),
2343 Args.getStartLoc(),
2344 BaseInit.takeAs<Expr>(),
2345 Args.getEndLoc(), EllipsisLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +00002346}
2347
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002348// Create a static_cast\<T&&>(expr).
2349static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2350 QualType ExprType = E->getType();
2351 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2352 SourceLocation ExprLoc = E->getLocStart();
2353 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2354 TargetType, ExprLoc);
2355
2356 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2357 SourceRange(ExprLoc, ExprLoc),
2358 E->getSourceRange()).take();
2359}
2360
Anders Carlssone5ef7402010-04-23 03:10:23 +00002361/// ImplicitInitializerKind - How an implicit base or member initializer should
2362/// initialize its base or member.
2363enum ImplicitInitializerKind {
2364 IIK_Default,
2365 IIK_Copy,
2366 IIK_Move
2367};
2368
Anders Carlssondefefd22010-04-23 02:00:02 +00002369static bool
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002370BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002371 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002372 CXXBaseSpecifier *BaseSpec,
Anders Carlssondefefd22010-04-23 02:00:02 +00002373 bool IsInheritedVirtualBase,
Sean Huntcbb67482011-01-08 20:30:50 +00002374 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlsson84688f22010-04-20 23:11:20 +00002375 InitializedEntity InitEntity
Anders Carlsson711f34a2010-04-21 19:52:01 +00002376 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2377 IsInheritedVirtualBase);
Anders Carlsson84688f22010-04-20 23:11:20 +00002378
John McCall60d7b3a2010-08-24 06:29:42 +00002379 ExprResult BaseInit;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002380
2381 switch (ImplicitInitKind) {
2382 case IIK_Default: {
2383 InitializationKind InitKind
2384 = InitializationKind::CreateDefault(Constructor->getLocation());
2385 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2386 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002387 MultiExprArg(SemaRef, 0, 0));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002388 break;
2389 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002390
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002391 case IIK_Move:
Anders Carlssone5ef7402010-04-23 03:10:23 +00002392 case IIK_Copy: {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002393 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssone5ef7402010-04-23 03:10:23 +00002394 ParmVarDecl *Param = Constructor->getParamDecl(0);
2395 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedmancf7c14c2012-01-16 21:00:51 +00002396
Anders Carlssone5ef7402010-04-23 03:10:23 +00002397 Expr *CopyCtorArg =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002398 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2399 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002400 Constructor->getLocation(), ParamType,
2401 VK_LValue, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002402
Eli Friedman5f2987c2012-02-02 03:46:19 +00002403 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2404
Anders Carlssonc7957502010-04-24 22:02:54 +00002405 // Cast to the base class to avoid ambiguities.
Anders Carlsson59b7f152010-05-01 16:39:01 +00002406 QualType ArgTy =
2407 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2408 ParamType.getQualifiers());
John McCallf871d0c2010-08-07 06:22:56 +00002409
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002410 if (Moving) {
2411 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2412 }
2413
John McCallf871d0c2010-08-07 06:22:56 +00002414 CXXCastPath BasePath;
2415 BasePath.push_back(BaseSpec);
John Wiegley429bb272011-04-08 18:41:53 +00002416 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2417 CK_UncheckedDerivedToBase,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002418 Moving ? VK_XValue : VK_LValue,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002419 &BasePath).take();
Anders Carlssonc7957502010-04-24 22:02:54 +00002420
Anders Carlssone5ef7402010-04-23 03:10:23 +00002421 InitializationKind InitKind
2422 = InitializationKind::CreateDirect(Constructor->getLocation(),
2423 SourceLocation(), SourceLocation());
2424 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2425 &CopyCtorArg, 1);
2426 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallf312b1e2010-08-26 23:41:50 +00002427 MultiExprArg(&CopyCtorArg, 1));
Anders Carlssone5ef7402010-04-23 03:10:23 +00002428 break;
2429 }
Anders Carlssone5ef7402010-04-23 03:10:23 +00002430 }
John McCall9ae2f072010-08-23 23:25:46 +00002431
Douglas Gregor53c374f2010-12-07 00:41:46 +00002432 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlsson84688f22010-04-20 23:11:20 +00002433 if (BaseInit.isInvalid())
Anders Carlssondefefd22010-04-23 02:00:02 +00002434 return true;
Anders Carlsson84688f22010-04-20 23:11:20 +00002435
Anders Carlssondefefd22010-04-23 02:00:02 +00002436 CXXBaseInit =
Sean Huntcbb67482011-01-08 20:30:50 +00002437 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlsson84688f22010-04-20 23:11:20 +00002438 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2439 SourceLocation()),
2440 BaseSpec->isVirtual(),
2441 SourceLocation(),
2442 BaseInit.takeAs<Expr>(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002443 SourceLocation(),
Anders Carlsson84688f22010-04-20 23:11:20 +00002444 SourceLocation());
2445
Anders Carlssondefefd22010-04-23 02:00:02 +00002446 return false;
Anders Carlsson84688f22010-04-20 23:11:20 +00002447}
2448
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002449static bool RefersToRValueRef(Expr *MemRef) {
2450 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2451 return Referenced->getType()->isRValueReferenceType();
2452}
2453
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002454static bool
2455BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002456 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002457 FieldDecl *Field, IndirectFieldDecl *Indirect,
Sean Huntcbb67482011-01-08 20:30:50 +00002458 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002459 if (Field->isInvalidDecl())
2460 return true;
2461
Chandler Carruthf186b542010-06-29 23:50:44 +00002462 SourceLocation Loc = Constructor->getLocation();
2463
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002464 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2465 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002466 ParmVarDecl *Param = Constructor->getParamDecl(0);
2467 QualType ParamType = Param->getType().getNonReferenceType();
John McCallb77115d2011-06-17 00:18:42 +00002468
2469 // Suppress copying zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002470 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2471 return false;
Douglas Gregorddb21472011-11-02 23:04:16 +00002472
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002473 Expr *MemberExprBase =
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002474 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2475 SourceLocation(), Param,
John McCallf89e55a2010-11-18 06:31:45 +00002476 Loc, ParamType, VK_LValue, 0);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002477
Eli Friedman5f2987c2012-02-02 03:46:19 +00002478 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2479
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002480 if (Moving) {
2481 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2482 }
2483
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002484 // Build a reference to this field within the parameter.
2485 CXXScopeSpec SS;
2486 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2487 Sema::LookupMemberName);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002488 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2489 : cast<ValueDecl>(Field), AS_public);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002490 MemberLookup.resolveKind();
Sebastian Redl74e611a2011-09-04 18:14:28 +00002491 ExprResult CtorArg
John McCall9ae2f072010-08-23 23:25:46 +00002492 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002493 ParamType, Loc,
2494 /*IsArrow=*/false,
2495 SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002496 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002497 /*FirstQualifierInScope=*/0,
2498 MemberLookup,
2499 /*TemplateArgs=*/0);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002500 if (CtorArg.isInvalid())
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002501 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002502
2503 // C++11 [class.copy]p15:
2504 // - if a member m has rvalue reference type T&&, it is direct-initialized
2505 // with static_cast<T&&>(x.m);
Sebastian Redl74e611a2011-09-04 18:14:28 +00002506 if (RefersToRValueRef(CtorArg.get())) {
2507 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002508 }
2509
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002510 // When the field we are copying is an array, create index variables for
2511 // each dimension of the array. We use these index variables to subscript
2512 // the source array, and other clients (e.g., CodeGen) will perform the
2513 // necessary iteration with these index variables.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002514 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002515 QualType BaseType = Field->getType();
2516 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002517 bool InitializingArray = false;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002518 while (const ConstantArrayType *Array
2519 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002520 InitializingArray = true;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002521 // Create the iteration variable for this array index.
2522 IdentifierInfo *IterationVarName = 0;
2523 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002524 SmallString<8> Str;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002525 llvm::raw_svector_ostream OS(Str);
2526 OS << "__i" << IndexVariables.size();
2527 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2528 }
2529 VarDecl *IterationVar
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002530 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002531 IterationVarName, SizeType,
2532 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00002533 SC_None, SC_None);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002534 IndexVariables.push_back(IterationVar);
2535
2536 // Create a reference to the iteration variable.
John McCall60d7b3a2010-08-24 06:29:42 +00002537 ExprResult IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00002538 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002539 assert(!IterationVarRef.isInvalid() &&
2540 "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00002541 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2542 assert(!IterationVarRef.isInvalid() &&
2543 "Conversion of invented variable cannot fail!");
Sebastian Redl74e611a2011-09-04 18:14:28 +00002544
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002545 // Subscript the array with this iteration variable.
Sebastian Redl74e611a2011-09-04 18:14:28 +00002546 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCall9ae2f072010-08-23 23:25:46 +00002547 IterationVarRef.take(),
Sebastian Redl74e611a2011-09-04 18:14:28 +00002548 Loc);
2549 if (CtorArg.isInvalid())
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002550 return true;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002551
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002552 BaseType = Array->getElementType();
2553 }
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002554
2555 // The array subscript expression is an lvalue, which is wrong for moving.
2556 if (Moving && InitializingArray)
Sebastian Redl74e611a2011-09-04 18:14:28 +00002557 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002558
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002559 // Construct the entity that we will be initializing. For an array, this
2560 // will be first element in the array, which may require several levels
2561 // of array-subscript entities.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002562 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002563 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002564 if (Indirect)
2565 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2566 else
2567 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002568 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2569 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2570 0,
2571 Entities.back()));
2572
2573 // Direct-initialize to use the copy constructor.
2574 InitializationKind InitKind =
2575 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2576
Sebastian Redl74e611a2011-09-04 18:14:28 +00002577 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002578 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002579 &CtorArgE, 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002580
John McCall60d7b3a2010-08-24 06:29:42 +00002581 ExprResult MemberInit
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002582 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redl74e611a2011-09-04 18:14:28 +00002583 MultiExprArg(&CtorArgE, 1));
Douglas Gregor53c374f2010-12-07 00:41:46 +00002584 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregorfb8cc252010-05-05 05:51:00 +00002585 if (MemberInit.isInvalid())
2586 return true;
2587
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002588 if (Indirect) {
2589 assert(IndexVariables.size() == 0 &&
2590 "Indirect field improperly initialized");
2591 CXXMemberInit
2592 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2593 Loc, Loc,
2594 MemberInit.takeAs<Expr>(),
2595 Loc);
2596 } else
2597 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2598 Loc, MemberInit.takeAs<Expr>(),
2599 Loc,
2600 IndexVariables.data(),
2601 IndexVariables.size());
Anders Carlssone5ef7402010-04-23 03:10:23 +00002602 return false;
2603 }
2604
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002605 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2606
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002607 QualType FieldBaseElementType =
2608 SemaRef.Context.getBaseElementType(Field->getType());
2609
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002610 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002611 InitializedEntity InitEntity
2612 = Indirect? InitializedEntity::InitializeMember(Indirect)
2613 : InitializedEntity::InitializeMember(Field);
Anders Carlssonf6513ed2010-04-23 16:04:08 +00002614 InitializationKind InitKind =
Chandler Carruthf186b542010-06-29 23:50:44 +00002615 InitializationKind::CreateDefault(Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002616
2617 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00002618 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +00002619 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCall9ae2f072010-08-23 23:25:46 +00002620
Douglas Gregor53c374f2010-12-07 00:41:46 +00002621 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002622 if (MemberInit.isInvalid())
2623 return true;
2624
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002625 if (Indirect)
2626 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2627 Indirect, Loc,
2628 Loc,
2629 MemberInit.get(),
2630 Loc);
2631 else
2632 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2633 Field, Loc, Loc,
2634 MemberInit.get(),
2635 Loc);
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002636 return false;
2637 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002638
Sean Hunt1f2f3842011-05-17 00:19:05 +00002639 if (!Field->getParent()->isUnion()) {
2640 if (FieldBaseElementType->isReferenceType()) {
2641 SemaRef.Diag(Constructor->getLocation(),
2642 diag::err_uninitialized_member_in_ctor)
2643 << (int)Constructor->isImplicit()
2644 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2645 << 0 << Field->getDeclName();
2646 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2647 return true;
2648 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002649
Sean Hunt1f2f3842011-05-17 00:19:05 +00002650 if (FieldBaseElementType.isConstQualified()) {
2651 SemaRef.Diag(Constructor->getLocation(),
2652 diag::err_uninitialized_member_in_ctor)
2653 << (int)Constructor->isImplicit()
2654 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2655 << 1 << Field->getDeclName();
2656 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2657 return true;
2658 }
Anders Carlsson114a2972010-04-23 03:07:47 +00002659 }
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002660
John McCallf85e1932011-06-15 23:02:42 +00002661 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2662 FieldBaseElementType->isObjCRetainableType() &&
2663 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2664 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2665 // Instant objects:
2666 // Default-initialize Objective-C pointers to NULL.
2667 CXXMemberInit
2668 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2669 Loc, Loc,
2670 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2671 Loc);
2672 return false;
2673 }
2674
Anders Carlssonddfb75f2010-04-23 02:15:47 +00002675 // Nothing to initialize.
2676 CXXMemberInit = 0;
2677 return false;
2678}
John McCallf1860e52010-05-20 23:23:51 +00002679
2680namespace {
2681struct BaseAndFieldInfo {
2682 Sema &S;
2683 CXXConstructorDecl *Ctor;
2684 bool AnyErrorsInInits;
2685 ImplicitInitializerKind IIK;
Sean Huntcbb67482011-01-08 20:30:50 +00002686 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002687 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallf1860e52010-05-20 23:23:51 +00002688
2689 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2690 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002691 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2692 if (Generated && Ctor->isCopyConstructor())
John McCallf1860e52010-05-20 23:23:51 +00002693 IIK = IIK_Copy;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002694 else if (Generated && Ctor->isMoveConstructor())
2695 IIK = IIK_Move;
John McCallf1860e52010-05-20 23:23:51 +00002696 else
2697 IIK = IIK_Default;
2698 }
Douglas Gregorf4853882011-11-28 20:03:15 +00002699
2700 bool isImplicitCopyOrMove() const {
2701 switch (IIK) {
2702 case IIK_Copy:
2703 case IIK_Move:
2704 return true;
2705
2706 case IIK_Default:
2707 return false;
2708 }
David Blaikie30263482012-01-20 21:50:17 +00002709
2710 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregorf4853882011-11-28 20:03:15 +00002711 }
John McCallf1860e52010-05-20 23:23:51 +00002712};
2713}
2714
Richard Smitha4950662011-09-19 13:34:43 +00002715/// \brief Determine whether the given indirect field declaration is somewhere
2716/// within an anonymous union.
2717static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2718 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2719 CEnd = F->chain_end();
2720 C != CEnd; ++C)
2721 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2722 if (Record->isUnion())
2723 return true;
2724
2725 return false;
2726}
2727
Douglas Gregorddb21472011-11-02 23:04:16 +00002728/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2729/// array type.
2730static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2731 if (T->isIncompleteArrayType())
2732 return true;
2733
2734 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2735 if (!ArrayT->getSize())
2736 return true;
2737
2738 T = ArrayT->getElementType();
2739 }
2740
2741 return false;
2742}
2743
Richard Smith7a614d82011-06-11 17:19:42 +00002744static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002745 FieldDecl *Field,
2746 IndirectFieldDecl *Indirect = 0) {
John McCallf1860e52010-05-20 23:23:51 +00002747
Chandler Carruthe861c602010-06-30 02:59:29 +00002748 // Overwhelmingly common case: we have a direct initializer for this field.
Sean Huntcbb67482011-01-08 20:30:50 +00002749 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002750 Info.AllToInit.push_back(Init);
John McCallf1860e52010-05-20 23:23:51 +00002751 return false;
2752 }
2753
Richard Smith7a614d82011-06-11 17:19:42 +00002754 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2755 // has a brace-or-equal-initializer, the entity is initialized as specified
2756 // in [dcl.init].
Douglas Gregorf4853882011-11-28 20:03:15 +00002757 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002758 CXXCtorInitializer *Init;
2759 if (Indirect)
2760 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2761 SourceLocation(),
2762 SourceLocation(), 0,
2763 SourceLocation());
2764 else
2765 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2766 SourceLocation(),
2767 SourceLocation(), 0,
2768 SourceLocation());
2769 Info.AllToInit.push_back(Init);
Richard Smith7a614d82011-06-11 17:19:42 +00002770 return false;
2771 }
2772
Richard Smithc115f632011-09-18 11:14:50 +00002773 // Don't build an implicit initializer for union members if none was
2774 // explicitly specified.
Richard Smitha4950662011-09-19 13:34:43 +00002775 if (Field->getParent()->isUnion() ||
2776 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smithc115f632011-09-18 11:14:50 +00002777 return false;
2778
Douglas Gregorddb21472011-11-02 23:04:16 +00002779 // Don't initialize incomplete or zero-length arrays.
2780 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2781 return false;
2782
John McCallf1860e52010-05-20 23:23:51 +00002783 // Don't try to build an implicit initializer if there were semantic
2784 // errors in any of the initializers (and therefore we might be
2785 // missing some that the user actually wrote).
Richard Smith7a614d82011-06-11 17:19:42 +00002786 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallf1860e52010-05-20 23:23:51 +00002787 return false;
2788
Sean Huntcbb67482011-01-08 20:30:50 +00002789 CXXCtorInitializer *Init = 0;
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002790 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2791 Indirect, Init))
John McCallf1860e52010-05-20 23:23:51 +00002792 return true;
John McCallf1860e52010-05-20 23:23:51 +00002793
Francois Pichet00eb3f92010-12-04 09:14:42 +00002794 if (Init)
2795 Info.AllToInit.push_back(Init);
2796
John McCallf1860e52010-05-20 23:23:51 +00002797 return false;
2798}
Sean Hunt059ce0d2011-05-01 07:04:31 +00002799
2800bool
2801Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2802 CXXCtorInitializer *Initializer) {
Sean Huntfe57eef2011-05-04 05:57:24 +00002803 assert(Initializer->isDelegatingInitializer());
Sean Hunt01aacc02011-05-03 20:43:02 +00002804 Constructor->setNumCtorInitializers(1);
2805 CXXCtorInitializer **initializer =
2806 new (Context) CXXCtorInitializer*[1];
2807 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2808 Constructor->setCtorInitializers(initializer);
2809
Sean Huntb76af9c2011-05-03 23:05:34 +00002810 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00002811 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Sean Huntb76af9c2011-05-03 23:05:34 +00002812 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2813 }
2814
Sean Huntc1598702011-05-05 00:05:47 +00002815 DelegatingCtorDecls.push_back(Constructor);
Sean Huntfe57eef2011-05-04 05:57:24 +00002816
Sean Hunt059ce0d2011-05-01 07:04:31 +00002817 return false;
2818}
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002819
John McCallb77115d2011-06-17 00:18:42 +00002820bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2821 CXXCtorInitializer **Initializers,
2822 unsigned NumInitializers,
2823 bool AnyErrors) {
Douglas Gregord836c0d2011-09-22 23:04:35 +00002824 if (Constructor->isDependentContext()) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002825 // Just store the initializers as written, they will be checked during
2826 // instantiation.
2827 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002828 Constructor->setNumCtorInitializers(NumInitializers);
2829 CXXCtorInitializer **baseOrMemberInitializers =
2830 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002831 memcpy(baseOrMemberInitializers, Initializers,
Sean Huntcbb67482011-01-08 20:30:50 +00002832 NumInitializers * sizeof(CXXCtorInitializer*));
2833 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002834 }
2835
2836 return false;
2837 }
2838
John McCallf1860e52010-05-20 23:23:51 +00002839 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlssone5ef7402010-04-23 03:10:23 +00002840
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002841 // We need to build the initializer AST according to order of construction
2842 // and not what user specified in the Initializers list.
Anders Carlssonea356fb2010-04-02 05:42:15 +00002843 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregord6068482010-03-26 22:43:07 +00002844 if (!ClassDecl)
2845 return true;
2846
Eli Friedman80c30da2009-11-09 19:20:36 +00002847 bool HadError = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002848
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002849 for (unsigned i = 0; i < NumInitializers; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00002850 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002851
2852 if (Member->isBaseInitializer())
John McCallf1860e52010-05-20 23:23:51 +00002853 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002854 else
Francois Pichet00eb3f92010-12-04 09:14:42 +00002855 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002856 }
2857
Anders Carlsson711f34a2010-04-21 19:52:01 +00002858 // Keep track of the direct virtual bases.
2859 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2860 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2861 E = ClassDecl->bases_end(); I != E; ++I) {
2862 if (I->isVirtual())
2863 DirectVBases.insert(I);
2864 }
2865
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002866 // Push virtual bases before others.
2867 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2868 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2869
Sean Huntcbb67482011-01-08 20:30:50 +00002870 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002871 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2872 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002873 } else if (!AnyErrors) {
Anders Carlsson711f34a2010-04-21 19:52:01 +00002874 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Sean Huntcbb67482011-01-08 20:30:50 +00002875 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002876 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002877 VBase, IsInheritedVirtualBase,
2878 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002879 HadError = true;
2880 continue;
2881 }
Anders Carlsson84688f22010-04-20 23:11:20 +00002882
John McCallf1860e52010-05-20 23:23:51 +00002883 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002884 }
2885 }
Mike Stump1eb44332009-09-09 15:08:12 +00002886
John McCallf1860e52010-05-20 23:23:51 +00002887 // Non-virtual bases.
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002888 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2889 E = ClassDecl->bases_end(); Base != E; ++Base) {
2890 // Virtuals are in the virtual base list and already constructed.
2891 if (Base->isVirtual())
2892 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00002893
Sean Huntcbb67482011-01-08 20:30:50 +00002894 if (CXXCtorInitializer *Value
John McCallf1860e52010-05-20 23:23:51 +00002895 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2896 Info.AllToInit.push_back(Value);
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002897 } else if (!AnyErrors) {
Sean Huntcbb67482011-01-08 20:30:50 +00002898 CXXCtorInitializer *CXXBaseInit;
John McCallf1860e52010-05-20 23:23:51 +00002899 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlssone5ef7402010-04-23 03:10:23 +00002900 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlssondefefd22010-04-23 02:00:02 +00002901 CXXBaseInit)) {
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002902 HadError = true;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002903 continue;
Anders Carlssonbcc12fd2010-04-02 06:26:44 +00002904 }
Fariborz Jahanian9d436202009-09-03 21:32:41 +00002905
John McCallf1860e52010-05-20 23:23:51 +00002906 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002907 }
2908 }
Mike Stump1eb44332009-09-09 15:08:12 +00002909
John McCallf1860e52010-05-20 23:23:51 +00002910 // Fields.
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002911 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2912 MemEnd = ClassDecl->decls_end();
2913 Mem != MemEnd; ++Mem) {
2914 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregord61db332011-10-10 17:22:13 +00002915 // C++ [class.bit]p2:
2916 // A declaration for a bit-field that omits the identifier declares an
2917 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2918 // initialized.
2919 if (F->isUnnamedBitfield())
2920 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00002921
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00002922 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002923 // handle anonymous struct/union fields based on their individual
2924 // indirect fields.
2925 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2926 continue;
2927
2928 if (CollectFieldInitializer(*this, Info, F))
2929 HadError = true;
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002930 continue;
2931 }
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002932
2933 // Beyond this point, we only consider default initialization.
2934 if (Info.IIK != IIK_Default)
2935 continue;
2936
2937 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2938 if (F->getType()->isIncompleteArrayType()) {
2939 assert(ClassDecl->hasFlexibleArrayMember() &&
2940 "Incomplete array type is not valid");
2941 continue;
2942 }
2943
Douglas Gregor4dc41c92011-08-10 15:22:55 +00002944 // Initialize each field of an anonymous struct individually.
2945 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2946 HadError = true;
2947
2948 continue;
2949 }
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00002950 }
Mike Stump1eb44332009-09-09 15:08:12 +00002951
John McCallf1860e52010-05-20 23:23:51 +00002952 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002953 if (NumInitializers > 0) {
Sean Huntcbb67482011-01-08 20:30:50 +00002954 Constructor->setNumCtorInitializers(NumInitializers);
2955 CXXCtorInitializer **baseOrMemberInitializers =
2956 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallf1860e52010-05-20 23:23:51 +00002957 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Sean Huntcbb67482011-01-08 20:30:50 +00002958 NumInitializers * sizeof(CXXCtorInitializer*));
2959 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola961b1672010-03-13 18:12:56 +00002960
John McCallef027fe2010-03-16 21:39:52 +00002961 // Constructors implicitly reference the base and member
2962 // destructors.
2963 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2964 Constructor->getParent());
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002965 }
Eli Friedman80c30da2009-11-09 19:20:36 +00002966
2967 return HadError;
Fariborz Jahanian80545ad2009-09-03 19:36:46 +00002968}
2969
Eli Friedman6347f422009-07-21 19:28:10 +00002970static void *GetKeyForTopLevelField(FieldDecl *Field) {
2971 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +00002972 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +00002973 if (RT->getDecl()->isAnonymousStructOrUnion())
2974 return static_cast<void *>(RT->getDecl());
2975 }
2976 return static_cast<void *>(Field);
2977}
2978
Anders Carlssonea356fb2010-04-02 05:42:15 +00002979static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCallf4c73712011-01-19 06:33:43 +00002980 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssoncdc83c72009-09-01 06:22:14 +00002981}
2982
Anders Carlssonea356fb2010-04-02 05:42:15 +00002983static void *GetKeyForMember(ASTContext &Context,
Sean Huntcbb67482011-01-08 20:30:50 +00002984 CXXCtorInitializer *Member) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00002985 if (!Member->isAnyMemberInitializer())
Anders Carlssonea356fb2010-04-02 05:42:15 +00002986 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlsson8f1a2402010-03-30 15:39:27 +00002987
Eli Friedman6347f422009-07-21 19:28:10 +00002988 // For fields injected into the class via declaration of an anonymous union,
2989 // use its anonymous union class declaration as the unique key.
Francois Pichet00eb3f92010-12-04 09:14:42 +00002990 FieldDecl *Field = Member->getAnyMember();
2991
John McCall3c3ccdb2010-04-10 09:28:51 +00002992 // If the field is a member of an anonymous struct or union, our key
2993 // is the anonymous record decl that's a direct child of the class.
Anders Carlssonee11b2d2010-03-30 16:19:37 +00002994 RecordDecl *RD = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00002995 if (RD->isAnonymousStructOrUnion()) {
2996 while (true) {
2997 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2998 if (Parent->isAnonymousStructOrUnion())
2999 RD = Parent;
3000 else
3001 break;
3002 }
3003
Anders Carlssonee11b2d2010-03-30 16:19:37 +00003004 return static_cast<void *>(RD);
John McCall3c3ccdb2010-04-10 09:28:51 +00003005 }
Mike Stump1eb44332009-09-09 15:08:12 +00003006
Anders Carlsson8f1a2402010-03-30 15:39:27 +00003007 return static_cast<void *>(Field);
Eli Friedman6347f422009-07-21 19:28:10 +00003008}
3009
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003010static void
3011DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson071d6102010-04-02 03:38:04 +00003012 const CXXConstructorDecl *Constructor,
Sean Huntcbb67482011-01-08 20:30:50 +00003013 CXXCtorInitializer **Inits,
John McCalld6ca8da2010-04-10 07:37:23 +00003014 unsigned NumInits) {
3015 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +00003016 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003017
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003018 // Don't check initializers order unless the warning is enabled at the
3019 // location of at least one initializer.
3020 bool ShouldCheckOrder = false;
3021 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003022 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003023 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3024 Init->getSourceLocation())
David Blaikied6471f72011-09-25 23:23:43 +00003025 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003026 ShouldCheckOrder = true;
3027 break;
3028 }
3029 }
3030 if (!ShouldCheckOrder)
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003031 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003032
John McCalld6ca8da2010-04-10 07:37:23 +00003033 // Build the list of bases and members in the order that they'll
3034 // actually be initialized. The explicit initializers should be in
3035 // this same order but may be missing things.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003036 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump1eb44332009-09-09 15:08:12 +00003037
Anders Carlsson071d6102010-04-02 03:38:04 +00003038 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3039
John McCalld6ca8da2010-04-10 07:37:23 +00003040 // 1. Virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003041 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003042 ClassDecl->vbases_begin(),
3043 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCalld6ca8da2010-04-10 07:37:23 +00003044 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00003045
John McCalld6ca8da2010-04-10 07:37:23 +00003046 // 2. Non-virtual bases.
Anders Carlsson071d6102010-04-02 03:38:04 +00003047 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003048 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003049 if (Base->isVirtual())
3050 continue;
John McCalld6ca8da2010-04-10 07:37:23 +00003051 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003052 }
Mike Stump1eb44332009-09-09 15:08:12 +00003053
John McCalld6ca8da2010-04-10 07:37:23 +00003054 // 3. Direct fields.
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003055 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregord61db332011-10-10 17:22:13 +00003056 E = ClassDecl->field_end(); Field != E; ++Field) {
3057 if (Field->isUnnamedBitfield())
3058 continue;
3059
John McCalld6ca8da2010-04-10 07:37:23 +00003060 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregord61db332011-10-10 17:22:13 +00003061 }
3062
John McCalld6ca8da2010-04-10 07:37:23 +00003063 unsigned NumIdealInits = IdealInitKeys.size();
3064 unsigned IdealIndex = 0;
Eli Friedman6347f422009-07-21 19:28:10 +00003065
Sean Huntcbb67482011-01-08 20:30:50 +00003066 CXXCtorInitializer *PrevInit = 0;
John McCalld6ca8da2010-04-10 07:37:23 +00003067 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Sean Huntcbb67482011-01-08 20:30:50 +00003068 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichet00eb3f92010-12-04 09:14:42 +00003069 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCalld6ca8da2010-04-10 07:37:23 +00003070
3071 // Scan forward to try to find this initializer in the idealized
3072 // initializers list.
3073 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3074 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003075 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003076
3077 // If we didn't find this initializer, it must be because we
3078 // scanned past it on a previous iteration. That can only
3079 // happen if we're out of order; emit a warning.
Douglas Gregorfe2d3792010-05-20 23:49:34 +00003080 if (IdealIndex == NumIdealInits && PrevInit) {
John McCalld6ca8da2010-04-10 07:37:23 +00003081 Sema::SemaDiagnosticBuilder D =
3082 SemaRef.Diag(PrevInit->getSourceLocation(),
3083 diag::warn_initializer_out_of_order);
3084
Francois Pichet00eb3f92010-12-04 09:14:42 +00003085 if (PrevInit->isAnyMemberInitializer())
3086 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003087 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003088 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003089
Francois Pichet00eb3f92010-12-04 09:14:42 +00003090 if (Init->isAnyMemberInitializer())
3091 D << 0 << Init->getAnyMember()->getDeclName();
John McCalld6ca8da2010-04-10 07:37:23 +00003092 else
Douglas Gregor76852c22011-11-01 01:16:03 +00003093 D << 1 << Init->getTypeSourceInfo()->getType();
John McCalld6ca8da2010-04-10 07:37:23 +00003094
3095 // Move back to the initializer's location in the ideal list.
3096 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3097 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlsson5c36fb22009-08-27 05:45:01 +00003098 break;
John McCalld6ca8da2010-04-10 07:37:23 +00003099
3100 assert(IdealIndex != NumIdealInits &&
3101 "initializer not found in initializer list");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003102 }
John McCalld6ca8da2010-04-10 07:37:23 +00003103
3104 PrevInit = Init;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00003105 }
Anders Carlssona7b35212009-03-25 02:58:17 +00003106}
3107
John McCall3c3ccdb2010-04-10 09:28:51 +00003108namespace {
3109bool CheckRedundantInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003110 CXXCtorInitializer *Init,
3111 CXXCtorInitializer *&PrevInit) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003112 if (!PrevInit) {
3113 PrevInit = Init;
3114 return false;
3115 }
3116
3117 if (FieldDecl *Field = Init->getMember())
3118 S.Diag(Init->getSourceLocation(),
3119 diag::err_multiple_mem_initialization)
3120 << Field->getDeclName()
3121 << Init->getSourceRange();
3122 else {
John McCallf4c73712011-01-19 06:33:43 +00003123 const Type *BaseClass = Init->getBaseClass();
John McCall3c3ccdb2010-04-10 09:28:51 +00003124 assert(BaseClass && "neither field nor base");
3125 S.Diag(Init->getSourceLocation(),
3126 diag::err_multiple_base_initialization)
3127 << QualType(BaseClass, 0)
3128 << Init->getSourceRange();
3129 }
3130 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3131 << 0 << PrevInit->getSourceRange();
3132
3133 return true;
3134}
3135
Sean Huntcbb67482011-01-08 20:30:50 +00003136typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall3c3ccdb2010-04-10 09:28:51 +00003137typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3138
3139bool CheckRedundantUnionInit(Sema &S,
Sean Huntcbb67482011-01-08 20:30:50 +00003140 CXXCtorInitializer *Init,
John McCall3c3ccdb2010-04-10 09:28:51 +00003141 RedundantUnionMap &Unions) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00003142 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003143 RecordDecl *Parent = Field->getParent();
John McCall3c3ccdb2010-04-10 09:28:51 +00003144 NamedDecl *Child = Field;
David Blaikie6fe29652011-11-17 06:01:57 +00003145
3146 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003147 if (Parent->isUnion()) {
3148 UnionEntry &En = Unions[Parent];
3149 if (En.first && En.first != Child) {
3150 S.Diag(Init->getSourceLocation(),
3151 diag::err_multiple_mem_union_initialization)
3152 << Field->getDeclName()
3153 << Init->getSourceRange();
3154 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3155 << 0 << En.second->getSourceRange();
3156 return true;
David Blaikie5bbe8162011-11-12 20:54:14 +00003157 }
3158 if (!En.first) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003159 En.first = Child;
3160 En.second = Init;
3161 }
David Blaikie6fe29652011-11-17 06:01:57 +00003162 if (!Parent->isAnonymousStructOrUnion())
3163 return false;
John McCall3c3ccdb2010-04-10 09:28:51 +00003164 }
3165
3166 Child = Parent;
3167 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie6fe29652011-11-17 06:01:57 +00003168 }
John McCall3c3ccdb2010-04-10 09:28:51 +00003169
3170 return false;
3171}
3172}
3173
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003174/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCalld226f652010-08-21 09:40:31 +00003175void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003176 SourceLocation ColonLoc,
Richard Trieu90ab75b2011-09-09 03:18:59 +00003177 CXXCtorInitializer **meminits,
3178 unsigned NumMemInits,
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003179 bool AnyErrors) {
3180 if (!ConstructorDecl)
3181 return;
3182
3183 AdjustDeclIfTemplate(ConstructorDecl);
3184
3185 CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003186 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003187
3188 if (!Constructor) {
3189 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3190 return;
3191 }
3192
Sean Huntcbb67482011-01-08 20:30:50 +00003193 CXXCtorInitializer **MemInits =
3194 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall3c3ccdb2010-04-10 09:28:51 +00003195
3196 // Mapping for the duplicate initializers check.
3197 // For member initializers, this is keyed with a FieldDecl*.
3198 // For base initializers, this is keyed with a Type*.
Sean Huntcbb67482011-01-08 20:30:50 +00003199 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall3c3ccdb2010-04-10 09:28:51 +00003200
3201 // Mapping for the inconsistent anonymous-union initializers check.
3202 RedundantUnionMap MemberUnions;
3203
Anders Carlssonea356fb2010-04-02 05:42:15 +00003204 bool HadError = false;
3205 for (unsigned i = 0; i < NumMemInits; i++) {
Sean Huntcbb67482011-01-08 20:30:50 +00003206 CXXCtorInitializer *Init = MemInits[i];
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003207
Abramo Bagnaraa0af3b42010-05-26 18:09:23 +00003208 // Set the source order index.
3209 Init->setSourceOrder(i);
3210
Francois Pichet00eb3f92010-12-04 09:14:42 +00003211 if (Init->isAnyMemberInitializer()) {
3212 FieldDecl *Field = Init->getAnyMember();
John McCall3c3ccdb2010-04-10 09:28:51 +00003213 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3214 CheckRedundantUnionInit(*this, Init, MemberUnions))
3215 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003216 } else if (Init->isBaseInitializer()) {
John McCall3c3ccdb2010-04-10 09:28:51 +00003217 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3218 if (CheckRedundantInit(*this, Init, Members[Key]))
3219 HadError = true;
Sean Hunt41717662011-02-26 19:13:13 +00003220 } else {
3221 assert(Init->isDelegatingInitializer());
3222 // This must be the only initializer
3223 if (i != 0 || NumMemInits > 1) {
3224 Diag(MemInits[0]->getSourceLocation(),
3225 diag::err_delegating_initializer_alone)
3226 << MemInits[0]->getSourceRange();
3227 HadError = true;
Sean Hunt059ce0d2011-05-01 07:04:31 +00003228 // We will treat this as being the only initializer.
Sean Hunt41717662011-02-26 19:13:13 +00003229 }
Sean Huntfe57eef2011-05-04 05:57:24 +00003230 SetDelegatingInitializer(Constructor, MemInits[i]);
Sean Hunt059ce0d2011-05-01 07:04:31 +00003231 // Return immediately as the initializer is set.
3232 return;
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003233 }
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003234 }
3235
Anders Carlssonea356fb2010-04-02 05:42:15 +00003236 if (HadError)
3237 return;
3238
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003239 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlssonec3332b2010-04-02 03:43:34 +00003240
Sean Huntcbb67482011-01-08 20:30:50 +00003241 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlsson58cfbde2010-04-02 03:37:03 +00003242}
3243
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003244void
John McCallef027fe2010-03-16 21:39:52 +00003245Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3246 CXXRecordDecl *ClassDecl) {
Richard Smith416f63e2011-09-18 12:11:43 +00003247 // Ignore dependent contexts. Also ignore unions, since their members never
3248 // have destructors implicitly called.
3249 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlsson9f853df2009-11-17 04:44:12 +00003250 return;
John McCall58e6f342010-03-16 05:22:47 +00003251
3252 // FIXME: all the access-control diagnostics are positioned on the
3253 // field/base declaration. That's probably good; that said, the
3254 // user might reasonably want to know why the destructor is being
3255 // emitted, and we currently don't say.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003256
Anders Carlsson9f853df2009-11-17 04:44:12 +00003257 // Non-static data members.
3258 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3259 E = ClassDecl->field_end(); I != E; ++I) {
3260 FieldDecl *Field = *I;
Fariborz Jahanian9614dc02010-05-17 18:15:18 +00003261 if (Field->isInvalidDecl())
3262 continue;
Douglas Gregorddb21472011-11-02 23:04:16 +00003263
3264 // Don't destroy incomplete or zero-length arrays.
3265 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3266 continue;
3267
Anders Carlsson9f853df2009-11-17 04:44:12 +00003268 QualType FieldType = Context.getBaseElementType(Field->getType());
3269
3270 const RecordType* RT = FieldType->getAs<RecordType>();
3271 if (!RT)
3272 continue;
3273
3274 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003275 if (FieldClassDecl->isInvalidDecl())
3276 continue;
Anders Carlsson9f853df2009-11-17 04:44:12 +00003277 if (FieldClassDecl->hasTrivialDestructor())
3278 continue;
3279
Douglas Gregordb89f282010-07-01 22:47:18 +00003280 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003281 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003282 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003283 PDiag(diag::err_access_dtor_field)
John McCall58e6f342010-03-16 05:22:47 +00003284 << Field->getDeclName()
3285 << FieldType);
3286
Eli Friedman5f2987c2012-02-02 03:46:19 +00003287 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003288 }
3289
John McCall58e6f342010-03-16 05:22:47 +00003290 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3291
Anders Carlsson9f853df2009-11-17 04:44:12 +00003292 // Bases.
3293 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3294 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall58e6f342010-03-16 05:22:47 +00003295 // Bases are always records in a well-formed non-dependent class.
3296 const RecordType *RT = Base->getType()->getAs<RecordType>();
3297
3298 // Remember direct virtual bases.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003299 if (Base->isVirtual())
John McCall58e6f342010-03-16 05:22:47 +00003300 DirectVirtualBases.insert(RT);
Anders Carlsson9f853df2009-11-17 04:44:12 +00003301
John McCall58e6f342010-03-16 05:22:47 +00003302 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003303 // If our base class is invalid, we probably can't get its dtor anyway.
3304 if (BaseClassDecl->isInvalidDecl())
3305 continue;
3306 // Ignore trivial destructors.
Anders Carlsson9f853df2009-11-17 04:44:12 +00003307 if (BaseClassDecl->hasTrivialDestructor())
3308 continue;
John McCall58e6f342010-03-16 05:22:47 +00003309
Douglas Gregordb89f282010-07-01 22:47:18 +00003310 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003311 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003312
3313 // FIXME: caret should be on the start of the class name
3314 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003315 PDiag(diag::err_access_dtor_base)
John McCall58e6f342010-03-16 05:22:47 +00003316 << Base->getType()
3317 << Base->getSourceRange());
Anders Carlsson9f853df2009-11-17 04:44:12 +00003318
Eli Friedman5f2987c2012-02-02 03:46:19 +00003319 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlsson9f853df2009-11-17 04:44:12 +00003320 }
3321
3322 // Virtual bases.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003323 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3324 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall58e6f342010-03-16 05:22:47 +00003325
3326 // Bases are always records in a well-formed non-dependent class.
3327 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3328
3329 // Ignore direct virtual bases.
3330 if (DirectVirtualBases.count(RT))
3331 continue;
3332
John McCall58e6f342010-03-16 05:22:47 +00003333 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003334 // If our base class is invalid, we probably can't get its dtor anyway.
3335 if (BaseClassDecl->isInvalidDecl())
3336 continue;
3337 // Ignore trivial destructors.
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003338 if (BaseClassDecl->hasTrivialDestructor())
3339 continue;
John McCall58e6f342010-03-16 05:22:47 +00003340
Douglas Gregordb89f282010-07-01 22:47:18 +00003341 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay3334b0b2011-03-28 01:39:13 +00003342 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall58e6f342010-03-16 05:22:47 +00003343 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00003344 PDiag(diag::err_access_dtor_vbase)
John McCall58e6f342010-03-16 05:22:47 +00003345 << VBase->getType());
3346
Eli Friedman5f2987c2012-02-02 03:46:19 +00003347 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian34374e62009-09-03 23:18:17 +00003348 }
3349}
3350
John McCalld226f652010-08-21 09:40:31 +00003351void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00003352 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003353 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003354
Mike Stump1eb44332009-09-09 15:08:12 +00003355 if (CXXConstructorDecl *Constructor
John McCalld226f652010-08-21 09:40:31 +00003356 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Sean Huntcbb67482011-01-08 20:30:50 +00003357 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00003358}
3359
Mike Stump1eb44332009-09-09 15:08:12 +00003360bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003361 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003362 if (SelID == -1)
John McCall94c3b562010-08-18 09:41:07 +00003363 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003364 else
John McCall94c3b562010-08-18 09:41:07 +00003365 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump1eb44332009-09-09 15:08:12 +00003366}
3367
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003368bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall94c3b562010-08-18 09:41:07 +00003369 const PartialDiagnostic &PD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003370 if (!getLangOptions().CPlusPlus)
3371 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003372
Anders Carlsson11f21a02009-03-23 19:10:31 +00003373 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall94c3b562010-08-18 09:41:07 +00003374 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump1eb44332009-09-09 15:08:12 +00003375
Ted Kremenek6217b802009-07-29 21:53:49 +00003376 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003377 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003378 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003379 PT = T;
Mike Stump1eb44332009-09-09 15:08:12 +00003380
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003381 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall94c3b562010-08-18 09:41:07 +00003382 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00003383 }
Mike Stump1eb44332009-09-09 15:08:12 +00003384
Ted Kremenek6217b802009-07-29 21:53:49 +00003385 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003386 if (!RT)
3387 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003388
John McCall86ff3082010-02-04 22:26:26 +00003389 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003390
John McCall94c3b562010-08-18 09:41:07 +00003391 // We can't answer whether something is abstract until it has a
3392 // definition. If it's currently being defined, we'll walk back
3393 // over all the declarations when we have a full definition.
3394 const CXXRecordDecl *Def = RD->getDefinition();
3395 if (!Def || Def->isBeingDefined())
John McCall86ff3082010-02-04 22:26:26 +00003396 return false;
3397
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003398 if (!RD->isAbstract())
3399 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003400
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00003401 Diag(Loc, PD) << RD->getDeclName();
John McCall94c3b562010-08-18 09:41:07 +00003402 DiagnoseAbstractType(RD);
Mike Stump1eb44332009-09-09 15:08:12 +00003403
John McCall94c3b562010-08-18 09:41:07 +00003404 return true;
3405}
3406
3407void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3408 // Check if we've already emitted the list of pure virtual functions
3409 // for this class.
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003410 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall94c3b562010-08-18 09:41:07 +00003411 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003413 CXXFinalOverriderMap FinalOverriders;
3414 RD->getFinalOverriders(FinalOverriders);
Mike Stump1eb44332009-09-09 15:08:12 +00003415
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003416 // Keep a set of seen pure methods so we won't diagnose the same method
3417 // more than once.
3418 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3419
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003420 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3421 MEnd = FinalOverriders.end();
3422 M != MEnd;
3423 ++M) {
3424 for (OverridingMethods::iterator SO = M->second.begin(),
3425 SOEnd = M->second.end();
3426 SO != SOEnd; ++SO) {
3427 // C++ [class.abstract]p4:
3428 // A class is abstract if it contains or inherits at least one
3429 // pure virtual function for which the final overrider is pure
3430 // virtual.
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003432 //
3433 if (SO->second.size() != 1)
3434 continue;
3435
3436 if (!SO->second.front().Method->isPure())
3437 continue;
3438
Anders Carlssonffdb2d22010-06-03 01:00:02 +00003439 if (!SeenPureMethods.insert(SO->second.front().Method))
3440 continue;
3441
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003442 Diag(SO->second.front().Method->getLocation(),
3443 diag::note_pure_virtual_function)
Chandler Carruth45f11b72011-02-18 23:59:51 +00003444 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor7b2fc9d2010-03-23 23:47:56 +00003445 }
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003446 }
3447
3448 if (!PureVirtualClassDiagSet)
3449 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3450 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson4681ebd2009-03-22 20:18:17 +00003451}
3452
Anders Carlsson8211eff2009-03-24 01:19:16 +00003453namespace {
John McCall94c3b562010-08-18 09:41:07 +00003454struct AbstractUsageInfo {
3455 Sema &S;
3456 CXXRecordDecl *Record;
3457 CanQualType AbstractType;
3458 bool Invalid;
Mike Stump1eb44332009-09-09 15:08:12 +00003459
John McCall94c3b562010-08-18 09:41:07 +00003460 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3461 : S(S), Record(Record),
3462 AbstractType(S.Context.getCanonicalType(
3463 S.Context.getTypeDeclType(Record))),
3464 Invalid(false) {}
Anders Carlsson8211eff2009-03-24 01:19:16 +00003465
John McCall94c3b562010-08-18 09:41:07 +00003466 void DiagnoseAbstractType() {
3467 if (Invalid) return;
3468 S.DiagnoseAbstractType(Record);
3469 Invalid = true;
3470 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00003471
John McCall94c3b562010-08-18 09:41:07 +00003472 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3473};
3474
3475struct CheckAbstractUsage {
3476 AbstractUsageInfo &Info;
3477 const NamedDecl *Ctx;
3478
3479 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3480 : Info(Info), Ctx(Ctx) {}
3481
3482 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3483 switch (TL.getTypeLocClass()) {
3484#define ABSTRACT_TYPELOC(CLASS, PARENT)
3485#define TYPELOC(CLASS, PARENT) \
3486 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3487#include "clang/AST/TypeLocNodes.def"
Anders Carlsson8211eff2009-03-24 01:19:16 +00003488 }
John McCall94c3b562010-08-18 09:41:07 +00003489 }
Mike Stump1eb44332009-09-09 15:08:12 +00003490
John McCall94c3b562010-08-18 09:41:07 +00003491 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3492 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3493 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor70191862011-02-22 23:21:06 +00003494 if (!TL.getArg(I))
3495 continue;
3496
John McCall94c3b562010-08-18 09:41:07 +00003497 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3498 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003499 }
John McCall94c3b562010-08-18 09:41:07 +00003500 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003501
John McCall94c3b562010-08-18 09:41:07 +00003502 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3503 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3504 }
Mike Stump1eb44332009-09-09 15:08:12 +00003505
John McCall94c3b562010-08-18 09:41:07 +00003506 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3507 // Visit the type parameters from a permissive context.
3508 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3509 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3510 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3511 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3512 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3513 // TODO: other template argument types?
Anders Carlsson8211eff2009-03-24 01:19:16 +00003514 }
John McCall94c3b562010-08-18 09:41:07 +00003515 }
Mike Stump1eb44332009-09-09 15:08:12 +00003516
John McCall94c3b562010-08-18 09:41:07 +00003517 // Visit pointee types from a permissive context.
3518#define CheckPolymorphic(Type) \
3519 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3520 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3521 }
3522 CheckPolymorphic(PointerTypeLoc)
3523 CheckPolymorphic(ReferenceTypeLoc)
3524 CheckPolymorphic(MemberPointerTypeLoc)
3525 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedmanb001de72011-10-06 23:00:33 +00003526 CheckPolymorphic(AtomicTypeLoc)
Mike Stump1eb44332009-09-09 15:08:12 +00003527
John McCall94c3b562010-08-18 09:41:07 +00003528 /// Handle all the types we haven't given a more specific
3529 /// implementation for above.
3530 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3531 // Every other kind of type that we haven't called out already
3532 // that has an inner type is either (1) sugar or (2) contains that
3533 // inner type in some way as a subobject.
3534 if (TypeLoc Next = TL.getNextTypeLoc())
3535 return Visit(Next, Sel);
3536
3537 // If there's no inner type and we're in a permissive context,
3538 // don't diagnose.
3539 if (Sel == Sema::AbstractNone) return;
3540
3541 // Check whether the type matches the abstract type.
3542 QualType T = TL.getType();
3543 if (T->isArrayType()) {
3544 Sel = Sema::AbstractArrayType;
3545 T = Info.S.Context.getBaseElementType(T);
Anders Carlssone65a3c82009-03-24 17:23:42 +00003546 }
John McCall94c3b562010-08-18 09:41:07 +00003547 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3548 if (CT != Info.AbstractType) return;
3549
3550 // It matched; do some magic.
3551 if (Sel == Sema::AbstractArrayType) {
3552 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3553 << T << TL.getSourceRange();
3554 } else {
3555 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3556 << Sel << T << TL.getSourceRange();
3557 }
3558 Info.DiagnoseAbstractType();
3559 }
3560};
3561
3562void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3563 Sema::AbstractDiagSelID Sel) {
3564 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3565}
3566
3567}
3568
3569/// Check for invalid uses of an abstract type in a method declaration.
3570static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3571 CXXMethodDecl *MD) {
3572 // No need to do the check on definitions, which require that
3573 // the return/param types be complete.
Sean Hunt10620eb2011-05-06 20:44:56 +00003574 if (MD->doesThisDeclarationHaveABody())
John McCall94c3b562010-08-18 09:41:07 +00003575 return;
3576
3577 // For safety's sake, just ignore it if we don't have type source
3578 // information. This should never happen for non-implicit methods,
3579 // but...
3580 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3581 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3582}
3583
3584/// Check for invalid uses of an abstract type within a class definition.
3585static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3586 CXXRecordDecl *RD) {
3587 for (CXXRecordDecl::decl_iterator
3588 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3589 Decl *D = *I;
3590 if (D->isImplicit()) continue;
3591
3592 // Methods and method templates.
3593 if (isa<CXXMethodDecl>(D)) {
3594 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3595 } else if (isa<FunctionTemplateDecl>(D)) {
3596 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3597 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3598
3599 // Fields and static variables.
3600 } else if (isa<FieldDecl>(D)) {
3601 FieldDecl *FD = cast<FieldDecl>(D);
3602 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3603 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3604 } else if (isa<VarDecl>(D)) {
3605 VarDecl *VD = cast<VarDecl>(D);
3606 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3607 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3608
3609 // Nested classes and class templates.
3610 } else if (isa<CXXRecordDecl>(D)) {
3611 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3612 } else if (isa<ClassTemplateDecl>(D)) {
3613 CheckAbstractClassUsage(Info,
3614 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3615 }
3616 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00003617}
3618
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003619/// \brief Perform semantic checks on a class definition that has been
3620/// completing, introducing implicitly-declared members, checking for
3621/// abstract types, etc.
Douglas Gregor23c94db2010-07-02 17:43:08 +00003622void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor7a39dd02010-09-29 00:15:42 +00003623 if (!Record)
Douglas Gregor1ab537b2009-12-03 18:33:45 +00003624 return;
3625
John McCall94c3b562010-08-18 09:41:07 +00003626 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3627 AbstractUsageInfo Info(*this, Record);
3628 CheckAbstractClassUsage(Info, Record);
3629 }
Douglas Gregor325e5932010-04-15 00:00:53 +00003630
3631 // If this is not an aggregate type and has no user-declared constructor,
3632 // complain about any non-static data members of reference or const scalar
3633 // type, since they will never get initializers.
3634 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3635 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3636 bool Complained = false;
3637 for (RecordDecl::field_iterator F = Record->field_begin(),
3638 FEnd = Record->field_end();
3639 F != FEnd; ++F) {
Douglas Gregord61db332011-10-10 17:22:13 +00003640 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00003641 continue;
3642
Douglas Gregor325e5932010-04-15 00:00:53 +00003643 if (F->getType()->isReferenceType() ||
Benjamin Kramer1deea662010-04-16 17:43:15 +00003644 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor325e5932010-04-15 00:00:53 +00003645 if (!Complained) {
3646 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3647 << Record->getTagKind() << Record;
3648 Complained = true;
3649 }
3650
3651 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3652 << F->getType()->isReferenceType()
3653 << F->getDeclName();
3654 }
3655 }
3656 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003657
Anders Carlssona5c6c2a2011-01-25 18:08:22 +00003658 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00003659 DynamicClasses.push_back(Record);
Douglas Gregora6e937c2010-10-15 13:21:21 +00003660
3661 if (Record->getIdentifier()) {
3662 // C++ [class.mem]p13:
3663 // If T is the name of a class, then each of the following shall have a
3664 // name different from T:
3665 // - every member of every anonymous union that is a member of class T.
3666 //
3667 // C++ [class.mem]p14:
3668 // In addition, if class T has a user-declared constructor (12.1), every
3669 // non-static data member of class T shall have a name different from T.
3670 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet87c2e122010-11-21 06:08:52 +00003671 R.first != R.second; ++R.first) {
3672 NamedDecl *D = *R.first;
3673 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3674 isa<IndirectFieldDecl>(D)) {
3675 Diag(D->getLocation(), diag::err_member_name_of_class)
3676 << D->getDeclName();
Douglas Gregora6e937c2010-10-15 13:21:21 +00003677 break;
3678 }
Francois Pichet87c2e122010-11-21 06:08:52 +00003679 }
Douglas Gregora6e937c2010-10-15 13:21:21 +00003680 }
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003681
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003682 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregorf4b793c2011-02-19 19:14:36 +00003683 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003684 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis9641fc82011-01-31 17:10:25 +00003685 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidisdef4e2a2011-01-31 07:05:00 +00003686 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3687 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3688 }
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003689
3690 // See if a method overloads virtual methods in a base
3691 /// class without overriding any.
3692 if (!Record->isDependentType()) {
3693 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3694 MEnd = Record->method_end();
3695 M != MEnd; ++M) {
Argyrios Kyrtzidis0266aa32011-03-03 22:58:57 +00003696 if (!(*M)->isStatic())
3697 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00003698 }
3699 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00003700
Richard Smith9f569cc2011-10-01 02:31:28 +00003701 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3702 // function that is not a constructor declares that member function to be
3703 // const. [...] The class of which that function is a member shall be
3704 // a literal type.
3705 //
3706 // It's fine to diagnose constructors here too: such constructors cannot
3707 // produce a constant expression, so are ill-formed (no diagnostic required).
3708 //
3709 // If the class has virtual bases, any constexpr members will already have
3710 // been diagnosed by the checks performed on the member declaration, so
3711 // suppress this (less useful) diagnostic.
3712 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3713 !Record->isLiteral() && !Record->getNumVBases()) {
3714 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3715 MEnd = Record->method_end();
3716 M != MEnd; ++M) {
Eli Friedman9ec0ef32012-01-13 02:31:53 +00003717 if (M->isConstexpr() && M->isInstance()) {
Richard Smith9f569cc2011-10-01 02:31:28 +00003718 switch (Record->getTemplateSpecializationKind()) {
3719 case TSK_ImplicitInstantiation:
3720 case TSK_ExplicitInstantiationDeclaration:
3721 case TSK_ExplicitInstantiationDefinition:
3722 // If a template instantiates to a non-literal type, but its members
3723 // instantiate to constexpr functions, the template is technically
3724 // ill-formed, but we allow it for sanity. Such members are treated as
3725 // non-constexpr.
3726 (*M)->setConstexpr(false);
3727 continue;
3728
3729 case TSK_Undeclared:
3730 case TSK_ExplicitSpecialization:
3731 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3732 PDiag(diag::err_constexpr_method_non_literal));
3733 break;
3734 }
3735
3736 // Only produce one error per class.
3737 break;
3738 }
3739 }
3740 }
3741
Sebastian Redlf677ea32011-02-05 19:23:19 +00003742 // Declare inherited constructors. We do this eagerly here because:
3743 // - The standard requires an eager diagnostic for conflicting inherited
3744 // constructors from different classes.
3745 // - The lazy declaration of the other implicit constructors is so as to not
3746 // waste space and performance on classes that are not meant to be
3747 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3748 // have inherited constructors.
Sebastian Redlcaa35e42011-03-12 13:44:32 +00003749 DeclareInheritedConstructors(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003750
Sean Hunteb88ae52011-05-23 21:07:59 +00003751 if (!Record->isDependentType())
3752 CheckExplicitlyDefaultedMethods(Record);
Sean Hunt001cad92011-05-10 00:49:42 +00003753}
3754
3755void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00003756 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3757 ME = Record->method_end();
3758 MI != ME; ++MI) {
3759 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3760 switch (getSpecialMember(*MI)) {
3761 case CXXDefaultConstructor:
3762 CheckExplicitlyDefaultedDefaultConstructor(
3763 cast<CXXConstructorDecl>(*MI));
3764 break;
Sean Hunt001cad92011-05-10 00:49:42 +00003765
Sean Huntcb45a0f2011-05-12 22:46:25 +00003766 case CXXDestructor:
3767 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3768 break;
3769
3770 case CXXCopyConstructor:
Sean Hunt49634cf2011-05-13 06:10:58 +00003771 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3772 break;
3773
Sean Huntcb45a0f2011-05-12 22:46:25 +00003774 case CXXCopyAssignment:
Sean Hunt2b188082011-05-14 05:23:28 +00003775 CheckExplicitlyDefaultedCopyAssignment(*MI);
Sean Huntcb45a0f2011-05-12 22:46:25 +00003776 break;
3777
Sean Hunt82713172011-05-25 23:16:36 +00003778 case CXXMoveConstructor:
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003779 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Sean Hunt82713172011-05-25 23:16:36 +00003780 break;
3781
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00003782 case CXXMoveAssignment:
3783 CheckExplicitlyDefaultedMoveAssignment(*MI);
3784 break;
3785
3786 case CXXInvalid:
Sean Huntcb45a0f2011-05-12 22:46:25 +00003787 llvm_unreachable("non-special member explicitly defaulted!");
3788 }
Sean Hunt001cad92011-05-10 00:49:42 +00003789 }
3790 }
3791
Sean Hunt001cad92011-05-10 00:49:42 +00003792}
3793
3794void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3795 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3796
3797 // Whether this was the first-declared instance of the constructor.
3798 // This affects whether we implicitly add an exception spec (and, eventually,
3799 // constexpr). It is also ill-formed to explicitly default a constructor such
3800 // that it would be deleted. (C++0x [decl.fct.def.default])
3801 bool First = CD == CD->getCanonicalDecl();
3802
Sean Hunt49634cf2011-05-13 06:10:58 +00003803 bool HadError = false;
Sean Hunt001cad92011-05-10 00:49:42 +00003804 if (CD->getNumParams() != 0) {
3805 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3806 << CD->getSourceRange();
Sean Hunt49634cf2011-05-13 06:10:58 +00003807 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003808 }
3809
3810 ImplicitExceptionSpecification Spec
3811 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3812 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith7a614d82011-06-11 17:19:42 +00003813 if (EPI.ExceptionSpecType == EST_Delayed) {
3814 // Exception specification depends on some deferred part of the class. We'll
3815 // try again when the class's definition has been fully processed.
3816 return;
3817 }
Sean Hunt001cad92011-05-10 00:49:42 +00003818 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3819 *ExceptionType = Context.getFunctionType(
3820 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3821
Richard Smith61802452011-12-22 02:22:31 +00003822 // C++11 [dcl.fct.def.default]p2:
3823 // An explicitly-defaulted function may be declared constexpr only if it
3824 // would have been implicitly declared as constexpr,
3825 if (CD->isConstexpr()) {
3826 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3827 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3828 << CXXDefaultConstructor;
3829 HadError = true;
3830 }
3831 }
3832 // and may have an explicit exception-specification only if it is compatible
3833 // with the exception-specification on the implicit declaration.
Sean Hunt001cad92011-05-10 00:49:42 +00003834 if (CtorType->hasExceptionSpec()) {
3835 if (CheckEquivalentExceptionSpec(
Sean Huntcb45a0f2011-05-12 22:46:25 +00003836 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003837 << CXXDefaultConstructor,
Sean Hunt001cad92011-05-10 00:49:42 +00003838 PDiag(),
3839 ExceptionType, SourceLocation(),
3840 CtorType, CD->getLocation())) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003841 HadError = true;
Sean Hunt001cad92011-05-10 00:49:42 +00003842 }
Richard Smith61802452011-12-22 02:22:31 +00003843 }
3844
3845 // If a function is explicitly defaulted on its first declaration,
3846 if (First) {
3847 // -- it is implicitly considered to be constexpr if the implicit
3848 // definition would be,
3849 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3850
3851 // -- it is implicitly considered to have the same
3852 // exception-specification as if it had been implicitly declared
3853 //
3854 // FIXME: a compatible, but different, explicit exception specification
3855 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003856 EPI.ExtInfo = CtorType->getExtInfo();
Sean Hunt001cad92011-05-10 00:49:42 +00003857 }
Sean Huntca46d132011-05-12 03:51:48 +00003858
Sean Hunt49634cf2011-05-13 06:10:58 +00003859 if (HadError) {
3860 CD->setInvalidDecl();
3861 return;
3862 }
3863
Sean Hunte16da072011-10-10 06:18:57 +00003864 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003865 if (First) {
Sean Huntca46d132011-05-12 03:51:48 +00003866 CD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00003867 } else {
Sean Huntca46d132011-05-12 03:51:48 +00003868 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003869 << CXXDefaultConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003870 CD->setInvalidDecl();
3871 }
3872 }
3873}
3874
3875void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3876 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3877
3878 // Whether this was the first-declared instance of the constructor.
3879 bool First = CD == CD->getCanonicalDecl();
3880
3881 bool HadError = false;
3882 if (CD->getNumParams() != 1) {
3883 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3884 << CD->getSourceRange();
3885 HadError = true;
3886 }
3887
3888 ImplicitExceptionSpecification Spec(Context);
3889 bool Const;
3890 llvm::tie(Spec, Const) =
3891 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3892
3893 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3894 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3895 *ExceptionType = Context.getFunctionType(
3896 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3897
3898 // Check for parameter type matching.
3899 // This is a copy ctor so we know it's a cv-qualified reference to T.
3900 QualType ArgType = CtorType->getArgType(0);
3901 if (ArgType->getPointeeType().isVolatileQualified()) {
3902 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3903 HadError = true;
3904 }
3905 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3906 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3907 HadError = true;
3908 }
3909
Richard Smith61802452011-12-22 02:22:31 +00003910 // C++11 [dcl.fct.def.default]p2:
3911 // An explicitly-defaulted function may be declared constexpr only if it
3912 // would have been implicitly declared as constexpr,
3913 if (CD->isConstexpr()) {
3914 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3915 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3916 << CXXCopyConstructor;
3917 HadError = true;
3918 }
3919 }
3920 // and may have an explicit exception-specification only if it is compatible
3921 // with the exception-specification on the implicit declaration.
Sean Hunt49634cf2011-05-13 06:10:58 +00003922 if (CtorType->hasExceptionSpec()) {
3923 if (CheckEquivalentExceptionSpec(
3924 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00003925 << CXXCopyConstructor,
Sean Hunt49634cf2011-05-13 06:10:58 +00003926 PDiag(),
3927 ExceptionType, SourceLocation(),
3928 CtorType, CD->getLocation())) {
3929 HadError = true;
3930 }
Richard Smith61802452011-12-22 02:22:31 +00003931 }
3932
3933 // If a function is explicitly defaulted on its first declaration,
3934 if (First) {
3935 // -- it is implicitly considered to be constexpr if the implicit
3936 // definition would be,
3937 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3938
3939 // -- it is implicitly considered to have the same
3940 // exception-specification as if it had been implicitly declared, and
3941 //
3942 // FIXME: a compatible, but different, explicit exception specification
3943 // will be silently overridden. We should issue a warning if this happens.
Sean Hunt2b188082011-05-14 05:23:28 +00003944 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00003945
3946 // -- [...] it shall have the same parameter type as if it had been
3947 // implicitly declared.
Sean Hunt49634cf2011-05-13 06:10:58 +00003948 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3949 }
3950
3951 if (HadError) {
3952 CD->setInvalidDecl();
3953 return;
3954 }
3955
Sean Huntc32d6842011-10-11 04:55:36 +00003956 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00003957 if (First) {
3958 CD->setDeletedAsWritten();
3959 } else {
3960 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00003961 << CXXCopyConstructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00003962 CD->setInvalidDecl();
3963 }
Sean Huntca46d132011-05-12 03:51:48 +00003964 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00003965}
Sean Hunt001cad92011-05-10 00:49:42 +00003966
Sean Hunt2b188082011-05-14 05:23:28 +00003967void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3968 assert(MD->isExplicitlyDefaulted());
3969
3970 // Whether this was the first-declared instance of the operator
3971 bool First = MD == MD->getCanonicalDecl();
3972
3973 bool HadError = false;
3974 if (MD->getNumParams() != 1) {
3975 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3976 << MD->getSourceRange();
3977 HadError = true;
3978 }
3979
3980 QualType ReturnType =
3981 MD->getType()->getAs<FunctionType>()->getResultType();
3982 if (!ReturnType->isLValueReferenceType() ||
3983 !Context.hasSameType(
3984 Context.getCanonicalType(ReturnType->getPointeeType()),
3985 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3986 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3987 HadError = true;
3988 }
3989
3990 ImplicitExceptionSpecification Spec(Context);
3991 bool Const;
3992 llvm::tie(Spec, Const) =
3993 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3994
3995 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3996 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3997 *ExceptionType = Context.getFunctionType(
3998 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3999
Sean Hunt2b188082011-05-14 05:23:28 +00004000 QualType ArgType = OperType->getArgType(0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004001 if (!ArgType->isLValueReferenceType()) {
Sean Huntbe631222011-05-17 20:44:43 +00004002 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Sean Hunt2b188082011-05-14 05:23:28 +00004003 HadError = true;
Sean Huntbe631222011-05-17 20:44:43 +00004004 } else {
4005 if (ArgType->getPointeeType().isVolatileQualified()) {
4006 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4007 HadError = true;
4008 }
4009 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4010 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4011 HadError = true;
4012 }
Sean Hunt2b188082011-05-14 05:23:28 +00004013 }
Sean Huntbe631222011-05-17 20:44:43 +00004014
Sean Hunt2b188082011-05-14 05:23:28 +00004015 if (OperType->getTypeQuals()) {
4016 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4017 HadError = true;
4018 }
4019
4020 if (OperType->hasExceptionSpec()) {
4021 if (CheckEquivalentExceptionSpec(
4022 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004023 << CXXCopyAssignment,
Sean Hunt2b188082011-05-14 05:23:28 +00004024 PDiag(),
4025 ExceptionType, SourceLocation(),
4026 OperType, MD->getLocation())) {
4027 HadError = true;
4028 }
Richard Smith61802452011-12-22 02:22:31 +00004029 }
4030 if (First) {
Sean Hunt2b188082011-05-14 05:23:28 +00004031 // We set the declaration to have the computed exception spec here.
4032 // We duplicate the one parameter type.
4033 EPI.RefQualifier = OperType->getRefQualifier();
4034 EPI.ExtInfo = OperType->getExtInfo();
4035 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4036 }
4037
4038 if (HadError) {
4039 MD->setInvalidDecl();
4040 return;
4041 }
4042
4043 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4044 if (First) {
4045 MD->setDeletedAsWritten();
4046 } else {
4047 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004048 << CXXCopyAssignment;
Sean Hunt2b188082011-05-14 05:23:28 +00004049 MD->setInvalidDecl();
4050 }
4051 }
4052}
4053
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004054void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4055 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4056
4057 // Whether this was the first-declared instance of the constructor.
4058 bool First = CD == CD->getCanonicalDecl();
4059
4060 bool HadError = false;
4061 if (CD->getNumParams() != 1) {
4062 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4063 << CD->getSourceRange();
4064 HadError = true;
4065 }
4066
4067 ImplicitExceptionSpecification Spec(
4068 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4069
4070 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4071 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4072 *ExceptionType = Context.getFunctionType(
4073 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4074
4075 // Check for parameter type matching.
4076 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4077 QualType ArgType = CtorType->getArgType(0);
4078 if (ArgType->getPointeeType().isVolatileQualified()) {
4079 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4080 HadError = true;
4081 }
4082 if (ArgType->getPointeeType().isConstQualified()) {
4083 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4084 HadError = true;
4085 }
4086
Richard Smith61802452011-12-22 02:22:31 +00004087 // C++11 [dcl.fct.def.default]p2:
4088 // An explicitly-defaulted function may be declared constexpr only if it
4089 // would have been implicitly declared as constexpr,
4090 if (CD->isConstexpr()) {
4091 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4092 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4093 << CXXMoveConstructor;
4094 HadError = true;
4095 }
4096 }
4097 // and may have an explicit exception-specification only if it is compatible
4098 // with the exception-specification on the implicit declaration.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004099 if (CtorType->hasExceptionSpec()) {
4100 if (CheckEquivalentExceptionSpec(
4101 PDiag(diag::err_incorrect_defaulted_exception_spec)
4102 << CXXMoveConstructor,
4103 PDiag(),
4104 ExceptionType, SourceLocation(),
4105 CtorType, CD->getLocation())) {
4106 HadError = true;
4107 }
Richard Smith61802452011-12-22 02:22:31 +00004108 }
4109
4110 // If a function is explicitly defaulted on its first declaration,
4111 if (First) {
4112 // -- it is implicitly considered to be constexpr if the implicit
4113 // definition would be,
4114 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4115
4116 // -- it is implicitly considered to have the same
4117 // exception-specification as if it had been implicitly declared, and
4118 //
4119 // FIXME: a compatible, but different, explicit exception specification
4120 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004121 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smith61802452011-12-22 02:22:31 +00004122
4123 // -- [...] it shall have the same parameter type as if it had been
4124 // implicitly declared.
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004125 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4126 }
4127
4128 if (HadError) {
4129 CD->setInvalidDecl();
4130 return;
4131 }
4132
Sean Hunt769bb2d2011-10-11 06:43:29 +00004133 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004134 if (First) {
4135 CD->setDeletedAsWritten();
4136 } else {
4137 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4138 << CXXMoveConstructor;
4139 CD->setInvalidDecl();
4140 }
4141 }
4142}
4143
4144void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4145 assert(MD->isExplicitlyDefaulted());
4146
4147 // Whether this was the first-declared instance of the operator
4148 bool First = MD == MD->getCanonicalDecl();
4149
4150 bool HadError = false;
4151 if (MD->getNumParams() != 1) {
4152 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4153 << MD->getSourceRange();
4154 HadError = true;
4155 }
4156
4157 QualType ReturnType =
4158 MD->getType()->getAs<FunctionType>()->getResultType();
4159 if (!ReturnType->isLValueReferenceType() ||
4160 !Context.hasSameType(
4161 Context.getCanonicalType(ReturnType->getPointeeType()),
4162 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4163 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4164 HadError = true;
4165 }
4166
4167 ImplicitExceptionSpecification Spec(
4168 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4169
4170 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4171 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4172 *ExceptionType = Context.getFunctionType(
4173 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4174
4175 QualType ArgType = OperType->getArgType(0);
4176 if (!ArgType->isRValueReferenceType()) {
4177 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4178 HadError = true;
4179 } else {
4180 if (ArgType->getPointeeType().isVolatileQualified()) {
4181 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4182 HadError = true;
4183 }
4184 if (ArgType->getPointeeType().isConstQualified()) {
4185 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4186 HadError = true;
4187 }
4188 }
4189
4190 if (OperType->getTypeQuals()) {
4191 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4192 HadError = true;
4193 }
4194
4195 if (OperType->hasExceptionSpec()) {
4196 if (CheckEquivalentExceptionSpec(
4197 PDiag(diag::err_incorrect_defaulted_exception_spec)
4198 << CXXMoveAssignment,
4199 PDiag(),
4200 ExceptionType, SourceLocation(),
4201 OperType, MD->getLocation())) {
4202 HadError = true;
4203 }
Richard Smith61802452011-12-22 02:22:31 +00004204 }
4205 if (First) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004206 // We set the declaration to have the computed exception spec here.
4207 // We duplicate the one parameter type.
4208 EPI.RefQualifier = OperType->getRefQualifier();
4209 EPI.ExtInfo = OperType->getExtInfo();
4210 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4211 }
4212
4213 if (HadError) {
4214 MD->setInvalidDecl();
4215 return;
4216 }
4217
4218 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4219 if (First) {
4220 MD->setDeletedAsWritten();
4221 } else {
4222 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4223 << CXXMoveAssignment;
4224 MD->setInvalidDecl();
4225 }
4226 }
4227}
4228
Sean Huntcb45a0f2011-05-12 22:46:25 +00004229void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4230 assert(DD->isExplicitlyDefaulted());
4231
4232 // Whether this was the first-declared instance of the destructor.
4233 bool First = DD == DD->getCanonicalDecl();
4234
4235 ImplicitExceptionSpecification Spec
4236 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4237 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4238 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4239 *ExceptionType = Context.getFunctionType(
4240 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4241
4242 if (DtorType->hasExceptionSpec()) {
4243 if (CheckEquivalentExceptionSpec(
4244 PDiag(diag::err_incorrect_defaulted_exception_spec)
Sean Hunt82713172011-05-25 23:16:36 +00004245 << CXXDestructor,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004246 PDiag(),
4247 ExceptionType, SourceLocation(),
4248 DtorType, DD->getLocation())) {
4249 DD->setInvalidDecl();
4250 return;
4251 }
Richard Smith61802452011-12-22 02:22:31 +00004252 }
4253 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004254 // We set the declaration to have the computed exception spec here.
4255 // There are no parameters.
Sean Hunt2b188082011-05-14 05:23:28 +00004256 EPI.ExtInfo = DtorType->getExtInfo();
Sean Huntcb45a0f2011-05-12 22:46:25 +00004257 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4258 }
4259
4260 if (ShouldDeleteDestructor(DD)) {
Sean Hunt49634cf2011-05-13 06:10:58 +00004261 if (First) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004262 DD->setDeletedAsWritten();
Sean Hunt49634cf2011-05-13 06:10:58 +00004263 } else {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004264 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Sean Hunt82713172011-05-25 23:16:36 +00004265 << CXXDestructor;
Sean Hunt49634cf2011-05-13 06:10:58 +00004266 DD->setInvalidDecl();
4267 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004268 }
Sean Huntcb45a0f2011-05-12 22:46:25 +00004269}
4270
Sean Hunte16da072011-10-10 06:18:57 +00004271/// This function implements the following C++0x paragraphs:
4272/// - [class.ctor]/5
Sean Huntc32d6842011-10-11 04:55:36 +00004273/// - [class.copy]/11
Sean Hunte16da072011-10-10 06:18:57 +00004274bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4275 assert(!MD->isInvalidDecl());
4276 CXXRecordDecl *RD = MD->getParent();
Sean Huntcdee3fe2011-05-11 22:34:38 +00004277 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004278 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004279 return false;
4280
Sean Hunte16da072011-10-10 06:18:57 +00004281 bool IsUnion = RD->isUnion();
4282 bool IsConstructor = false;
4283 bool IsAssignment = false;
4284 bool IsMove = false;
4285
4286 bool ConstArg = false;
4287
4288 switch (CSM) {
4289 case CXXDefaultConstructor:
4290 IsConstructor = true;
4291 break;
Sean Huntc32d6842011-10-11 04:55:36 +00004292 case CXXCopyConstructor:
4293 IsConstructor = true;
4294 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4295 break;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004296 case CXXMoveConstructor:
4297 IsConstructor = true;
4298 IsMove = true;
4299 break;
Sean Hunte16da072011-10-10 06:18:57 +00004300 default:
4301 llvm_unreachable("function only currently implemented for default ctors");
4302 }
4303
4304 SourceLocation Loc = MD->getLocation();
Sean Hunt71a682f2011-05-18 03:41:58 +00004305
Sean Huntc32d6842011-10-11 04:55:36 +00004306 // Do access control from the special member function
Sean Hunte16da072011-10-10 06:18:57 +00004307 ContextRAII MethodContext(*this, MD);
Sean Huntcdee3fe2011-05-11 22:34:38 +00004308
Sean Huntcdee3fe2011-05-11 22:34:38 +00004309 bool AllConst = true;
4310
Sean Huntcdee3fe2011-05-11 22:34:38 +00004311 // We do this because we should never actually use an anonymous
4312 // union's constructor.
Sean Hunte16da072011-10-10 06:18:57 +00004313 if (IsUnion && RD->isAnonymousStructOrUnion())
Sean Huntcdee3fe2011-05-11 22:34:38 +00004314 return false;
4315
4316 // FIXME: We should put some diagnostic logic right into this function.
4317
Sean Huntcdee3fe2011-05-11 22:34:38 +00004318 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4319 BE = RD->bases_end();
4320 BI != BE; ++BI) {
Sean Huntcb45a0f2011-05-12 22:46:25 +00004321 // We'll handle this one later
4322 if (BI->isVirtual())
4323 continue;
4324
Sean Huntcdee3fe2011-05-11 22:34:38 +00004325 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4326 assert(BaseDecl && "base isn't a CXXRecordDecl");
4327
Sean Hunte16da072011-10-10 06:18:57 +00004328 // Unless we have an assignment operator, the base's destructor must
4329 // be accessible and not deleted.
4330 if (!IsAssignment) {
4331 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4332 if (BaseDtor->isDeleted())
4333 return true;
4334 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4335 AR_accessible)
4336 return true;
4337 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004338
Sean Hunte16da072011-10-10 06:18:57 +00004339 // Finding the corresponding member in the base should lead to a
Sean Huntc32d6842011-10-11 04:55:36 +00004340 // unique, accessible, non-deleted function. If we are doing
4341 // a destructor, we have already checked this case.
Sean Hunte16da072011-10-10 06:18:57 +00004342 if (CSM != CXXDestructor) {
4343 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004344 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004345 false);
4346 if (!SMOR->hasSuccess())
4347 return true;
4348 CXXMethodDecl *BaseMember = SMOR->getMethod();
4349 if (IsConstructor) {
4350 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4351 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4352 PDiag()) != AR_accessible)
4353 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004354
4355 // For a move operation, the corresponding operation must actually
4356 // be a move operation (and not a copy selected by overload
4357 // resolution) unless we are working on a trivially copyable class.
4358 if (IsMove && !BaseCtor->isMoveConstructor() &&
4359 !BaseDecl->isTriviallyCopyable())
4360 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004361 }
4362 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004363 }
4364
4365 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4366 BE = RD->vbases_end();
4367 BI != BE; ++BI) {
4368 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4369 assert(BaseDecl && "base isn't a CXXRecordDecl");
4370
Sean Hunte16da072011-10-10 06:18:57 +00004371 // Unless we have an assignment operator, the base's destructor must
4372 // be accessible and not deleted.
4373 if (!IsAssignment) {
4374 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4375 if (BaseDtor->isDeleted())
4376 return true;
4377 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4378 AR_accessible)
4379 return true;
4380 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004381
Sean Hunte16da072011-10-10 06:18:57 +00004382 // Finding the corresponding member in the base should lead to a
4383 // unique, accessible, non-deleted function.
4384 if (CSM != CXXDestructor) {
4385 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004386 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004387 false);
4388 if (!SMOR->hasSuccess())
4389 return true;
4390 CXXMethodDecl *BaseMember = SMOR->getMethod();
4391 if (IsConstructor) {
4392 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4393 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4394 PDiag()) != AR_accessible)
4395 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004396
4397 // For a move operation, the corresponding operation must actually
4398 // be a move operation (and not a copy selected by overload
4399 // resolution) unless we are working on a trivially copyable class.
4400 if (IsMove && !BaseCtor->isMoveConstructor() &&
4401 !BaseDecl->isTriviallyCopyable())
4402 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004403 }
4404 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004405 }
4406
4407 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4408 FE = RD->field_end();
4409 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004410 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith7a614d82011-06-11 17:19:42 +00004411 continue;
4412
Sean Huntcdee3fe2011-05-11 22:34:38 +00004413 QualType FieldType = Context.getBaseElementType(FI->getType());
4414 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith7a614d82011-06-11 17:19:42 +00004415
Sean Hunte16da072011-10-10 06:18:57 +00004416 // For a default constructor, all references must be initialized in-class
4417 // and, if a union, it must have a non-const member.
4418 if (CSM == CXXDefaultConstructor) {
4419 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4420 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004421
Sean Hunte16da072011-10-10 06:18:57 +00004422 if (IsUnion && !FieldType.isConstQualified())
4423 AllConst = false;
Sean Huntc32d6842011-10-11 04:55:36 +00004424 // For a copy constructor, data members must not be of rvalue reference
4425 // type.
4426 } else if (CSM == CXXCopyConstructor) {
4427 if (FieldType->isRValueReferenceType())
4428 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004429 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004430
4431 if (FieldRecord) {
Sean Hunte16da072011-10-10 06:18:57 +00004432 // For a default constructor, a const member must have a user-provided
4433 // default constructor or else be explicitly initialized.
4434 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith7a614d82011-06-11 17:19:42 +00004435 !FI->hasInClassInitializer() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004436 !FieldRecord->hasUserProvidedDefaultConstructor())
4437 return true;
4438
Sean Huntc32d6842011-10-11 04:55:36 +00004439 // Some additional restrictions exist on the variant members.
4440 if (!IsUnion && FieldRecord->isUnion() &&
Sean Huntcdee3fe2011-05-11 22:34:38 +00004441 FieldRecord->isAnonymousStructOrUnion()) {
4442 // We're okay to reuse AllConst here since we only care about the
4443 // value otherwise if we're in a union.
4444 AllConst = true;
4445
4446 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4447 UE = FieldRecord->field_end();
4448 UI != UE; ++UI) {
4449 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4450 CXXRecordDecl *UnionFieldRecord =
4451 UnionFieldType->getAsCXXRecordDecl();
4452
4453 if (!UnionFieldType.isConstQualified())
4454 AllConst = false;
4455
Sean Huntc32d6842011-10-11 04:55:36 +00004456 if (UnionFieldRecord) {
4457 // FIXME: Checking for accessibility and validity of this
4458 // destructor is technically going beyond the
4459 // standard, but this is believed to be a defect.
4460 if (!IsAssignment) {
4461 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4462 if (FieldDtor->isDeleted())
4463 return true;
4464 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4465 AR_accessible)
4466 return true;
4467 if (!FieldDtor->isTrivial())
4468 return true;
4469 }
4470
4471 if (CSM != CXXDestructor) {
4472 SpecialMemberOverloadResult *SMOR =
4473 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Sean Hunt769bb2d2011-10-11 06:43:29 +00004474 false, false, false);
Sean Huntc32d6842011-10-11 04:55:36 +00004475 // FIXME: Checking for accessibility and validity of this
4476 // corresponding member is technically going beyond the
4477 // standard, but this is believed to be a defect.
4478 if (!SMOR->hasSuccess())
4479 return true;
4480
4481 CXXMethodDecl *FieldMember = SMOR->getMethod();
4482 // A member of a union must have a trivial corresponding
4483 // constructor.
4484 if (!FieldMember->isTrivial())
4485 return true;
4486
4487 if (IsConstructor) {
4488 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4489 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4490 PDiag()) != AR_accessible)
4491 return true;
4492 }
4493 }
4494 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004495 }
Sean Hunt2be7e902011-05-12 22:46:29 +00004496
Sean Huntc32d6842011-10-11 04:55:36 +00004497 // At least one member in each anonymous union must be non-const
4498 if (CSM == CXXDefaultConstructor && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004499 return true;
4500
4501 // Don't try to initialize the anonymous union
Sean Hunta6bff2c2011-05-11 22:50:12 +00004502 // This is technically non-conformant, but sanity demands it.
Sean Huntcdee3fe2011-05-11 22:34:38 +00004503 continue;
4504 }
Sean Huntb320e0c2011-06-10 03:50:41 +00004505
Sean Huntc32d6842011-10-11 04:55:36 +00004506 // Unless we're doing assignment, the field's destructor must be
4507 // accessible and not deleted.
4508 if (!IsAssignment) {
4509 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4510 if (FieldDtor->isDeleted())
4511 return true;
4512 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4513 AR_accessible)
4514 return true;
4515 }
4516
Sean Hunte16da072011-10-10 06:18:57 +00004517 // Check that the corresponding member of the field is accessible,
4518 // unique, and non-deleted. We don't do this if it has an explicit
4519 // initialization when default-constructing.
4520 if (CSM != CXXDestructor &&
4521 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4522 SpecialMemberOverloadResult *SMOR =
Sean Hunt769bb2d2011-10-11 06:43:29 +00004523 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Sean Hunte16da072011-10-10 06:18:57 +00004524 false);
4525 if (!SMOR->hasSuccess())
Richard Smith7a614d82011-06-11 17:19:42 +00004526 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004527
4528 CXXMethodDecl *FieldMember = SMOR->getMethod();
4529 if (IsConstructor) {
4530 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4531 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4532 PDiag()) != AR_accessible)
4533 return true;
Sean Hunt769bb2d2011-10-11 06:43:29 +00004534
4535 // For a move operation, the corresponding operation must actually
4536 // be a move operation (and not a copy selected by overload
4537 // resolution) unless we are working on a trivially copyable class.
4538 if (IsMove && !FieldCtor->isMoveConstructor() &&
4539 !FieldRecord->isTriviallyCopyable())
4540 return true;
Sean Hunte16da072011-10-10 06:18:57 +00004541 }
4542
4543 // We need the corresponding member of a union to be trivial so that
4544 // we can safely copy them all simultaneously.
4545 // FIXME: Note that performing the check here (where we rely on the lack
4546 // of an in-class initializer) is technically ill-formed. However, this
4547 // seems most obviously to be a bug in the standard.
4548 if (IsUnion && !FieldMember->isTrivial())
Richard Smith7a614d82011-06-11 17:19:42 +00004549 return true;
4550 }
Sean Hunte16da072011-10-10 06:18:57 +00004551 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4552 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4553 // We can't initialize a const member of non-class type to any value.
Sean Hunte3406822011-05-20 21:43:47 +00004554 return true;
Sean Huntcdee3fe2011-05-11 22:34:38 +00004555 }
Sean Huntcdee3fe2011-05-11 22:34:38 +00004556 }
4557
Sean Hunte16da072011-10-10 06:18:57 +00004558 // We can't have all const members in a union when default-constructing,
4559 // or else they're all nonsensical garbage values that can't be changed.
4560 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Sean Huntcdee3fe2011-05-11 22:34:38 +00004561 return true;
4562
4563 return false;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004564}
4565
Sean Hunt7f410192011-05-14 05:23:24 +00004566bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4567 CXXRecordDecl *RD = MD->getParent();
4568 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004569 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Hunt7f410192011-05-14 05:23:24 +00004570 return false;
4571
Sean Hunt71a682f2011-05-18 03:41:58 +00004572 SourceLocation Loc = MD->getLocation();
4573
Sean Hunt7f410192011-05-14 05:23:24 +00004574 // Do access control from the constructor
4575 ContextRAII MethodContext(*this, MD);
4576
4577 bool Union = RD->isUnion();
4578
Sean Hunt661c67a2011-06-21 23:42:56 +00004579 unsigned ArgQuals =
4580 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4581 Qualifiers::Const : 0;
Sean Hunt7f410192011-05-14 05:23:24 +00004582
4583 // We do this because we should never actually use an anonymous
4584 // union's constructor.
4585 if (Union && RD->isAnonymousStructOrUnion())
4586 return false;
4587
Sean Hunt7f410192011-05-14 05:23:24 +00004588 // FIXME: We should put some diagnostic logic right into this function.
4589
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004590 // C++0x [class.copy]/20
Sean Hunt7f410192011-05-14 05:23:24 +00004591 // A defaulted [copy] assignment operator for class X is defined as deleted
4592 // if X has:
4593
4594 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4595 BE = RD->bases_end();
4596 BI != BE; ++BI) {
4597 // We'll handle this one later
4598 if (BI->isVirtual())
4599 continue;
4600
4601 QualType BaseType = BI->getType();
4602 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4603 assert(BaseDecl && "base isn't a CXXRecordDecl");
4604
4605 // -- a [direct base class] B that cannot be [copied] because overload
4606 // resolution, as applied to B's [copy] assignment operator, results in
Sean Hunt2b188082011-05-14 05:23:28 +00004607 // an ambiguity or a function that is deleted or inaccessible from the
Sean Hunt7f410192011-05-14 05:23:24 +00004608 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004609 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4610 0);
4611 if (!CopyOper || CopyOper->isDeleted())
4612 return true;
4613 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004614 return true;
4615 }
4616
4617 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4618 BE = RD->vbases_end();
4619 BI != BE; ++BI) {
4620 QualType BaseType = BI->getType();
4621 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4622 assert(BaseDecl && "base isn't a CXXRecordDecl");
4623
Sean Hunt7f410192011-05-14 05:23:24 +00004624 // -- a [virtual base class] B that cannot be [copied] because overload
Sean Hunt2b188082011-05-14 05:23:28 +00004625 // resolution, as applied to B's [copy] assignment operator, results in
4626 // an ambiguity or a function that is deleted or inaccessible from the
4627 // assignment operator
Sean Hunt661c67a2011-06-21 23:42:56 +00004628 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4629 0);
4630 if (!CopyOper || CopyOper->isDeleted())
4631 return true;
4632 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sean Hunt7f410192011-05-14 05:23:24 +00004633 return true;
Sean Hunt7f410192011-05-14 05:23:24 +00004634 }
4635
4636 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4637 FE = RD->field_end();
4638 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004639 if (FI->isUnnamedBitfield())
4640 continue;
4641
Sean Hunt7f410192011-05-14 05:23:24 +00004642 QualType FieldType = Context.getBaseElementType(FI->getType());
4643
4644 // -- a non-static data member of reference type
4645 if (FieldType->isReferenceType())
4646 return true;
4647
4648 // -- a non-static data member of const non-class type (or array thereof)
4649 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4650 return true;
4651
4652 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4653
4654 if (FieldRecord) {
4655 // This is an anonymous union
4656 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4657 // Anonymous unions inside unions do not variant members create
4658 if (!Union) {
4659 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4660 UE = FieldRecord->field_end();
4661 UI != UE; ++UI) {
4662 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4663 CXXRecordDecl *UnionFieldRecord =
4664 UnionFieldType->getAsCXXRecordDecl();
4665
4666 // -- a variant member with a non-trivial [copy] assignment operator
4667 // and X is a union-like class
4668 if (UnionFieldRecord &&
4669 !UnionFieldRecord->hasTrivialCopyAssignment())
4670 return true;
4671 }
4672 }
4673
4674 // Don't try to initalize an anonymous union
4675 continue;
4676 // -- a variant member with a non-trivial [copy] assignment operator
4677 // and X is a union-like class
4678 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4679 return true;
4680 }
Sean Hunt7f410192011-05-14 05:23:24 +00004681
Sean Hunt661c67a2011-06-21 23:42:56 +00004682 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4683 false, 0);
4684 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004685 return true;
Sean Hunt661c67a2011-06-21 23:42:56 +00004686 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004687 return true;
4688 }
4689 }
4690
4691 return false;
4692}
4693
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004694bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4695 CXXRecordDecl *RD = MD->getParent();
4696 assert(!RD->isDependentType() && "do deletion after instantiation");
4697 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4698 return false;
4699
4700 SourceLocation Loc = MD->getLocation();
4701
4702 // Do access control from the constructor
4703 ContextRAII MethodContext(*this, MD);
4704
4705 bool Union = RD->isUnion();
4706
4707 // We do this because we should never actually use an anonymous
4708 // union's constructor.
4709 if (Union && RD->isAnonymousStructOrUnion())
4710 return false;
4711
4712 // C++0x [class.copy]/20
4713 // A defaulted [move] assignment operator for class X is defined as deleted
4714 // if X has:
4715
4716 // -- for the move constructor, [...] any direct or indirect virtual base
4717 // class.
4718 if (RD->getNumVBases() != 0)
4719 return true;
4720
4721 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4722 BE = RD->bases_end();
4723 BI != BE; ++BI) {
4724
4725 QualType BaseType = BI->getType();
4726 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4727 assert(BaseDecl && "base isn't a CXXRecordDecl");
4728
4729 // -- a [direct base class] B that cannot be [moved] because overload
4730 // resolution, as applied to B's [move] assignment operator, results in
4731 // an ambiguity or a function that is deleted or inaccessible from the
4732 // assignment operator
4733 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4734 if (!MoveOper || MoveOper->isDeleted())
4735 return true;
4736 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4737 return true;
4738
4739 // -- for the move assignment operator, a [direct base class] with a type
4740 // that does not have a move assignment operator and is not trivially
4741 // copyable.
4742 if (!MoveOper->isMoveAssignmentOperator() &&
4743 !BaseDecl->isTriviallyCopyable())
4744 return true;
4745 }
4746
4747 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4748 FE = RD->field_end();
4749 FI != FE; ++FI) {
Douglas Gregord61db332011-10-10 17:22:13 +00004750 if (FI->isUnnamedBitfield())
4751 continue;
4752
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00004753 QualType FieldType = Context.getBaseElementType(FI->getType());
4754
4755 // -- a non-static data member of reference type
4756 if (FieldType->isReferenceType())
4757 return true;
4758
4759 // -- a non-static data member of const non-class type (or array thereof)
4760 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4761 return true;
4762
4763 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4764
4765 if (FieldRecord) {
4766 // This is an anonymous union
4767 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4768 // Anonymous unions inside unions do not variant members create
4769 if (!Union) {
4770 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4771 UE = FieldRecord->field_end();
4772 UI != UE; ++UI) {
4773 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4774 CXXRecordDecl *UnionFieldRecord =
4775 UnionFieldType->getAsCXXRecordDecl();
4776
4777 // -- a variant member with a non-trivial [move] assignment operator
4778 // and X is a union-like class
4779 if (UnionFieldRecord &&
4780 !UnionFieldRecord->hasTrivialMoveAssignment())
4781 return true;
4782 }
4783 }
4784
4785 // Don't try to initalize an anonymous union
4786 continue;
4787 // -- a variant member with a non-trivial [move] assignment operator
4788 // and X is a union-like class
4789 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4790 return true;
4791 }
4792
4793 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4794 if (!MoveOper || MoveOper->isDeleted())
4795 return true;
4796 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4797 return true;
4798
4799 // -- for the move assignment operator, a [non-static data member] with a
4800 // type that does not have a move assignment operator and is not
4801 // trivially copyable.
4802 if (!MoveOper->isMoveAssignmentOperator() &&
4803 !FieldRecord->isTriviallyCopyable())
4804 return true;
Sean Hunt2b188082011-05-14 05:23:28 +00004805 }
Sean Hunt7f410192011-05-14 05:23:24 +00004806 }
4807
4808 return false;
4809}
4810
Sean Huntcb45a0f2011-05-12 22:46:25 +00004811bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4812 CXXRecordDecl *RD = DD->getParent();
4813 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaracdb80762011-07-11 08:52:40 +00004814 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Sean Huntcb45a0f2011-05-12 22:46:25 +00004815 return false;
4816
Sean Hunt71a682f2011-05-18 03:41:58 +00004817 SourceLocation Loc = DD->getLocation();
4818
Sean Huntcb45a0f2011-05-12 22:46:25 +00004819 // Do access control from the destructor
4820 ContextRAII CtorContext(*this, DD);
4821
4822 bool Union = RD->isUnion();
4823
Sean Hunt49634cf2011-05-13 06:10:58 +00004824 // We do this because we should never actually use an anonymous
4825 // union's destructor.
4826 if (Union && RD->isAnonymousStructOrUnion())
4827 return false;
4828
Sean Huntcb45a0f2011-05-12 22:46:25 +00004829 // C++0x [class.dtor]p5
4830 // A defaulted destructor for a class X is defined as deleted if:
4831 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4832 BE = RD->bases_end();
4833 BI != BE; ++BI) {
4834 // We'll handle this one later
4835 if (BI->isVirtual())
4836 continue;
4837
4838 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4839 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4840 assert(BaseDtor && "base has no destructor");
4841
4842 // -- any direct or virtual base class has a deleted destructor or
4843 // a destructor that is inaccessible from the defaulted destructor
4844 if (BaseDtor->isDeleted())
4845 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004846 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004847 AR_accessible)
4848 return true;
4849 }
4850
4851 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4852 BE = RD->vbases_end();
4853 BI != BE; ++BI) {
4854 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4855 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4856 assert(BaseDtor && "base has no destructor");
4857
4858 // -- any direct or virtual base class has a deleted destructor or
4859 // a destructor that is inaccessible from the defaulted destructor
4860 if (BaseDtor->isDeleted())
4861 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004862 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004863 AR_accessible)
4864 return true;
4865 }
4866
4867 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4868 FE = RD->field_end();
4869 FI != FE; ++FI) {
4870 QualType FieldType = Context.getBaseElementType(FI->getType());
4871 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4872 if (FieldRecord) {
4873 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4874 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4875 UE = FieldRecord->field_end();
4876 UI != UE; ++UI) {
4877 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4878 CXXRecordDecl *UnionFieldRecord =
4879 UnionFieldType->getAsCXXRecordDecl();
4880
4881 // -- X is a union-like class that has a variant member with a non-
4882 // trivial destructor.
4883 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4884 return true;
4885 }
4886 // Technically we are supposed to do this next check unconditionally.
4887 // But that makes absolutely no sense.
4888 } else {
4889 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4890
4891 // -- any of the non-static data members has class type M (or array
4892 // thereof) and M has a deleted destructor or a destructor that is
4893 // inaccessible from the defaulted destructor
4894 if (FieldDtor->isDeleted())
4895 return true;
Sean Hunt71a682f2011-05-18 03:41:58 +00004896 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Sean Huntcb45a0f2011-05-12 22:46:25 +00004897 AR_accessible)
4898 return true;
4899
4900 // -- X is a union-like class that has a variant member with a non-
4901 // trivial destructor.
4902 if (Union && !FieldDtor->isTrivial())
4903 return true;
4904 }
4905 }
4906 }
4907
4908 if (DD->isVirtual()) {
4909 FunctionDecl *OperatorDelete = 0;
4910 DeclarationName Name =
4911 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Sean Hunt71a682f2011-05-18 03:41:58 +00004912 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Sean Huntcb45a0f2011-05-12 22:46:25 +00004913 false))
4914 return true;
4915 }
4916
4917
4918 return false;
4919}
4920
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004921/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004922namespace {
4923 struct FindHiddenVirtualMethodData {
4924 Sema *S;
4925 CXXMethodDecl *Method;
4926 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004927 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramerc54061a2011-03-04 13:12:48 +00004928 };
4929}
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004930
4931/// \brief Member lookup function that determines whether a given C++
4932/// method overloads virtual methods in a base class without overriding any,
4933/// to be used with CXXRecordDecl::lookupInBases().
4934static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4935 CXXBasePath &Path,
4936 void *UserData) {
4937 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4938
4939 FindHiddenVirtualMethodData &Data
4940 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4941
4942 DeclarationName Name = Data.Method->getDeclName();
4943 assert(Name.getNameKind() == DeclarationName::Identifier);
4944
4945 bool foundSameNameMethod = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004946 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004947 for (Path.Decls = BaseRecord->lookup(Name);
4948 Path.Decls.first != Path.Decls.second;
4949 ++Path.Decls.first) {
4950 NamedDecl *D = *Path.Decls.first;
4951 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004952 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004953 foundSameNameMethod = true;
4954 // Interested only in hidden virtual methods.
4955 if (!MD->isVirtual())
4956 continue;
4957 // If the method we are checking overrides a method from its base
4958 // don't warn about the other overloaded methods.
4959 if (!Data.S->IsOverload(Data.Method, MD, false))
4960 return true;
4961 // Collect the overload only if its hidden.
4962 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4963 overloadedMethods.push_back(MD);
4964 }
4965 }
4966
4967 if (foundSameNameMethod)
4968 Data.OverloadedMethods.append(overloadedMethods.begin(),
4969 overloadedMethods.end());
4970 return foundSameNameMethod;
4971}
4972
4973/// \brief See if a method overloads virtual methods in a base class without
4974/// overriding any.
4975void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4976 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikied6471f72011-09-25 23:23:43 +00004977 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004978 return;
4979 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4980 return;
4981
4982 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4983 /*bool RecordPaths=*/false,
4984 /*bool DetectVirtual=*/false);
4985 FindHiddenVirtualMethodData Data;
4986 Data.Method = MD;
4987 Data.S = this;
4988
4989 // Keep the base methods that were overriden or introduced in the subclass
4990 // by 'using' in a set. A base method not in this set is hidden.
4991 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4992 res.first != res.second; ++res.first) {
4993 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4994 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4995 E = MD->end_overridden_methods();
4996 I != E; ++I)
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00004997 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00004998 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4999 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis74b47f92011-02-10 18:13:41 +00005000 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis799ef662011-02-03 18:01:15 +00005001 }
5002
5003 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5004 !Data.OverloadedMethods.empty()) {
5005 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5006 << MD << (Data.OverloadedMethods.size() > 1);
5007
5008 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5009 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5010 Diag(overloadedMD->getLocation(),
5011 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5012 }
5013 }
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005014}
5015
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005016void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCalld226f652010-08-21 09:40:31 +00005017 Decl *TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005018 SourceLocation LBrac,
Douglas Gregor0b4c9b52010-03-29 14:42:08 +00005019 SourceLocation RBrac,
5020 AttributeList *AttrList) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005021 if (!TagDecl)
5022 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005023
Douglas Gregor42af25f2009-05-11 19:58:34 +00005024 AdjustDeclIfTemplate(TagDecl);
Douglas Gregor1ab537b2009-12-03 18:33:45 +00005025
David Blaikie77b6de02011-09-22 02:58:26 +00005026 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCalld226f652010-08-21 09:40:31 +00005027 // strict aliasing violation!
5028 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie77b6de02011-09-22 02:58:26 +00005029 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor2943aed2009-03-03 04:44:36 +00005030
Douglas Gregor23c94db2010-07-02 17:43:08 +00005031 CheckCompletedCXXClass(
John McCalld226f652010-08-21 09:40:31 +00005032 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00005033}
5034
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005035/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5036/// special functions, such as the default constructor, copy
5037/// constructor, or destructor, to the given C++ class (C++
5038/// [special]p1). This routine can only be executed just before the
5039/// definition of the class is complete.
Douglas Gregor23c94db2010-07-02 17:43:08 +00005040void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor32df23e2010-07-01 22:02:46 +00005041 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor18274032010-07-03 00:47:00 +00005042 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005043
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00005044 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregor22584312010-07-02 23:41:54 +00005045 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005046
Richard Smithb701d3d2011-12-24 21:56:24 +00005047 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5048 ++ASTContext::NumImplicitMoveConstructors;
5049
Douglas Gregora376d102010-07-02 21:50:04 +00005050 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5051 ++ASTContext::NumImplicitCopyAssignmentOperators;
5052
5053 // If we have a dynamic class, then the copy assignment operator may be
5054 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5055 // it shows up in the right place in the vtable and that we diagnose
5056 // problems with the implicit exception specification.
5057 if (ClassDecl->isDynamicClass())
5058 DeclareImplicitCopyAssignment(ClassDecl);
5059 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00005060
Richard Smithb701d3d2011-12-24 21:56:24 +00005061 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5062 ++ASTContext::NumImplicitMoveAssignmentOperators;
5063
5064 // Likewise for the move assignment operator.
5065 if (ClassDecl->isDynamicClass())
5066 DeclareImplicitMoveAssignment(ClassDecl);
5067 }
5068
Douglas Gregor4923aa22010-07-02 20:37:36 +00005069 if (!ClassDecl->hasUserDeclaredDestructor()) {
5070 ++ASTContext::NumImplicitDestructors;
5071
5072 // If we have a dynamic class, then the destructor may be virtual, so we
5073 // have to declare the destructor immediately. This ensures that, e.g., it
5074 // shows up in the right place in the vtable and that we diagnose problems
5075 // with the implicit exception specification.
5076 if (ClassDecl->isDynamicClass())
5077 DeclareImplicitDestructor(ClassDecl);
5078 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00005079}
5080
Francois Pichet8387e2a2011-04-22 22:18:13 +00005081void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5082 if (!D)
5083 return;
5084
5085 int NumParamList = D->getNumTemplateParameterLists();
5086 for (int i = 0; i < NumParamList; i++) {
5087 TemplateParameterList* Params = D->getTemplateParameterList(i);
5088 for (TemplateParameterList::iterator Param = Params->begin(),
5089 ParamEnd = Params->end();
5090 Param != ParamEnd; ++Param) {
5091 NamedDecl *Named = cast<NamedDecl>(*Param);
5092 if (Named->getDeclName()) {
5093 S->AddDecl(Named);
5094 IdResolver.AddDecl(Named);
5095 }
5096 }
5097 }
5098}
5099
John McCalld226f652010-08-21 09:40:31 +00005100void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregor1cdcc572009-09-10 00:12:48 +00005101 if (!D)
5102 return;
5103
5104 TemplateParameterList *Params = 0;
5105 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5106 Params = Template->getTemplateParameters();
5107 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5108 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5109 Params = PartialSpec->getTemplateParameters();
5110 else
Douglas Gregor6569d682009-05-27 23:11:45 +00005111 return;
5112
Douglas Gregor6569d682009-05-27 23:11:45 +00005113 for (TemplateParameterList::iterator Param = Params->begin(),
5114 ParamEnd = Params->end();
5115 Param != ParamEnd; ++Param) {
5116 NamedDecl *Named = cast<NamedDecl>(*Param);
5117 if (Named->getDeclName()) {
John McCalld226f652010-08-21 09:40:31 +00005118 S->AddDecl(Named);
Douglas Gregor6569d682009-05-27 23:11:45 +00005119 IdResolver.AddDecl(Named);
5120 }
5121 }
5122}
5123
John McCalld226f652010-08-21 09:40:31 +00005124void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005125 if (!RecordD) return;
5126 AdjustDeclIfTemplate(RecordD);
John McCalld226f652010-08-21 09:40:31 +00005127 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall7a1dc562009-12-19 10:49:29 +00005128 PushDeclContext(S, Record);
5129}
5130
John McCalld226f652010-08-21 09:40:31 +00005131void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall7a1dc562009-12-19 10:49:29 +00005132 if (!RecordD) return;
5133 PopDeclContext();
5134}
5135
Douglas Gregor72b505b2008-12-16 21:30:33 +00005136/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5137/// parsing a top-level (non-nested) C++ class, and we are now
5138/// parsing those parts of the given Method declaration that could
5139/// not be parsed earlier (C++ [class.mem]p2), such as default
5140/// arguments. This action should enter the scope of the given
5141/// Method declaration as if we had just parsed the qualified method
5142/// name. However, it should not bring the parameters into scope;
5143/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCalld226f652010-08-21 09:40:31 +00005144void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005145}
5146
5147/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5148/// C++ method declaration. We're (re-)introducing the given
5149/// function parameter into scope for use in parsing later parts of
5150/// the method declaration. For example, we could see an
5151/// ActOnParamDefaultArgument event for this parameter.
John McCalld226f652010-08-21 09:40:31 +00005152void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005153 if (!ParamD)
5154 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005155
John McCalld226f652010-08-21 09:40:31 +00005156 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor61366e92008-12-24 00:01:03 +00005157
5158 // If this parameter has an unparsed default argument, clear it out
5159 // to make way for the parsed default argument.
5160 if (Param->hasUnparsedDefaultArg())
5161 Param->setDefaultArg(0);
5162
John McCalld226f652010-08-21 09:40:31 +00005163 S->AddDecl(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005164 if (Param->getDeclName())
5165 IdResolver.AddDecl(Param);
5166}
5167
5168/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5169/// processing the delayed method declaration for Method. The method
5170/// declaration is now considered finished. There may be a separate
5171/// ActOnStartOfFunctionDef action later (not necessarily
5172/// immediately!) for this method, if it was also defined inside the
5173/// class body.
John McCalld226f652010-08-21 09:40:31 +00005174void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00005175 if (!MethodD)
5176 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005177
Douglas Gregorefd5bda2009-08-24 11:57:43 +00005178 AdjustDeclIfTemplate(MethodD);
Mike Stump1eb44332009-09-09 15:08:12 +00005179
John McCalld226f652010-08-21 09:40:31 +00005180 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005181
5182 // Now that we have our default arguments, check the constructor
5183 // again. It could produce additional diagnostics or affect whether
5184 // the class has implicitly-declared destructors, among other
5185 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00005186 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5187 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00005188
5189 // Check the default arguments, which we may have added.
5190 if (!Method->isInvalidDecl())
5191 CheckCXXDefaultArguments(Method);
5192}
5193
Douglas Gregor42a552f2008-11-05 20:51:48 +00005194/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00005195/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00005196/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005197/// emit diagnostics and set the invalid bit to true. In any case, the type
5198/// will be updated to reflect a well-formed type for the constructor and
5199/// returned.
5200QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005201 StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005202 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005203
5204 // C++ [class.ctor]p3:
5205 // A constructor shall not be virtual (10.3) or static (9.4). A
5206 // constructor can be invoked for a const, volatile or const
5207 // volatile object. A constructor shall not be declared const,
5208 // volatile, or const volatile (9.3.2).
5209 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00005210 if (!D.isInvalidType())
5211 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5212 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5213 << SourceRange(D.getIdentifierLoc());
5214 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005215 }
John McCalld931b082010-08-26 03:08:43 +00005216 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005217 if (!D.isInvalidType())
5218 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5219 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5220 << SourceRange(D.getIdentifierLoc());
5221 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005222 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005223 }
Mike Stump1eb44332009-09-09 15:08:12 +00005224
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005225 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005226 if (FTI.TypeQuals != 0) {
John McCall0953e762009-09-24 19:53:00 +00005227 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005228 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5229 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005230 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005231 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5232 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005233 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005234 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5235 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalle23cf432010-12-14 08:05:40 +00005236 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005237 }
Mike Stump1eb44332009-09-09 15:08:12 +00005238
Douglas Gregorc938c162011-01-26 05:01:58 +00005239 // C++0x [class.ctor]p4:
5240 // A constructor shall not be declared with a ref-qualifier.
5241 if (FTI.hasRefQualifier()) {
5242 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5243 << FTI.RefQualifierIsLValueRef
5244 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5245 D.setInvalidType();
5246 }
5247
Douglas Gregor42a552f2008-11-05 20:51:48 +00005248 // Rebuild the function type "R" without any type qualifiers (in
5249 // case any of the errors above fired) and with "void" as the
Douglas Gregord92ec472010-07-01 05:10:53 +00005250 // return type, since constructors don't have return types.
John McCall183700f2009-09-21 23:43:11 +00005251 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005252 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5253 return R;
5254
5255 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5256 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005257 EPI.RefQualifier = RQ_None;
5258
Chris Lattner65401802009-04-25 08:28:21 +00005259 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalle23cf432010-12-14 08:05:40 +00005260 Proto->getNumArgs(), EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005261}
5262
Douglas Gregor72b505b2008-12-16 21:30:33 +00005263/// CheckConstructor - Checks a fully-formed constructor for
5264/// well-formedness, issuing any diagnostics required. Returns true if
5265/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00005266void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump1eb44332009-09-09 15:08:12 +00005267 CXXRecordDecl *ClassDecl
Douglas Gregor33297562009-03-27 04:38:56 +00005268 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5269 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00005270 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005271
5272 // C++ [class.copy]p3:
5273 // A declaration of a constructor for a class X is ill-formed if
5274 // its first parameter is of type (optionally cv-qualified) X and
5275 // either there are no other parameters or else all other
5276 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00005277 if (!Constructor->isInvalidDecl() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005278 ((Constructor->getNumParams() == 1) ||
5279 (Constructor->getNumParams() > 1 &&
Douglas Gregor66724ea2009-11-14 01:20:54 +00005280 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5281 Constructor->getTemplateSpecializationKind()
5282 != TSK_ImplicitInstantiation) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00005283 QualType ParamType = Constructor->getParamDecl(0)->getType();
5284 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5285 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00005286 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005287 const char *ConstRef
5288 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5289 : " const &";
Douglas Gregora3a83512009-04-01 23:51:29 +00005290 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregoraeb4a282010-05-27 21:28:21 +00005291 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregor66724ea2009-11-14 01:20:54 +00005292
5293 // FIXME: Rather that making the constructor invalid, we should endeavor
5294 // to fix the type.
Chris Lattner6e475012009-04-25 08:35:12 +00005295 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00005296 }
5297 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00005298}
5299
John McCall15442822010-08-04 01:04:25 +00005300/// CheckDestructor - Checks a fully-formed destructor definition for
5301/// well-formedness, issuing any diagnostics required. Returns true
5302/// on error.
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005303bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson6d701392009-11-15 22:49:34 +00005304 CXXRecordDecl *RD = Destructor->getParent();
5305
5306 if (Destructor->isVirtual()) {
5307 SourceLocation Loc;
5308
5309 if (!Destructor->isImplicit())
5310 Loc = Destructor->getLocation();
5311 else
5312 Loc = RD->getLocation();
5313
5314 // If we have a virtual destructor, look up the deallocation function
5315 FunctionDecl *OperatorDelete = 0;
5316 DeclarationName Name =
5317 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00005318 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson37909802009-11-30 21:24:50 +00005319 return true;
John McCall5efd91a2010-07-03 18:33:00 +00005320
Eli Friedman5f2987c2012-02-02 03:46:19 +00005321 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson37909802009-11-30 21:24:50 +00005322
5323 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson6d701392009-11-15 22:49:34 +00005324 }
Anders Carlsson37909802009-11-30 21:24:50 +00005325
5326 return false;
Anders Carlsson6d701392009-11-15 22:49:34 +00005327}
5328
Mike Stump1eb44332009-09-09 15:08:12 +00005329static inline bool
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005330FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5331 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5332 FTI.ArgInfo[0].Param &&
John McCalld226f652010-08-21 09:40:31 +00005333 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005334}
5335
Douglas Gregor42a552f2008-11-05 20:51:48 +00005336/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5337/// the well-formednes of the destructor declarator @p D with type @p
5338/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00005339/// emit diagnostics and set the declarator to invalid. Even if this happens,
5340/// will be updated to reflect a well-formed type for the destructor and
5341/// returned.
Douglas Gregord92ec472010-07-01 05:10:53 +00005342QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCalld931b082010-08-26 03:08:43 +00005343 StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005344 // C++ [class.dtor]p1:
5345 // [...] A typedef-name that names a class is a class-name
5346 // (7.1.3); however, a typedef-name that names a class shall not
5347 // be used as the identifier in the declarator for a destructor
5348 // declaration.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005349 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smith162e1c12011-04-15 14:24:37 +00005350 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner65401802009-04-25 08:28:21 +00005351 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smith162e1c12011-04-15 14:24:37 +00005352 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3e4c6c42011-05-05 21:57:07 +00005353 else if (const TemplateSpecializationType *TST =
5354 DeclaratorType->getAs<TemplateSpecializationType>())
5355 if (TST->isTypeAlias())
5356 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5357 << DeclaratorType << 1;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005358
5359 // C++ [class.dtor]p2:
5360 // A destructor is used to destroy objects of its class type. A
5361 // destructor takes no parameters, and no return type can be
5362 // specified for it (not even void). The address of a destructor
5363 // shall not be taken. A destructor shall not be static. A
5364 // destructor can be invoked for a const, volatile or const
5365 // volatile object. A destructor shall not be declared const,
5366 // volatile or const volatile (9.3.2).
John McCalld931b082010-08-26 03:08:43 +00005367 if (SC == SC_Static) {
Chris Lattner65401802009-04-25 08:28:21 +00005368 if (!D.isInvalidType())
5369 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5370 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregord92ec472010-07-01 05:10:53 +00005371 << SourceRange(D.getIdentifierLoc())
5372 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5373
John McCalld931b082010-08-26 03:08:43 +00005374 SC = SC_None;
Douglas Gregor42a552f2008-11-05 20:51:48 +00005375 }
Chris Lattner65401802009-04-25 08:28:21 +00005376 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005377 // Destructors don't have return types, but the parser will
5378 // happily parse something like:
5379 //
5380 // class X {
5381 // float ~X();
5382 // };
5383 //
5384 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005385 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5386 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5387 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00005388 }
Mike Stump1eb44332009-09-09 15:08:12 +00005389
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005390 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner65401802009-04-25 08:28:21 +00005391 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall0953e762009-09-24 19:53:00 +00005392 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005393 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5394 << "const" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005395 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005396 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5397 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall0953e762009-09-24 19:53:00 +00005398 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005399 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5400 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00005401 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005402 }
5403
Douglas Gregorc938c162011-01-26 05:01:58 +00005404 // C++0x [class.dtor]p2:
5405 // A destructor shall not be declared with a ref-qualifier.
5406 if (FTI.hasRefQualifier()) {
5407 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5408 << FTI.RefQualifierIsLValueRef
5409 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5410 D.setInvalidType();
5411 }
5412
Douglas Gregor42a552f2008-11-05 20:51:48 +00005413 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00005414 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005415 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5416
5417 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00005418 FTI.freeArgs();
5419 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00005420 }
5421
Mike Stump1eb44332009-09-09 15:08:12 +00005422 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00005423 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00005424 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00005425 D.setInvalidType();
5426 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00005427
5428 // Rebuild the function type "R" without any type qualifiers or
5429 // parameters (in case any of the errors above fired) and with
5430 // "void" as the return type, since destructors don't have return
Douglas Gregord92ec472010-07-01 05:10:53 +00005431 // types.
John McCalle23cf432010-12-14 08:05:40 +00005432 if (!D.isInvalidType())
5433 return R;
5434
Douglas Gregord92ec472010-07-01 05:10:53 +00005435 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalle23cf432010-12-14 08:05:40 +00005436 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5437 EPI.Variadic = false;
5438 EPI.TypeQuals = 0;
Douglas Gregorc938c162011-01-26 05:01:58 +00005439 EPI.RefQualifier = RQ_None;
John McCalle23cf432010-12-14 08:05:40 +00005440 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor42a552f2008-11-05 20:51:48 +00005441}
5442
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005443/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5444/// well-formednes of the conversion function declarator @p D with
5445/// type @p R. If there are any errors in the declarator, this routine
5446/// will emit diagnostics and return true. Otherwise, it will return
5447/// false. Either way, the type @p R will be updated to reflect a
5448/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00005449void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCalld931b082010-08-26 03:08:43 +00005450 StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005451 // C++ [class.conv.fct]p1:
5452 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00005453 // type of a conversion function (8.3.5) is "function taking no
Mike Stump1eb44332009-09-09 15:08:12 +00005454 // parameter returning conversion-type-id."
John McCalld931b082010-08-26 03:08:43 +00005455 if (SC == SC_Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00005456 if (!D.isInvalidType())
5457 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5458 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5459 << SourceRange(D.getIdentifierLoc());
5460 D.setInvalidType();
John McCalld931b082010-08-26 03:08:43 +00005461 SC = SC_None;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005462 }
John McCalla3f81372010-04-13 00:04:31 +00005463
5464 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5465
Chris Lattner6e475012009-04-25 08:35:12 +00005466 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005467 // Conversion functions don't have return types, but the parser will
5468 // happily parse something like:
5469 //
5470 // class X {
5471 // float operator bool();
5472 // };
5473 //
5474 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005475 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5476 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5477 << SourceRange(D.getIdentifierLoc());
John McCalla3f81372010-04-13 00:04:31 +00005478 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005479 }
5480
John McCalla3f81372010-04-13 00:04:31 +00005481 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5482
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005483 // Make sure we don't have any parameters.
John McCalla3f81372010-04-13 00:04:31 +00005484 if (Proto->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005485 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5486
5487 // Delete the parameters.
Abramo Bagnara075f8f12010-12-10 16:29:40 +00005488 D.getFunctionTypeInfo().freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00005489 D.setInvalidType();
John McCalla3f81372010-04-13 00:04:31 +00005490 } else if (Proto->isVariadic()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005491 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00005492 D.setInvalidType();
5493 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005494
John McCalla3f81372010-04-13 00:04:31 +00005495 // Diagnose "&operator bool()" and other such nonsense. This
5496 // is actually a gcc extension which we don't support.
5497 if (Proto->getResultType() != ConvType) {
5498 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5499 << Proto->getResultType();
5500 D.setInvalidType();
5501 ConvType = Proto->getResultType();
5502 }
5503
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005504 // C++ [class.conv.fct]p4:
5505 // The conversion-type-id shall not represent a function type nor
5506 // an array type.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005507 if (ConvType->isArrayType()) {
5508 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5509 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005510 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005511 } else if (ConvType->isFunctionType()) {
5512 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5513 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00005514 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005515 }
5516
5517 // Rebuild the function type "R" without any parameters (in case any
5518 // of the errors above fired) and with the conversion type as the
Mike Stump1eb44332009-09-09 15:08:12 +00005519 // return type.
John McCalle23cf432010-12-14 08:05:40 +00005520 if (D.isInvalidType())
5521 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005522
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005523 // C++0x explicit conversion operators.
Richard Smithebaf0e62011-10-18 20:49:44 +00005524 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump1eb44332009-09-09 15:08:12 +00005525 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smithebaf0e62011-10-18 20:49:44 +00005526 getLangOptions().CPlusPlus0x ?
5527 diag::warn_cxx98_compat_explicit_conversion_functions :
5528 diag::ext_explicit_conversion_functions)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005529 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005530}
5531
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005532/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5533/// the declaration of the given C++ conversion function. This routine
5534/// is responsible for recording the conversion function in the C++
5535/// class, if possible.
John McCalld226f652010-08-21 09:40:31 +00005536Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005537 assert(Conversion && "Expected to receive a conversion function declaration");
5538
Douglas Gregor9d350972008-12-12 08:25:50 +00005539 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005540
5541 // Make sure we aren't redeclaring the conversion function.
5542 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005543
5544 // C++ [class.conv.fct]p1:
5545 // [...] A conversion function is never used to convert a
5546 // (possibly cv-qualified) object to the (possibly cv-qualified)
5547 // same object type (or a reference to it), to a (possibly
5548 // cv-qualified) base class of that type (or a reference to it),
5549 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00005550 // FIXME: Suppress this warning if the conversion function ends up being a
5551 // virtual function that overrides a virtual function in a base class.
Mike Stump1eb44332009-09-09 15:08:12 +00005552 QualType ClassType
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005553 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00005554 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005555 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005556 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5557 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregor10341702010-09-13 16:44:26 +00005558 /* Suppress diagnostics for instantiations. */;
Douglas Gregorda0fd9a2010-09-12 07:22:28 +00005559 else if (ConvType->isRecordType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005560 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5561 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00005562 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005563 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005564 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00005565 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005566 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005567 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00005568 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00005569 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005570 }
5571
Douglas Gregore80622f2010-09-29 04:25:11 +00005572 if (FunctionTemplateDecl *ConversionTemplate
5573 = Conversion->getDescribedFunctionTemplate())
5574 return ConversionTemplate;
5575
John McCalld226f652010-08-21 09:40:31 +00005576 return Conversion;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00005577}
5578
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005579//===----------------------------------------------------------------------===//
5580// Namespace Handling
5581//===----------------------------------------------------------------------===//
5582
John McCallea318642010-08-26 09:15:37 +00005583
5584
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005585/// ActOnStartNamespaceDef - This is called at the start of a namespace
5586/// definition.
John McCalld226f652010-08-21 09:40:31 +00005587Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redld078e642010-08-27 23:12:46 +00005588 SourceLocation InlineLoc,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005589 SourceLocation NamespaceLoc,
John McCallea318642010-08-26 09:15:37 +00005590 SourceLocation IdentLoc,
5591 IdentifierInfo *II,
5592 SourceLocation LBrace,
5593 AttributeList *AttrList) {
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005594 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5595 // For anonymous namespace, take the location of the left brace.
5596 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005597 bool IsInline = InlineLoc.isValid();
Douglas Gregor67310742012-01-10 22:14:10 +00005598 bool IsInvalid = false;
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005599 bool IsStd = false;
5600 bool AddToKnown = false;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005601 Scope *DeclRegionScope = NamespcScope->getParent();
5602
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005603 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005604 if (II) {
5605 // C++ [namespace.def]p2:
Douglas Gregorfe7574b2010-10-22 15:24:46 +00005606 // The identifier in an original-namespace-definition shall not
5607 // have been previously defined in the declarative region in
5608 // which the original-namespace-definition appears. The
5609 // identifier in an original-namespace-definition is the name of
5610 // the namespace. Subsequently in that declarative region, it is
5611 // treated as an original-namespace-name.
5612 //
5613 // Since namespace names are unique in their scope, and we don't
Douglas Gregor010157f2011-05-06 23:28:47 +00005614 // look through using directives, just look for any ordinary names.
5615
5616 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005617 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5618 Decl::IDNS_Namespace;
Douglas Gregor010157f2011-05-06 23:28:47 +00005619 NamedDecl *PrevDecl = 0;
5620 for (DeclContext::lookup_result R
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005621 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregor010157f2011-05-06 23:28:47 +00005622 R.first != R.second; ++R.first) {
5623 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5624 PrevDecl = *R.first;
5625 break;
5626 }
5627 }
5628
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005629 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5630
5631 if (PrevNS) {
Douglas Gregor44b43212008-12-11 16:49:14 +00005632 // This is an extended namespace definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005633 if (IsInline != PrevNS->isInline()) {
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005634 // inline-ness must match
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005635 if (PrevNS->isInline()) {
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005636 // The user probably just forgot the 'inline', so suggest that it
5637 // be added back.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005638 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005639 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5640 } else {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005641 Diag(Loc, diag::err_inline_namespace_mismatch)
5642 << IsInline;
Douglas Gregorb7ec9062011-05-20 15:48:31 +00005643 }
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005644 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5645
5646 IsInline = PrevNS->isInline();
5647 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005648 } else if (PrevDecl) {
5649 // This is an invalid name redefinition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005650 Diag(Loc, diag::err_redefinition_different_kind)
5651 << II;
Douglas Gregor44b43212008-12-11 16:49:14 +00005652 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005653 IsInvalid = true;
Douglas Gregor44b43212008-12-11 16:49:14 +00005654 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005655 } else if (II->isStr("std") &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00005656 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor7adb10f2009-09-15 22:30:29 +00005657 // This is the first "real" definition of the namespace "std", so update
5658 // our cache of the "std" namespace to point at this definition.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005659 PrevNS = getStdNamespace();
5660 IsStd = true;
5661 AddToKnown = !IsInline;
5662 } else {
5663 // We've seen this namespace for the first time.
5664 AddToKnown = !IsInline;
Mike Stump1eb44332009-09-09 15:08:12 +00005665 }
Douglas Gregor44b43212008-12-11 16:49:14 +00005666 } else {
John McCall9aeed322009-10-01 00:25:31 +00005667 // Anonymous namespaces.
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005668
5669 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl7a126a42010-08-31 00:36:30 +00005670 DeclContext *Parent = CurContext->getRedeclContext();
John McCall5fdd7642009-12-16 02:06:49 +00005671 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005672 PrevNS = TU->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005673 } else {
5674 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005675 PrevNS = ND->getAnonymousNamespace();
John McCall5fdd7642009-12-16 02:06:49 +00005676 }
5677
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005678 if (PrevNS && IsInline != PrevNS->isInline()) {
5679 // inline-ness must match
5680 Diag(Loc, diag::err_inline_namespace_mismatch)
5681 << IsInline;
5682 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor67310742012-01-10 22:14:10 +00005683
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005684 // Recover by ignoring the new namespace's inline status.
5685 IsInline = PrevNS->isInline();
5686 }
5687 }
5688
5689 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5690 StartLoc, Loc, II, PrevNS);
Douglas Gregor67310742012-01-10 22:14:10 +00005691 if (IsInvalid)
5692 Namespc->setInvalidDecl();
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005693
5694 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redl4e4d5702010-08-31 00:36:36 +00005695
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005696 // FIXME: Should we be merging attributes?
5697 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005698 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005699
5700 if (IsStd)
5701 StdNamespace = Namespc;
5702 if (AddToKnown)
5703 KnownNamespaces[Namespc] = false;
5704
5705 if (II) {
5706 PushOnScopeChains(Namespc, DeclRegionScope);
5707 } else {
5708 // Link the anonymous namespace into its parent.
5709 DeclContext *Parent = CurContext->getRedeclContext();
5710 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5711 TU->setAnonymousNamespace(Namespc);
5712 } else {
5713 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall5fdd7642009-12-16 02:06:49 +00005714 }
John McCall9aeed322009-10-01 00:25:31 +00005715
Douglas Gregora4181472010-03-24 00:46:35 +00005716 CurContext->addDecl(Namespc);
5717
John McCall9aeed322009-10-01 00:25:31 +00005718 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5719 // behaves as if it were replaced by
5720 // namespace unique { /* empty body */ }
5721 // using namespace unique;
5722 // namespace unique { namespace-body }
5723 // where all occurrences of 'unique' in a translation unit are
5724 // replaced by the same identifier and this identifier differs
5725 // from all other identifiers in the entire program.
5726
5727 // We just create the namespace with an empty name and then add an
5728 // implicit using declaration, just like the standard suggests.
5729 //
5730 // CodeGen enforces the "universally unique" aspect by giving all
5731 // declarations semantically contained within an anonymous
5732 // namespace internal linkage.
5733
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005734 if (!PrevNS) {
John McCall5fdd7642009-12-16 02:06:49 +00005735 UsingDirectiveDecl* UD
5736 = UsingDirectiveDecl::Create(Context, CurContext,
5737 /* 'using' */ LBrace,
5738 /* 'namespace' */ SourceLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00005739 /* qualifier */ NestedNameSpecifierLoc(),
John McCall5fdd7642009-12-16 02:06:49 +00005740 /* identifier */ SourceLocation(),
5741 Namespc,
5742 /* Ancestor */ CurContext);
5743 UD->setImplicit();
5744 CurContext->addDecl(UD);
5745 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005746 }
5747
5748 // Although we could have an invalid decl (i.e. the namespace name is a
5749 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00005750 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5751 // for the namespace has the declarations that showed up in that particular
5752 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00005753 PushDeclContext(NamespcScope, Namespc);
John McCalld226f652010-08-21 09:40:31 +00005754 return Namespc;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005755}
5756
Sebastian Redleb0d8c92009-11-23 15:34:23 +00005757/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5758/// is a namespace alias, returns the namespace it points to.
5759static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5760 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5761 return AD->getNamespace();
5762 return dyn_cast_or_null<NamespaceDecl>(D);
5763}
5764
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005765/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5766/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCalld226f652010-08-21 09:40:31 +00005767void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005768 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5769 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005770 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005771 PopDeclContext();
Eli Friedmanaa8b0d12010-08-05 06:57:20 +00005772 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola20039ae2012-02-01 23:24:59 +00005773 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00005774}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00005775
John McCall384aff82010-08-25 07:42:41 +00005776CXXRecordDecl *Sema::getStdBadAlloc() const {
5777 return cast_or_null<CXXRecordDecl>(
5778 StdBadAlloc.get(Context.getExternalSource()));
5779}
5780
5781NamespaceDecl *Sema::getStdNamespace() const {
5782 return cast_or_null<NamespaceDecl>(
5783 StdNamespace.get(Context.getExternalSource()));
5784}
5785
Douglas Gregor66992202010-06-29 17:53:46 +00005786/// \brief Retrieve the special "std" namespace, which may require us to
5787/// implicitly define the namespace.
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00005788NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregor66992202010-06-29 17:53:46 +00005789 if (!StdNamespace) {
5790 // The "std" namespace has not yet been defined, so build one implicitly.
5791 StdNamespace = NamespaceDecl::Create(Context,
5792 Context.getTranslationUnitDecl(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005793 /*Inline=*/false,
Abramo Bagnaraacba90f2011-03-08 12:38:20 +00005794 SourceLocation(), SourceLocation(),
Douglas Gregorf5c9f9f2012-01-07 09:11:48 +00005795 &PP.getIdentifierTable().get("std"),
5796 /*PrevDecl=*/0);
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005797 getStdNamespace()->setImplicit(true);
Douglas Gregor66992202010-06-29 17:53:46 +00005798 }
5799
Argyrios Kyrtzidis76c38d32010-08-02 07:14:54 +00005800 return getStdNamespace();
Douglas Gregor66992202010-06-29 17:53:46 +00005801}
5802
Sebastian Redl395e04d2012-01-17 22:49:33 +00005803bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5804 assert(getLangOptions().CPlusPlus &&
5805 "Looking for std::initializer_list outside of C++.");
5806
5807 // We're looking for implicit instantiations of
5808 // template <typename E> class std::initializer_list.
5809
5810 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5811 return false;
5812
Sebastian Redl84760e32012-01-17 22:49:58 +00005813 ClassTemplateDecl *Template = 0;
5814 const TemplateArgument *Arguments = 0;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005815
Sebastian Redl84760e32012-01-17 22:49:58 +00005816 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl395e04d2012-01-17 22:49:33 +00005817
Sebastian Redl84760e32012-01-17 22:49:58 +00005818 ClassTemplateSpecializationDecl *Specialization =
5819 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5820 if (!Specialization)
5821 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005822
Sebastian Redl84760e32012-01-17 22:49:58 +00005823 Template = Specialization->getSpecializedTemplate();
5824 Arguments = Specialization->getTemplateArgs().data();
5825 } else if (const TemplateSpecializationType *TST =
5826 Ty->getAs<TemplateSpecializationType>()) {
5827 Template = dyn_cast_or_null<ClassTemplateDecl>(
5828 TST->getTemplateName().getAsTemplateDecl());
5829 Arguments = TST->getArgs();
5830 }
5831 if (!Template)
5832 return false;
Sebastian Redl395e04d2012-01-17 22:49:33 +00005833
5834 if (!StdInitializerList) {
5835 // Haven't recognized std::initializer_list yet, maybe this is it.
5836 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5837 if (TemplateClass->getIdentifier() !=
5838 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005839 !getStdNamespace()->InEnclosingNamespaceSetOf(
5840 TemplateClass->getDeclContext()))
Sebastian Redl395e04d2012-01-17 22:49:33 +00005841 return false;
5842 // This is a template called std::initializer_list, but is it the right
5843 // template?
5844 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005845 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl395e04d2012-01-17 22:49:33 +00005846 return false;
5847 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5848 return false;
5849
5850 // It's the right template.
5851 StdInitializerList = Template;
5852 }
5853
5854 if (Template != StdInitializerList)
5855 return false;
5856
5857 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl84760e32012-01-17 22:49:58 +00005858 if (Element)
5859 *Element = Arguments[0].getAsType();
Sebastian Redl395e04d2012-01-17 22:49:33 +00005860 return true;
5861}
5862
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005863static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5864 NamespaceDecl *Std = S.getStdNamespace();
5865 if (!Std) {
5866 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5867 return 0;
5868 }
5869
5870 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5871 Loc, Sema::LookupOrdinaryName);
5872 if (!S.LookupQualifiedName(Result, Std)) {
5873 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5874 return 0;
5875 }
5876 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5877 if (!Template) {
5878 Result.suppressDiagnostics();
5879 // We found something weird. Complain about the first thing we found.
5880 NamedDecl *Found = *Result.begin();
5881 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5882 return 0;
5883 }
5884
5885 // We found some template called std::initializer_list. Now verify that it's
5886 // correct.
5887 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redlb832f6d2012-01-23 22:09:39 +00005888 if (Params->getMinRequiredArguments() != 1 ||
5889 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00005890 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5891 return 0;
5892 }
5893
5894 return Template;
5895}
5896
5897QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5898 if (!StdInitializerList) {
5899 StdInitializerList = LookupStdInitializerList(*this, Loc);
5900 if (!StdInitializerList)
5901 return QualType();
5902 }
5903
5904 TemplateArgumentListInfo Args(Loc, Loc);
5905 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5906 Context.getTrivialTypeSourceInfo(Element,
5907 Loc)));
5908 return Context.getCanonicalType(
5909 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5910}
5911
Sebastian Redl98d36062012-01-17 22:50:14 +00005912bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5913 // C++ [dcl.init.list]p2:
5914 // A constructor is an initializer-list constructor if its first parameter
5915 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5916 // std::initializer_list<E> for some type E, and either there are no other
5917 // parameters or else all other parameters have default arguments.
5918 if (Ctor->getNumParams() < 1 ||
5919 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5920 return false;
5921
5922 QualType ArgType = Ctor->getParamDecl(0)->getType();
5923 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5924 ArgType = RT->getPointeeType().getUnqualifiedType();
5925
5926 return isStdInitializerList(ArgType, 0);
5927}
5928
Douglas Gregor9172aa62011-03-26 22:25:30 +00005929/// \brief Determine whether a using statement is in a context where it will be
5930/// apply in all contexts.
5931static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5932 switch (CurContext->getDeclKind()) {
5933 case Decl::TranslationUnit:
5934 return true;
5935 case Decl::LinkageSpec:
5936 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5937 default:
5938 return false;
5939 }
5940}
5941
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005942namespace {
5943
5944// Callback to only accept typo corrections that are namespaces.
5945class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5946 public:
5947 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5948 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5949 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5950 }
5951 return false;
5952 }
5953};
5954
5955}
5956
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005957static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5958 CXXScopeSpec &SS,
5959 SourceLocation IdentLoc,
5960 IdentifierInfo *Ident) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005961 NamespaceValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005962 R.clear();
5963 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005964 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00005965 Validator)) {
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005966 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5967 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5968 if (DeclContext *DC = S.computeDeclContext(SS, false))
5969 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5970 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5971 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5972 else
5973 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5974 << Ident << CorrectedQuotedStr
5975 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005976
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005977 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5978 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005979
Kaelyn Uhrain7d5e6942012-01-11 19:37:46 +00005980 Ident = Corrected.getCorrectionAsIdentifierInfo();
5981 R.addDecl(Corrected.getCorrectionDecl());
5982 return true;
Douglas Gregord8bba9c2011-06-28 16:20:02 +00005983 }
5984 return false;
5985}
5986
John McCalld226f652010-08-21 09:40:31 +00005987Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005988 SourceLocation UsingLoc,
5989 SourceLocation NamespcLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005990 CXXScopeSpec &SS,
Chris Lattnerb28317a2009-03-28 19:18:32 +00005991 SourceLocation IdentLoc,
5992 IdentifierInfo *NamespcName,
5993 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00005994 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5995 assert(NamespcName && "Invalid NamespcName.");
5996 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall78b81052010-11-10 02:40:36 +00005997
5998 // This can only happen along a recovery path.
5999 while (S->getFlags() & Scope::TemplateParamScope)
6000 S = S->getParent();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006001 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00006002
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006003 UsingDirectiveDecl *UDir = 0;
Douglas Gregor66992202010-06-29 17:53:46 +00006004 NestedNameSpecifier *Qualifier = 0;
6005 if (SS.isSet())
6006 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6007
Douglas Gregoreb11cd02009-01-14 22:20:51 +00006008 // Lookup namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006009 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6010 LookupParsedName(R, S, &SS);
6011 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006012 return 0;
John McCalla24dc2e2009-11-17 02:14:36 +00006013
Douglas Gregor66992202010-06-29 17:53:46 +00006014 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006015 R.clear();
Douglas Gregor66992202010-06-29 17:53:46 +00006016 // Allow "using namespace std;" or "using namespace ::std;" even if
6017 // "std" hasn't been defined yet, for GCC compatibility.
6018 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6019 NamespcName->isStr("std")) {
6020 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis26faaac2010-08-02 07:14:39 +00006021 R.addDecl(getOrCreateStdNamespace());
Douglas Gregor66992202010-06-29 17:53:46 +00006022 R.resolveKind();
6023 }
6024 // Otherwise, attempt typo correction.
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006025 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregor66992202010-06-29 17:53:46 +00006026 }
6027
John McCallf36e02d2009-10-09 21:13:30 +00006028 if (!R.empty()) {
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006029 NamedDecl *Named = R.getFoundDecl();
6030 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6031 && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006032 // C++ [namespace.udir]p1:
6033 // A using-directive specifies that the names in the nominated
6034 // namespace can be used in the scope in which the
6035 // using-directive appears after the using-directive. During
6036 // unqualified name lookup (3.4.1), the names appear as if they
6037 // were declared in the nearest enclosing namespace which
6038 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00006039 // namespace. [Note: in this context, "contains" means "contains
6040 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006041
6042 // Find enclosing context containing both using-directive and
6043 // nominated namespace.
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006044 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006045 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6046 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6047 CommonAncestor = CommonAncestor->getParent();
6048
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006049 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregordb992412011-02-25 16:33:46 +00006050 SS.getWithLocInContext(Context),
Sebastian Redleb0d8c92009-11-23 15:34:23 +00006051 IdentLoc, Named, CommonAncestor);
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006052
Douglas Gregor9172aa62011-03-26 22:25:30 +00006053 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth40278532011-07-25 16:49:02 +00006054 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregord6a49bb2011-03-18 16:10:52 +00006055 Diag(IdentLoc, diag::warn_using_directive_in_header);
6056 }
6057
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006058 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006059 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00006060 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00006061 }
6062
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006063 // FIXME: We ignore attributes for now.
John McCalld226f652010-08-21 09:40:31 +00006064 return UDir;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006065}
6066
6067void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6068 // If scope has associated entity, then using directive is at namespace
6069 // or translation unit scope. We add UsingDirectiveDecls, into
6070 // it's lookup structure.
6071 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00006072 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00006073 else
6074 // Otherwise it is block-sope. using-directives will affect lookup
6075 // only to the end of scope.
John McCalld226f652010-08-21 09:40:31 +00006076 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00006077}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00006078
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006079
John McCalld226f652010-08-21 09:40:31 +00006080Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall78b81052010-11-10 02:40:36 +00006081 AccessSpecifier AS,
6082 bool HasUsingKeyword,
6083 SourceLocation UsingLoc,
6084 CXXScopeSpec &SS,
6085 UnqualifiedId &Name,
6086 AttributeList *AttrList,
6087 bool IsTypeName,
6088 SourceLocation TypenameLoc) {
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006089 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump1eb44332009-09-09 15:08:12 +00006090
Douglas Gregor12c118a2009-11-04 16:30:06 +00006091 switch (Name.getKind()) {
Fariborz Jahanian98a54032011-07-12 17:16:56 +00006092 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006093 case UnqualifiedId::IK_Identifier:
6094 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunt0486d742009-11-28 04:44:28 +00006095 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor12c118a2009-11-04 16:30:06 +00006096 case UnqualifiedId::IK_ConversionFunctionId:
6097 break;
6098
6099 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor0efc2c12010-01-13 17:31:36 +00006100 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall604e7f12009-12-08 07:46:18 +00006101 // C++0x inherited constructors.
Richard Smithebaf0e62011-10-18 20:49:44 +00006102 Diag(Name.getSourceRange().getBegin(),
6103 getLangOptions().CPlusPlus0x ?
6104 diag::warn_cxx98_compat_using_decl_constructor :
6105 diag::err_using_decl_constructor)
6106 << SS.getRange();
6107
John McCall604e7f12009-12-08 07:46:18 +00006108 if (getLangOptions().CPlusPlus0x) break;
6109
John McCalld226f652010-08-21 09:40:31 +00006110 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006111
6112 case UnqualifiedId::IK_DestructorName:
6113 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6114 << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006115 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006116
6117 case UnqualifiedId::IK_TemplateId:
6118 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6119 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCalld226f652010-08-21 09:40:31 +00006120 return 0;
Douglas Gregor12c118a2009-11-04 16:30:06 +00006121 }
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006122
6123 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6124 DeclarationName TargetName = TargetNameInfo.getName();
John McCall604e7f12009-12-08 07:46:18 +00006125 if (!TargetName)
John McCalld226f652010-08-21 09:40:31 +00006126 return 0;
John McCall604e7f12009-12-08 07:46:18 +00006127
John McCall60fa3cf2009-12-11 02:10:03 +00006128 // Warn about using declarations.
6129 // TODO: store that the declaration was written without 'using' and
6130 // talk about access decls instead of using decls in the
6131 // diagnostics.
6132 if (!HasUsingKeyword) {
6133 UsingLoc = Name.getSourceRange().getBegin();
6134
6135 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregor849b2432010-03-31 17:46:05 +00006136 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCall60fa3cf2009-12-11 02:10:03 +00006137 }
6138
Douglas Gregor56c04582010-12-16 00:46:58 +00006139 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6140 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6141 return 0;
6142
John McCall9488ea12009-11-17 05:59:44 +00006143 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006144 TargetNameInfo, AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006145 /* IsInstantiation */ false,
6146 IsTypeName, TypenameLoc);
John McCalled976492009-12-04 22:46:56 +00006147 if (UD)
6148 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump1eb44332009-09-09 15:08:12 +00006149
John McCalld226f652010-08-21 09:40:31 +00006150 return UD;
Anders Carlssonc72160b2009-08-28 05:40:36 +00006151}
6152
Douglas Gregor09acc982010-07-07 23:08:52 +00006153/// \brief Determine whether a using declaration considers the given
6154/// declarations as "equivalent", e.g., if they are redeclarations of
6155/// the same entity or are both typedefs of the same type.
6156static bool
6157IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6158 bool &SuppressRedeclaration) {
6159 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6160 SuppressRedeclaration = false;
6161 return true;
6162 }
6163
Richard Smith162e1c12011-04-15 14:24:37 +00006164 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6165 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor09acc982010-07-07 23:08:52 +00006166 SuppressRedeclaration = true;
6167 return Context.hasSameType(TD1->getUnderlyingType(),
6168 TD2->getUnderlyingType());
6169 }
6170
6171 return false;
6172}
6173
6174
John McCall9f54ad42009-12-10 09:41:52 +00006175/// Determines whether to create a using shadow decl for a particular
6176/// decl, given the set of decls existing prior to this using lookup.
6177bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6178 const LookupResult &Previous) {
6179 // Diagnose finding a decl which is not from a base class of the
6180 // current class. We do this now because there are cases where this
6181 // function will silently decide not to build a shadow decl, which
6182 // will pre-empt further diagnostics.
6183 //
6184 // We don't need to do this in C++0x because we do the check once on
6185 // the qualifier.
6186 //
6187 // FIXME: diagnose the following if we care enough:
6188 // struct A { int foo; };
6189 // struct B : A { using A::foo; };
6190 // template <class T> struct C : A {};
6191 // template <class T> struct D : C<T> { using B::foo; } // <---
6192 // This is invalid (during instantiation) in C++03 because B::foo
6193 // resolves to the using decl in B, which is not a base class of D<T>.
6194 // We can't diagnose it immediately because C<T> is an unknown
6195 // specialization. The UsingShadowDecl in D<T> then points directly
6196 // to A::foo, which will look well-formed when we instantiate.
6197 // The right solution is to not collapse the shadow-decl chain.
6198 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6199 DeclContext *OrigDC = Orig->getDeclContext();
6200
6201 // Handle enums and anonymous structs.
6202 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6203 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6204 while (OrigRec->isAnonymousStructOrUnion())
6205 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6206
6207 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6208 if (OrigDC == CurContext) {
6209 Diag(Using->getLocation(),
6210 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006211 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006212 Diag(Orig->getLocation(), diag::note_using_decl_target);
6213 return true;
6214 }
6215
Douglas Gregordc355712011-02-25 00:36:19 +00006216 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall9f54ad42009-12-10 09:41:52 +00006217 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregordc355712011-02-25 00:36:19 +00006218 << Using->getQualifier()
John McCall9f54ad42009-12-10 09:41:52 +00006219 << cast<CXXRecordDecl>(CurContext)
Douglas Gregordc355712011-02-25 00:36:19 +00006220 << Using->getQualifierLoc().getSourceRange();
John McCall9f54ad42009-12-10 09:41:52 +00006221 Diag(Orig->getLocation(), diag::note_using_decl_target);
6222 return true;
6223 }
6224 }
6225
6226 if (Previous.empty()) return false;
6227
6228 NamedDecl *Target = Orig;
6229 if (isa<UsingShadowDecl>(Target))
6230 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6231
John McCalld7533ec2009-12-11 02:33:26 +00006232 // If the target happens to be one of the previous declarations, we
6233 // don't have a conflict.
6234 //
6235 // FIXME: but we might be increasing its access, in which case we
6236 // should redeclare it.
6237 NamedDecl *NonTag = 0, *Tag = 0;
6238 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6239 I != E; ++I) {
6240 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor09acc982010-07-07 23:08:52 +00006241 bool Result;
6242 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6243 return Result;
John McCalld7533ec2009-12-11 02:33:26 +00006244
6245 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6246 }
6247
John McCall9f54ad42009-12-10 09:41:52 +00006248 if (Target->isFunctionOrFunctionTemplate()) {
6249 FunctionDecl *FD;
6250 if (isa<FunctionTemplateDecl>(Target))
6251 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6252 else
6253 FD = cast<FunctionDecl>(Target);
6254
6255 NamedDecl *OldDecl = 0;
John McCallad00b772010-06-16 08:42:20 +00006256 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall9f54ad42009-12-10 09:41:52 +00006257 case Ovl_Overload:
6258 return false;
6259
6260 case Ovl_NonFunction:
John McCall41ce66f2009-12-10 19:51:03 +00006261 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006262 break;
6263
6264 // We found a decl with the exact signature.
6265 case Ovl_Match:
John McCall9f54ad42009-12-10 09:41:52 +00006266 // If we're in a record, we want to hide the target, so we
6267 // return true (without a diagnostic) to tell the caller not to
6268 // build a shadow decl.
6269 if (CurContext->isRecord())
6270 return true;
6271
6272 // If we're not in a record, this is an error.
John McCall41ce66f2009-12-10 19:51:03 +00006273 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006274 break;
6275 }
6276
6277 Diag(Target->getLocation(), diag::note_using_decl_target);
6278 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6279 return true;
6280 }
6281
6282 // Target is not a function.
6283
John McCall9f54ad42009-12-10 09:41:52 +00006284 if (isa<TagDecl>(Target)) {
6285 // No conflict between a tag and a non-tag.
6286 if (!Tag) return false;
6287
John McCall41ce66f2009-12-10 19:51:03 +00006288 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006289 Diag(Target->getLocation(), diag::note_using_decl_target);
6290 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6291 return true;
6292 }
6293
6294 // No conflict between a tag and a non-tag.
6295 if (!NonTag) return false;
6296
John McCall41ce66f2009-12-10 19:51:03 +00006297 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall9f54ad42009-12-10 09:41:52 +00006298 Diag(Target->getLocation(), diag::note_using_decl_target);
6299 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6300 return true;
6301}
6302
John McCall9488ea12009-11-17 05:59:44 +00006303/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall604e7f12009-12-08 07:46:18 +00006304UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall604e7f12009-12-08 07:46:18 +00006305 UsingDecl *UD,
6306 NamedDecl *Orig) {
John McCall9488ea12009-11-17 05:59:44 +00006307
6308 // If we resolved to another shadow declaration, just coalesce them.
John McCall604e7f12009-12-08 07:46:18 +00006309 NamedDecl *Target = Orig;
6310 if (isa<UsingShadowDecl>(Target)) {
6311 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6312 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall9488ea12009-11-17 05:59:44 +00006313 }
6314
6315 UsingShadowDecl *Shadow
John McCall604e7f12009-12-08 07:46:18 +00006316 = UsingShadowDecl::Create(Context, CurContext,
6317 UD->getLocation(), UD, Target);
John McCall9488ea12009-11-17 05:59:44 +00006318 UD->addShadowDecl(Shadow);
Douglas Gregore80622f2010-09-29 04:25:11 +00006319
6320 Shadow->setAccess(UD->getAccess());
6321 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6322 Shadow->setInvalidDecl();
6323
John McCall9488ea12009-11-17 05:59:44 +00006324 if (S)
John McCall604e7f12009-12-08 07:46:18 +00006325 PushOnScopeChains(Shadow, S);
John McCall9488ea12009-11-17 05:59:44 +00006326 else
John McCall604e7f12009-12-08 07:46:18 +00006327 CurContext->addDecl(Shadow);
John McCall9488ea12009-11-17 05:59:44 +00006328
John McCall604e7f12009-12-08 07:46:18 +00006329
John McCall9f54ad42009-12-10 09:41:52 +00006330 return Shadow;
6331}
John McCall604e7f12009-12-08 07:46:18 +00006332
John McCall9f54ad42009-12-10 09:41:52 +00006333/// Hides a using shadow declaration. This is required by the current
6334/// using-decl implementation when a resolvable using declaration in a
6335/// class is followed by a declaration which would hide or override
6336/// one or more of the using decl's targets; for example:
6337///
6338/// struct Base { void foo(int); };
6339/// struct Derived : Base {
6340/// using Base::foo;
6341/// void foo(int);
6342/// };
6343///
6344/// The governing language is C++03 [namespace.udecl]p12:
6345///
6346/// When a using-declaration brings names from a base class into a
6347/// derived class scope, member functions in the derived class
6348/// override and/or hide member functions with the same name and
6349/// parameter types in a base class (rather than conflicting).
6350///
6351/// There are two ways to implement this:
6352/// (1) optimistically create shadow decls when they're not hidden
6353/// by existing declarations, or
6354/// (2) don't create any shadow decls (or at least don't make them
6355/// visible) until we've fully parsed/instantiated the class.
6356/// The problem with (1) is that we might have to retroactively remove
6357/// a shadow decl, which requires several O(n) operations because the
6358/// decl structures are (very reasonably) not designed for removal.
6359/// (2) avoids this but is very fiddly and phase-dependent.
6360void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCall32daa422010-03-31 01:36:47 +00006361 if (Shadow->getDeclName().getNameKind() ==
6362 DeclarationName::CXXConversionFunctionName)
6363 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6364
John McCall9f54ad42009-12-10 09:41:52 +00006365 // Remove it from the DeclContext...
6366 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006367
John McCall9f54ad42009-12-10 09:41:52 +00006368 // ...and the scope, if applicable...
6369 if (S) {
John McCalld226f652010-08-21 09:40:31 +00006370 S->RemoveDecl(Shadow);
John McCall9f54ad42009-12-10 09:41:52 +00006371 IdResolver.RemoveDecl(Shadow);
John McCall604e7f12009-12-08 07:46:18 +00006372 }
6373
John McCall9f54ad42009-12-10 09:41:52 +00006374 // ...and the using decl.
6375 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6376
6377 // TODO: complain somehow if Shadow was used. It shouldn't
John McCall32daa422010-03-31 01:36:47 +00006378 // be possible for this to happen, because...?
John McCall9488ea12009-11-17 05:59:44 +00006379}
6380
John McCall7ba107a2009-11-18 02:36:19 +00006381/// Builds a using declaration.
6382///
6383/// \param IsInstantiation - Whether this call arises from an
6384/// instantiation of an unresolved using declaration. We treat
6385/// the lookup differently for these declarations.
John McCall9488ea12009-11-17 05:59:44 +00006386NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6387 SourceLocation UsingLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006388 CXXScopeSpec &SS,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006389 const DeclarationNameInfo &NameInfo,
Anders Carlssonc72160b2009-08-28 05:40:36 +00006390 AttributeList *AttrList,
John McCall7ba107a2009-11-18 02:36:19 +00006391 bool IsInstantiation,
6392 bool IsTypeName,
6393 SourceLocation TypenameLoc) {
Anders Carlssonc72160b2009-08-28 05:40:36 +00006394 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006395 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlssonc72160b2009-08-28 05:40:36 +00006396 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00006397
Anders Carlsson550b14b2009-08-28 05:49:21 +00006398 // FIXME: We ignore attributes for now.
Mike Stump1eb44332009-09-09 15:08:12 +00006399
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006400 if (SS.isEmpty()) {
6401 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00006402 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006403 }
Mike Stump1eb44332009-09-09 15:08:12 +00006404
John McCall9f54ad42009-12-10 09:41:52 +00006405 // Do the redeclaration lookup in the current scope.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006406 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall9f54ad42009-12-10 09:41:52 +00006407 ForRedeclaration);
6408 Previous.setHideTags(false);
6409 if (S) {
6410 LookupName(Previous, S);
6411
6412 // It is really dumb that we have to do this.
6413 LookupResult::Filter F = Previous.makeFilter();
6414 while (F.hasNext()) {
6415 NamedDecl *D = F.next();
6416 if (!isDeclInScope(D, CurContext, S))
6417 F.erase();
6418 }
6419 F.done();
6420 } else {
6421 assert(IsInstantiation && "no scope in non-instantiation");
6422 assert(CurContext->isRecord() && "scope not record in instantiation");
6423 LookupQualifiedName(Previous, CurContext);
6424 }
6425
John McCall9f54ad42009-12-10 09:41:52 +00006426 // Check for invalid redeclarations.
6427 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6428 return 0;
6429
6430 // Check for bad qualifiers.
John McCalled976492009-12-04 22:46:56 +00006431 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6432 return 0;
6433
John McCallaf8e6ed2009-11-12 03:15:40 +00006434 DeclContext *LookupContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006435 NamedDecl *D;
Douglas Gregordc355712011-02-25 00:36:19 +00006436 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallaf8e6ed2009-11-12 03:15:40 +00006437 if (!LookupContext) {
John McCall7ba107a2009-11-18 02:36:19 +00006438 if (IsTypeName) {
John McCalled976492009-12-04 22:46:56 +00006439 // FIXME: not all declaration name kinds are legal here
6440 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6441 UsingLoc, TypenameLoc,
Douglas Gregordc355712011-02-25 00:36:19 +00006442 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006443 IdentLoc, NameInfo.getName());
John McCalled976492009-12-04 22:46:56 +00006444 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006445 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6446 QualifierLoc, NameInfo);
John McCall7ba107a2009-11-18 02:36:19 +00006447 }
John McCalled976492009-12-04 22:46:56 +00006448 } else {
Douglas Gregordc355712011-02-25 00:36:19 +00006449 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6450 NameInfo, IsTypeName);
Anders Carlsson550b14b2009-08-28 05:49:21 +00006451 }
John McCalled976492009-12-04 22:46:56 +00006452 D->setAccess(AS);
6453 CurContext->addDecl(D);
6454
6455 if (!LookupContext) return D;
6456 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump1eb44332009-09-09 15:08:12 +00006457
John McCall77bb1aa2010-05-01 00:40:08 +00006458 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall604e7f12009-12-08 07:46:18 +00006459 UD->setInvalidDecl();
6460 return UD;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006461 }
6462
Sebastian Redlf677ea32011-02-05 19:23:19 +00006463 // Constructor inheriting using decls get special treatment.
6464 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlcaa35e42011-03-12 13:44:32 +00006465 if (CheckInheritedConstructorUsingDecl(UD))
6466 UD->setInvalidDecl();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006467 return UD;
6468 }
6469
6470 // Otherwise, look up the target name.
John McCall604e7f12009-12-08 07:46:18 +00006471
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006472 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCall7ba107a2009-11-18 02:36:19 +00006473
John McCall604e7f12009-12-08 07:46:18 +00006474 // Unlike most lookups, we don't always want to hide tag
6475 // declarations: tag names are visible through the using declaration
6476 // even if hidden by ordinary names, *except* in a dependent context
6477 // where it's important for the sanity of two-phase lookup.
John McCall7ba107a2009-11-18 02:36:19 +00006478 if (!IsInstantiation)
6479 R.setHideTags(false);
John McCall9488ea12009-11-17 05:59:44 +00006480
John McCalla24dc2e2009-11-17 02:14:36 +00006481 LookupQualifiedName(R, LookupContext);
Mike Stump1eb44332009-09-09 15:08:12 +00006482
John McCallf36e02d2009-10-09 21:13:30 +00006483 if (R.empty()) {
Douglas Gregor3f093272009-10-13 21:16:44 +00006484 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00006485 << NameInfo.getName() << LookupContext << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006486 UD->setInvalidDecl();
6487 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006488 }
6489
John McCalled976492009-12-04 22:46:56 +00006490 if (R.isAmbiguous()) {
6491 UD->setInvalidDecl();
6492 return UD;
6493 }
Mike Stump1eb44332009-09-09 15:08:12 +00006494
John McCall7ba107a2009-11-18 02:36:19 +00006495 if (IsTypeName) {
6496 // If we asked for a typename and got a non-type decl, error out.
John McCalled976492009-12-04 22:46:56 +00006497 if (!R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006498 Diag(IdentLoc, diag::err_using_typename_non_type);
6499 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6500 Diag((*I)->getUnderlyingDecl()->getLocation(),
6501 diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006502 UD->setInvalidDecl();
6503 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006504 }
6505 } else {
6506 // If we asked for a non-typename and we got a type, error out,
6507 // but only if this is an instantiation of an unresolved using
6508 // decl. Otherwise just silently find the type name.
John McCalled976492009-12-04 22:46:56 +00006509 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCall7ba107a2009-11-18 02:36:19 +00006510 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6511 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCalled976492009-12-04 22:46:56 +00006512 UD->setInvalidDecl();
6513 return UD;
John McCall7ba107a2009-11-18 02:36:19 +00006514 }
Anders Carlssoncf9f9212009-08-28 03:16:11 +00006515 }
6516
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006517 // C++0x N2914 [namespace.udecl]p6:
6518 // A using-declaration shall not name a namespace.
John McCalled976492009-12-04 22:46:56 +00006519 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006520 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6521 << SS.getRange();
John McCalled976492009-12-04 22:46:56 +00006522 UD->setInvalidDecl();
6523 return UD;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00006524 }
Mike Stump1eb44332009-09-09 15:08:12 +00006525
John McCall9f54ad42009-12-10 09:41:52 +00006526 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6527 if (!CheckUsingShadowDecl(UD, *I, Previous))
6528 BuildUsingShadowDecl(S, UD, *I);
6529 }
John McCall9488ea12009-11-17 05:59:44 +00006530
6531 return UD;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00006532}
6533
Sebastian Redlf677ea32011-02-05 19:23:19 +00006534/// Additional checks for a using declaration referring to a constructor name.
6535bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6536 if (UD->isTypeName()) {
6537 // FIXME: Cannot specify typename when specifying constructor
6538 return true;
6539 }
6540
Douglas Gregordc355712011-02-25 00:36:19 +00006541 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redlf677ea32011-02-05 19:23:19 +00006542 assert(SourceType &&
6543 "Using decl naming constructor doesn't have type in scope spec.");
6544 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6545
6546 // Check whether the named type is a direct base class.
6547 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6548 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6549 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6550 BaseIt != BaseE; ++BaseIt) {
6551 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6552 if (CanonicalSourceType == BaseType)
6553 break;
6554 }
6555
6556 if (BaseIt == BaseE) {
6557 // Did not find SourceType in the bases.
6558 Diag(UD->getUsingLocation(),
6559 diag::err_using_decl_constructor_not_in_direct_base)
6560 << UD->getNameInfo().getSourceRange()
6561 << QualType(SourceType, 0) << TargetClass;
6562 return true;
6563 }
6564
6565 BaseIt->setInheritConstructors();
6566
6567 return false;
6568}
6569
John McCall9f54ad42009-12-10 09:41:52 +00006570/// Checks that the given using declaration is not an invalid
6571/// redeclaration. Note that this is checking only for the using decl
6572/// itself, not for any ill-formedness among the UsingShadowDecls.
6573bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6574 bool isTypeName,
6575 const CXXScopeSpec &SS,
6576 SourceLocation NameLoc,
6577 const LookupResult &Prev) {
6578 // C++03 [namespace.udecl]p8:
6579 // C++0x [namespace.udecl]p10:
6580 // A using-declaration is a declaration and can therefore be used
6581 // repeatedly where (and only where) multiple declarations are
6582 // allowed.
Douglas Gregora97badf2010-05-06 23:31:27 +00006583 //
John McCall8a726212010-11-29 18:01:58 +00006584 // That's in non-member contexts.
6585 if (!CurContext->getRedeclContext()->isRecord())
John McCall9f54ad42009-12-10 09:41:52 +00006586 return false;
6587
6588 NestedNameSpecifier *Qual
6589 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6590
6591 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6592 NamedDecl *D = *I;
6593
6594 bool DTypename;
6595 NestedNameSpecifier *DQual;
6596 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6597 DTypename = UD->isTypeName();
Douglas Gregordc355712011-02-25 00:36:19 +00006598 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006599 } else if (UnresolvedUsingValueDecl *UD
6600 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6601 DTypename = false;
Douglas Gregordc355712011-02-25 00:36:19 +00006602 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006603 } else if (UnresolvedUsingTypenameDecl *UD
6604 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6605 DTypename = true;
Douglas Gregordc355712011-02-25 00:36:19 +00006606 DQual = UD->getQualifier();
John McCall9f54ad42009-12-10 09:41:52 +00006607 } else continue;
6608
6609 // using decls differ if one says 'typename' and the other doesn't.
6610 // FIXME: non-dependent using decls?
6611 if (isTypeName != DTypename) continue;
6612
6613 // using decls differ if they name different scopes (but note that
6614 // template instantiation can cause this check to trigger when it
6615 // didn't before instantiation).
6616 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6617 Context.getCanonicalNestedNameSpecifier(DQual))
6618 continue;
6619
6620 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCall41ce66f2009-12-10 19:51:03 +00006621 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall9f54ad42009-12-10 09:41:52 +00006622 return true;
6623 }
6624
6625 return false;
6626}
6627
John McCall604e7f12009-12-08 07:46:18 +00006628
John McCalled976492009-12-04 22:46:56 +00006629/// Checks that the given nested-name qualifier used in a using decl
6630/// in the current context is appropriately related to the current
6631/// scope. If an error is found, diagnoses it and returns true.
6632bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6633 const CXXScopeSpec &SS,
6634 SourceLocation NameLoc) {
John McCall604e7f12009-12-08 07:46:18 +00006635 DeclContext *NamedContext = computeDeclContext(SS);
John McCalled976492009-12-04 22:46:56 +00006636
John McCall604e7f12009-12-08 07:46:18 +00006637 if (!CurContext->isRecord()) {
6638 // C++03 [namespace.udecl]p3:
6639 // C++0x [namespace.udecl]p8:
6640 // A using-declaration for a class member shall be a member-declaration.
6641
6642 // If we weren't able to compute a valid scope, it must be a
6643 // dependent class scope.
6644 if (!NamedContext || NamedContext->isRecord()) {
6645 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6646 << SS.getRange();
6647 return true;
6648 }
6649
6650 // Otherwise, everything is known to be fine.
6651 return false;
6652 }
6653
6654 // The current scope is a record.
6655
6656 // If the named context is dependent, we can't decide much.
6657 if (!NamedContext) {
6658 // FIXME: in C++0x, we can diagnose if we can prove that the
6659 // nested-name-specifier does not refer to a base class, which is
6660 // still possible in some cases.
6661
6662 // Otherwise we have to conservatively report that things might be
6663 // okay.
6664 return false;
6665 }
6666
6667 if (!NamedContext->isRecord()) {
6668 // Ideally this would point at the last name in the specifier,
6669 // but we don't have that level of source info.
6670 Diag(SS.getRange().getBegin(),
6671 diag::err_using_decl_nested_name_specifier_is_not_class)
6672 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6673 return true;
6674 }
6675
Douglas Gregor6fb07292010-12-21 07:41:49 +00006676 if (!NamedContext->isDependentContext() &&
6677 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6678 return true;
6679
John McCall604e7f12009-12-08 07:46:18 +00006680 if (getLangOptions().CPlusPlus0x) {
6681 // C++0x [namespace.udecl]p3:
6682 // In a using-declaration used as a member-declaration, the
6683 // nested-name-specifier shall name a base class of the class
6684 // being defined.
6685
6686 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6687 cast<CXXRecordDecl>(NamedContext))) {
6688 if (CurContext == NamedContext) {
6689 Diag(NameLoc,
6690 diag::err_using_decl_nested_name_specifier_is_current_class)
6691 << SS.getRange();
6692 return true;
6693 }
6694
6695 Diag(SS.getRange().getBegin(),
6696 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6697 << (NestedNameSpecifier*) SS.getScopeRep()
6698 << cast<CXXRecordDecl>(CurContext)
6699 << SS.getRange();
6700 return true;
6701 }
6702
6703 return false;
6704 }
6705
6706 // C++03 [namespace.udecl]p4:
6707 // A using-declaration used as a member-declaration shall refer
6708 // to a member of a base class of the class being defined [etc.].
6709
6710 // Salient point: SS doesn't have to name a base class as long as
6711 // lookup only finds members from base classes. Therefore we can
6712 // diagnose here only if we can prove that that can't happen,
6713 // i.e. if the class hierarchies provably don't intersect.
6714
6715 // TODO: it would be nice if "definitely valid" results were cached
6716 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6717 // need to be repeated.
6718
6719 struct UserData {
6720 llvm::DenseSet<const CXXRecordDecl*> Bases;
6721
6722 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6723 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6724 Data->Bases.insert(Base);
6725 return true;
6726 }
6727
6728 bool hasDependentBases(const CXXRecordDecl *Class) {
6729 return !Class->forallBases(collect, this);
6730 }
6731
6732 /// Returns true if the base is dependent or is one of the
6733 /// accumulated base classes.
6734 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6735 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6736 return !Data->Bases.count(Base);
6737 }
6738
6739 bool mightShareBases(const CXXRecordDecl *Class) {
6740 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6741 }
6742 };
6743
6744 UserData Data;
6745
6746 // Returns false if we find a dependent base.
6747 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6748 return false;
6749
6750 // Returns false if the class has a dependent base or if it or one
6751 // of its bases is present in the base set of the current context.
6752 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6753 return false;
6754
6755 Diag(SS.getRange().getBegin(),
6756 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6757 << (NestedNameSpecifier*) SS.getScopeRep()
6758 << cast<CXXRecordDecl>(CurContext)
6759 << SS.getRange();
6760
6761 return true;
John McCalled976492009-12-04 22:46:56 +00006762}
6763
Richard Smith162e1c12011-04-15 14:24:37 +00006764Decl *Sema::ActOnAliasDeclaration(Scope *S,
6765 AccessSpecifier AS,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006766 MultiTemplateParamsArg TemplateParamLists,
Richard Smith162e1c12011-04-15 14:24:37 +00006767 SourceLocation UsingLoc,
6768 UnqualifiedId &Name,
6769 TypeResult Type) {
Richard Smith3e4c6c42011-05-05 21:57:07 +00006770 // Skip up to the relevant declaration scope.
6771 while (S->getFlags() & Scope::TemplateParamScope)
6772 S = S->getParent();
Richard Smith162e1c12011-04-15 14:24:37 +00006773 assert((S->getFlags() & Scope::DeclScope) &&
6774 "got alias-declaration outside of declaration scope");
6775
6776 if (Type.isInvalid())
6777 return 0;
6778
6779 bool Invalid = false;
6780 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6781 TypeSourceInfo *TInfo = 0;
Nick Lewyckyb79bf1d2011-05-02 01:07:19 +00006782 GetTypeFromParser(Type.get(), &TInfo);
Richard Smith162e1c12011-04-15 14:24:37 +00006783
6784 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6785 return 0;
6786
6787 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3e4c6c42011-05-05 21:57:07 +00006788 UPPC_DeclarationType)) {
Richard Smith162e1c12011-04-15 14:24:37 +00006789 Invalid = true;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006790 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6791 TInfo->getTypeLoc().getBeginLoc());
6792 }
Richard Smith162e1c12011-04-15 14:24:37 +00006793
6794 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6795 LookupName(Previous, S);
6796
6797 // Warn about shadowing the name of a template parameter.
6798 if (Previous.isSingleResult() &&
6799 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorcb8f9512011-10-20 17:58:49 +00006800 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smith162e1c12011-04-15 14:24:37 +00006801 Previous.clear();
6802 }
6803
6804 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6805 "name in alias declaration must be an identifier");
6806 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6807 Name.StartLocation,
6808 Name.Identifier, TInfo);
6809
6810 NewTD->setAccess(AS);
6811
6812 if (Invalid)
6813 NewTD->setInvalidDecl();
6814
Richard Smith3e4c6c42011-05-05 21:57:07 +00006815 CheckTypedefForVariablyModifiedType(S, NewTD);
6816 Invalid |= NewTD->isInvalidDecl();
6817
Richard Smith162e1c12011-04-15 14:24:37 +00006818 bool Redeclaration = false;
Richard Smith3e4c6c42011-05-05 21:57:07 +00006819
6820 NamedDecl *NewND;
6821 if (TemplateParamLists.size()) {
6822 TypeAliasTemplateDecl *OldDecl = 0;
6823 TemplateParameterList *OldTemplateParams = 0;
6824
6825 if (TemplateParamLists.size() != 1) {
6826 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6827 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6828 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6829 }
6830 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6831
6832 // Only consider previous declarations in the same scope.
6833 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6834 /*ExplicitInstantiationOrSpecialization*/false);
6835 if (!Previous.empty()) {
6836 Redeclaration = true;
6837
6838 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6839 if (!OldDecl && !Invalid) {
6840 Diag(UsingLoc, diag::err_redefinition_different_kind)
6841 << Name.Identifier;
6842
6843 NamedDecl *OldD = Previous.getRepresentativeDecl();
6844 if (OldD->getLocation().isValid())
6845 Diag(OldD->getLocation(), diag::note_previous_definition);
6846
6847 Invalid = true;
6848 }
6849
6850 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6851 if (TemplateParameterListsAreEqual(TemplateParams,
6852 OldDecl->getTemplateParameters(),
6853 /*Complain=*/true,
6854 TPL_TemplateMatch))
6855 OldTemplateParams = OldDecl->getTemplateParameters();
6856 else
6857 Invalid = true;
6858
6859 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6860 if (!Invalid &&
6861 !Context.hasSameType(OldTD->getUnderlyingType(),
6862 NewTD->getUnderlyingType())) {
6863 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6864 // but we can't reasonably accept it.
6865 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6866 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6867 if (OldTD->getLocation().isValid())
6868 Diag(OldTD->getLocation(), diag::note_previous_definition);
6869 Invalid = true;
6870 }
6871 }
6872 }
6873
6874 // Merge any previous default template arguments into our parameters,
6875 // and check the parameter list.
6876 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6877 TPC_TypeAliasTemplate))
6878 return 0;
6879
6880 TypeAliasTemplateDecl *NewDecl =
6881 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6882 Name.Identifier, TemplateParams,
6883 NewTD);
6884
6885 NewDecl->setAccess(AS);
6886
6887 if (Invalid)
6888 NewDecl->setInvalidDecl();
6889 else if (OldDecl)
6890 NewDecl->setPreviousDeclaration(OldDecl);
6891
6892 NewND = NewDecl;
6893 } else {
6894 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6895 NewND = NewTD;
6896 }
Richard Smith162e1c12011-04-15 14:24:37 +00006897
6898 if (!Redeclaration)
Richard Smith3e4c6c42011-05-05 21:57:07 +00006899 PushOnScopeChains(NewND, S);
Richard Smith162e1c12011-04-15 14:24:37 +00006900
Richard Smith3e4c6c42011-05-05 21:57:07 +00006901 return NewND;
Richard Smith162e1c12011-04-15 14:24:37 +00006902}
6903
John McCalld226f652010-08-21 09:40:31 +00006904Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006905 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00006906 SourceLocation AliasLoc,
6907 IdentifierInfo *Alias,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00006908 CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00006909 SourceLocation IdentLoc,
6910 IdentifierInfo *Ident) {
Mike Stump1eb44332009-09-09 15:08:12 +00006911
Anders Carlsson81c85c42009-03-28 23:53:49 +00006912 // Lookup the namespace name.
John McCalla24dc2e2009-11-17 02:14:36 +00006913 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6914 LookupParsedName(R, S, &SS);
Anders Carlsson81c85c42009-03-28 23:53:49 +00006915
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006916 // Check if we have a previous declaration with the same name.
Douglas Gregorae374752010-05-03 15:37:31 +00006917 NamedDecl *PrevDecl
6918 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6919 ForRedeclaration);
6920 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6921 PrevDecl = 0;
6922
6923 if (PrevDecl) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00006924 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006925 // We already have an alias with the same name that points to the same
Anders Carlsson81c85c42009-03-28 23:53:49 +00006926 // namespace, so don't create a new one.
Douglas Gregorc67b0322010-03-26 22:59:39 +00006927 // FIXME: At some point, we'll want to create the (redundant)
6928 // declaration to maintain better source information.
John McCallf36e02d2009-10-09 21:13:30 +00006929 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregorc67b0322010-03-26 22:59:39 +00006930 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCalld226f652010-08-21 09:40:31 +00006931 return 0;
Anders Carlsson81c85c42009-03-28 23:53:49 +00006932 }
Mike Stump1eb44332009-09-09 15:08:12 +00006933
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006934 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6935 diag::err_redefinition_different_kind;
6936 Diag(AliasLoc, DiagID) << Alias;
6937 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCalld226f652010-08-21 09:40:31 +00006938 return 0;
Anders Carlsson8d7ba402009-03-28 06:23:46 +00006939 }
6940
John McCalla24dc2e2009-11-17 02:14:36 +00006941 if (R.isAmbiguous())
John McCalld226f652010-08-21 09:40:31 +00006942 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00006943
John McCallf36e02d2009-10-09 21:13:30 +00006944 if (R.empty()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00006945 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006946 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCalld226f652010-08-21 09:40:31 +00006947 return 0;
Douglas Gregor0e8c4b92010-06-29 18:55:19 +00006948 }
Anders Carlsson5721c682009-03-28 06:42:02 +00006949 }
Mike Stump1eb44332009-09-09 15:08:12 +00006950
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00006951 NamespaceAliasDecl *AliasDecl =
Mike Stump1eb44332009-09-09 15:08:12 +00006952 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +00006953 Alias, SS.getWithLocInContext(Context),
John McCallf36e02d2009-10-09 21:13:30 +00006954 IdentLoc, R.getFoundDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006955
John McCall3dbd3d52010-02-16 06:53:13 +00006956 PushOnScopeChains(AliasDecl, S);
John McCalld226f652010-08-21 09:40:31 +00006957 return AliasDecl;
Anders Carlssondbb00942009-03-28 05:27:17 +00006958}
6959
Douglas Gregor39957dc2010-05-01 15:04:51 +00006960namespace {
6961 /// \brief Scoped object used to handle the state changes required in Sema
6962 /// to implicitly define the body of a C++ member function;
6963 class ImplicitlyDefinedFunctionScope {
6964 Sema &S;
John McCalleee1d542011-02-14 07:13:47 +00006965 Sema::ContextRAII SavedContext;
Douglas Gregor39957dc2010-05-01 15:04:51 +00006966
6967 public:
6968 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCalleee1d542011-02-14 07:13:47 +00006969 : S(S), SavedContext(S, Method)
Douglas Gregor39957dc2010-05-01 15:04:51 +00006970 {
Douglas Gregor39957dc2010-05-01 15:04:51 +00006971 S.PushFunctionScope();
6972 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6973 }
6974
6975 ~ImplicitlyDefinedFunctionScope() {
6976 S.PopExpressionEvaluationContext();
Eli Friedmanec9ea722012-01-05 03:35:19 +00006977 S.PopFunctionScopeInfo();
Douglas Gregor39957dc2010-05-01 15:04:51 +00006978 }
6979 };
6980}
6981
Sean Hunt001cad92011-05-10 00:49:42 +00006982Sema::ImplicitExceptionSpecification
6983Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006984 // C++ [except.spec]p14:
6985 // An implicitly declared special member function (Clause 12) shall have an
6986 // exception-specification. [...]
6987 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00006988 if (ClassDecl->isInvalidDecl())
6989 return ExceptSpec;
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006990
Sebastian Redl60618fa2011-03-12 11:50:43 +00006991 // Direct base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00006992 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6993 BEnd = ClassDecl->bases_end();
6994 B != BEnd; ++B) {
6995 if (B->isVirtual()) // Handled below.
6996 continue;
6997
Douglas Gregor18274032010-07-03 00:47:00 +00006998 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6999 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007000 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7001 // If this is a deleted function, add it anyway. This might be conformant
7002 // with the standard. This might not. I'm not sure. It might not matter.
7003 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007004 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007005 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007006 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007007
7008 // Virtual base-class constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007009 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7010 BEnd = ClassDecl->vbases_end();
7011 B != BEnd; ++B) {
Douglas Gregor18274032010-07-03 00:47:00 +00007012 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7013 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00007014 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7015 // If this is a deleted function, add it anyway. This might be conformant
7016 // with the standard. This might not. I'm not sure. It might not matter.
7017 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007018 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007019 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007020 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007021
7022 // Field constructors.
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007023 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7024 FEnd = ClassDecl->field_end();
7025 F != FEnd; ++F) {
Richard Smith7a614d82011-06-11 17:19:42 +00007026 if (F->hasInClassInitializer()) {
7027 if (Expr *E = F->getInClassInitializer())
7028 ExceptSpec.CalledExpr(E);
7029 else if (!F->isInvalidDecl())
7030 ExceptSpec.SetDelayed();
7031 } else if (const RecordType *RecordTy
Douglas Gregor18274032010-07-03 00:47:00 +00007032 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Sean Huntb320e0c2011-06-10 03:50:41 +00007033 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7034 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7035 // If this is a deleted function, add it anyway. This might be conformant
7036 // with the standard. This might not. I'm not sure. It might not matter.
7037 // In particular, the problem is that this function never gets called. It
7038 // might just be ill-formed because this function attempts to refer to
7039 // a deleted function here.
7040 if (Constructor)
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007041 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor18274032010-07-03 00:47:00 +00007042 }
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007043 }
John McCalle23cf432010-12-14 08:05:40 +00007044
Sean Hunt001cad92011-05-10 00:49:42 +00007045 return ExceptSpec;
7046}
7047
7048CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7049 CXXRecordDecl *ClassDecl) {
7050 // C++ [class.ctor]p5:
7051 // A default constructor for a class X is a constructor of class X
7052 // that can be called without an argument. If there is no
7053 // user-declared constructor for class X, a default constructor is
7054 // implicitly declared. An implicitly-declared default constructor
7055 // is an inline public member of its class.
7056 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7057 "Should not build implicit default constructor!");
7058
7059 ImplicitExceptionSpecification Spec =
7060 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7061 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl8b5b4092011-03-06 10:52:04 +00007062
Douglas Gregoreb8c6702010-07-01 22:31:05 +00007063 // Create the actual constructor declaration.
Douglas Gregor32df23e2010-07-01 22:02:46 +00007064 CanQualType ClassType
7065 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007066 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007067 DeclarationName Name
7068 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007069 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smith61802452011-12-22 02:22:31 +00007070 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7071 Context, ClassDecl, ClassLoc, NameInfo,
7072 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7073 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7074 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7075 getLangOptions().CPlusPlus0x);
Douglas Gregor32df23e2010-07-01 22:02:46 +00007076 DefaultCon->setAccess(AS_public);
Sean Hunt1e238652011-05-12 03:51:51 +00007077 DefaultCon->setDefaulted();
Douglas Gregor32df23e2010-07-01 22:02:46 +00007078 DefaultCon->setImplicit();
Sean Hunt023df372011-05-09 18:22:59 +00007079 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor18274032010-07-03 00:47:00 +00007080
7081 // Note that we have declared this constructor.
Douglas Gregor18274032010-07-03 00:47:00 +00007082 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7083
Douglas Gregor23c94db2010-07-02 17:43:08 +00007084 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor18274032010-07-03 00:47:00 +00007085 PushOnScopeChains(DefaultCon, S, false);
7086 ClassDecl->addDecl(DefaultCon);
Sean Hunt71a682f2011-05-18 03:41:58 +00007087
Sean Hunte16da072011-10-10 06:18:57 +00007088 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00007089 DefaultCon->setDeletedAsWritten();
Douglas Gregor18274032010-07-03 00:47:00 +00007090
Douglas Gregor32df23e2010-07-01 22:02:46 +00007091 return DefaultCon;
7092}
7093
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007094void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7095 CXXConstructorDecl *Constructor) {
Sean Hunt1e238652011-05-12 03:51:51 +00007096 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007097 !Constructor->doesThisDeclarationHaveABody() &&
7098 !Constructor->isDeleted()) &&
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007099 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00007100
Anders Carlssonf6513ed2010-04-23 16:04:08 +00007101 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman80c30da2009-11-09 19:20:36 +00007102 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedman49c16da2009-11-09 01:05:47 +00007103
Douglas Gregor39957dc2010-05-01 15:04:51 +00007104 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007105 DiagnosticErrorTrap Trap(Diags);
Sean Huntcbb67482011-01-08 20:30:50 +00007106 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007107 Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007108 Diag(CurrentLocation, diag::note_member_synthesized_at)
Sean Huntf961ea52011-05-10 19:08:14 +00007109 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman80c30da2009-11-09 19:20:36 +00007110 Constructor->setInvalidDecl();
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007111 return;
Eli Friedman80c30da2009-11-09 19:20:36 +00007112 }
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007113
7114 SourceLocation Loc = Constructor->getLocation();
7115 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7116
7117 Constructor->setUsed();
7118 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007119
7120 if (ASTMutationListener *L = getASTMutationListener()) {
7121 L->CompletedImplicitDefinition(Constructor);
7122 }
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00007123}
7124
Richard Smith7a614d82011-06-11 17:19:42 +00007125/// Get any existing defaulted default constructor for the given class. Do not
7126/// implicitly define one if it does not exist.
7127static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7128 CXXRecordDecl *D) {
7129 ASTContext &Context = Self.Context;
7130 QualType ClassType = Context.getTypeDeclType(D);
7131 DeclarationName ConstructorName
7132 = Context.DeclarationNames.getCXXConstructorName(
7133 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7134
7135 DeclContext::lookup_const_iterator Con, ConEnd;
7136 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7137 Con != ConEnd; ++Con) {
7138 // A function template cannot be defaulted.
7139 if (isa<FunctionTemplateDecl>(*Con))
7140 continue;
7141
7142 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7143 if (Constructor->isDefaultConstructor())
7144 return Constructor->isDefaulted() ? Constructor : 0;
7145 }
7146 return 0;
7147}
7148
7149void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7150 if (!D) return;
7151 AdjustDeclIfTemplate(D);
7152
7153 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7154 CXXConstructorDecl *CtorDecl
7155 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7156
7157 if (!CtorDecl) return;
7158
7159 // Compute the exception specification for the default constructor.
7160 const FunctionProtoType *CtorTy =
7161 CtorDecl->getType()->castAs<FunctionProtoType>();
7162 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7163 ImplicitExceptionSpecification Spec =
7164 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7165 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7166 assert(EPI.ExceptionSpecType != EST_Delayed);
7167
7168 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7169 }
7170
7171 // If the default constructor is explicitly defaulted, checking the exception
7172 // specification is deferred until now.
7173 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7174 !ClassDecl->isDependentType())
7175 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7176}
7177
Sebastian Redlf677ea32011-02-05 19:23:19 +00007178void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7179 // We start with an initial pass over the base classes to collect those that
7180 // inherit constructors from. If there are none, we can forgo all further
7181 // processing.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007182 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007183 BasesVector BasesToInheritFrom;
7184 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7185 BaseE = ClassDecl->bases_end();
7186 BaseIt != BaseE; ++BaseIt) {
7187 if (BaseIt->getInheritConstructors()) {
7188 QualType Base = BaseIt->getType();
7189 if (Base->isDependentType()) {
7190 // If we inherit constructors from anything that is dependent, just
7191 // abort processing altogether. We'll get another chance for the
7192 // instantiations.
7193 return;
7194 }
7195 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7196 }
7197 }
7198 if (BasesToInheritFrom.empty())
7199 return;
7200
7201 // Now collect the constructors that we already have in the current class.
7202 // Those take precedence over inherited constructors.
7203 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7204 // unless there is a user-declared constructor with the same signature in
7205 // the class where the using-declaration appears.
7206 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7207 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7208 CtorE = ClassDecl->ctor_end();
7209 CtorIt != CtorE; ++CtorIt) {
7210 ExistingConstructors.insert(
7211 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7212 }
7213
7214 Scope *S = getScopeForContext(ClassDecl);
7215 DeclarationName CreatedCtorName =
7216 Context.DeclarationNames.getCXXConstructorName(
7217 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7218
7219 // Now comes the true work.
7220 // First, we keep a map from constructor types to the base that introduced
7221 // them. Needed for finding conflicting constructors. We also keep the
7222 // actually inserted declarations in there, for pretty diagnostics.
7223 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7224 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7225 ConstructorToSourceMap InheritedConstructors;
7226 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7227 BaseE = BasesToInheritFrom.end();
7228 BaseIt != BaseE; ++BaseIt) {
7229 const RecordType *Base = *BaseIt;
7230 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7231 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7232 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7233 CtorE = BaseDecl->ctor_end();
7234 CtorIt != CtorE; ++CtorIt) {
7235 // Find the using declaration for inheriting this base's constructors.
7236 DeclarationName Name =
7237 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7238 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7239 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7240 SourceLocation UsingLoc = UD ? UD->getLocation() :
7241 ClassDecl->getLocation();
7242
7243 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7244 // from the class X named in the using-declaration consists of actual
7245 // constructors and notional constructors that result from the
7246 // transformation of defaulted parameters as follows:
7247 // - all non-template default constructors of X, and
7248 // - for each non-template constructor of X that has at least one
7249 // parameter with a default argument, the set of constructors that
7250 // results from omitting any ellipsis parameter specification and
7251 // successively omitting parameters with a default argument from the
7252 // end of the parameter-type-list.
7253 CXXConstructorDecl *BaseCtor = *CtorIt;
7254 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7255 const FunctionProtoType *BaseCtorType =
7256 BaseCtor->getType()->getAs<FunctionProtoType>();
7257
7258 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7259 maxParams = BaseCtor->getNumParams();
7260 params <= maxParams; ++params) {
7261 // Skip default constructors. They're never inherited.
7262 if (params == 0)
7263 continue;
7264 // Skip copy and move constructors for the same reason.
7265 if (CanBeCopyOrMove && params == 1)
7266 continue;
7267
7268 // Build up a function type for this particular constructor.
7269 // FIXME: The working paper does not consider that the exception spec
7270 // for the inheriting constructor might be larger than that of the
Richard Smith7a614d82011-06-11 17:19:42 +00007271 // source. This code doesn't yet, either. When it does, this code will
7272 // need to be delayed until after exception specifications and in-class
7273 // member initializers are attached.
Sebastian Redlf677ea32011-02-05 19:23:19 +00007274 const Type *NewCtorType;
7275 if (params == maxParams)
7276 NewCtorType = BaseCtorType;
7277 else {
Chris Lattner5f9e2722011-07-23 10:55:15 +00007278 SmallVector<QualType, 16> Args;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007279 for (unsigned i = 0; i < params; ++i) {
7280 Args.push_back(BaseCtorType->getArgType(i));
7281 }
7282 FunctionProtoType::ExtProtoInfo ExtInfo =
7283 BaseCtorType->getExtProtoInfo();
7284 ExtInfo.Variadic = false;
7285 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7286 Args.data(), params, ExtInfo)
7287 .getTypePtr();
7288 }
7289 const Type *CanonicalNewCtorType =
7290 Context.getCanonicalType(NewCtorType);
7291
7292 // Now that we have the type, first check if the class already has a
7293 // constructor with this signature.
7294 if (ExistingConstructors.count(CanonicalNewCtorType))
7295 continue;
7296
7297 // Then we check if we have already declared an inherited constructor
7298 // with this signature.
7299 std::pair<ConstructorToSourceMap::iterator, bool> result =
7300 InheritedConstructors.insert(std::make_pair(
7301 CanonicalNewCtorType,
7302 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7303 if (!result.second) {
7304 // Already in the map. If it came from a different class, that's an
7305 // error. Not if it's from the same.
7306 CanQualType PreviousBase = result.first->second.first;
7307 if (CanonicalBase != PreviousBase) {
7308 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7309 const CXXConstructorDecl *PrevBaseCtor =
7310 PrevCtor->getInheritedConstructor();
7311 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7312
7313 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7314 Diag(BaseCtor->getLocation(),
7315 diag::note_using_decl_constructor_conflict_current_ctor);
7316 Diag(PrevBaseCtor->getLocation(),
7317 diag::note_using_decl_constructor_conflict_previous_ctor);
7318 Diag(PrevCtor->getLocation(),
7319 diag::note_using_decl_constructor_conflict_previous_using);
7320 }
7321 continue;
7322 }
7323
7324 // OK, we're there, now add the constructor.
7325 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007326 // user-written inline constructor [...]
Sebastian Redlf677ea32011-02-05 19:23:19 +00007327 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7328 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007329 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7330 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007331 /*ImplicitlyDeclared=*/true,
7332 // FIXME: Due to a defect in the standard, we treat inherited
7333 // constructors as constexpr even if that makes them ill-formed.
7334 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redlf677ea32011-02-05 19:23:19 +00007335 NewCtor->setAccess(BaseCtor->getAccess());
7336
7337 // Build up the parameter decls and add them.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007338 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007339 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007340 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7341 UsingLoc, UsingLoc,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007342 /*IdentifierInfo=*/0,
7343 BaseCtorType->getArgType(i),
7344 /*TInfo=*/0, SC_None,
7345 SC_None, /*DefaultArg=*/0));
7346 }
David Blaikie4278c652011-09-21 18:16:56 +00007347 NewCtor->setParams(ParamDecls);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007348 NewCtor->setInheritedConstructor(BaseCtor);
7349
7350 PushOnScopeChains(NewCtor, S, false);
7351 ClassDecl->addDecl(NewCtor);
7352 result.first->second.second = NewCtor;
7353 }
7354 }
7355 }
7356}
7357
Sean Huntcb45a0f2011-05-12 22:46:25 +00007358Sema::ImplicitExceptionSpecification
7359Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007360 // C++ [except.spec]p14:
7361 // An implicitly declared special member function (Clause 12) shall have
7362 // an exception-specification.
7363 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007364 if (ClassDecl->isInvalidDecl())
7365 return ExceptSpec;
7366
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007367 // Direct base-class destructors.
7368 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7369 BEnd = ClassDecl->bases_end();
7370 B != BEnd; ++B) {
7371 if (B->isVirtual()) // Handled below.
7372 continue;
7373
7374 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7375 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007376 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007377 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007378
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007379 // Virtual base-class destructors.
7380 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7381 BEnd = ClassDecl->vbases_end();
7382 B != BEnd; ++B) {
7383 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7384 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007385 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007386 }
Sebastian Redl0ee33912011-05-19 05:13:44 +00007387
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007388 // Field destructors.
7389 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7390 FEnd = ClassDecl->field_end();
7391 F != FEnd; ++F) {
7392 if (const RecordType *RecordTy
7393 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7394 ExceptSpec.CalledDecl(
Sebastian Redl0ee33912011-05-19 05:13:44 +00007395 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007396 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007397
Sean Huntcb45a0f2011-05-12 22:46:25 +00007398 return ExceptSpec;
7399}
7400
7401CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7402 // C++ [class.dtor]p2:
7403 // If a class has no user-declared destructor, a destructor is
7404 // declared implicitly. An implicitly-declared destructor is an
7405 // inline public member of its class.
7406
7407 ImplicitExceptionSpecification Spec =
Sebastian Redl0ee33912011-05-19 05:13:44 +00007408 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007409 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7410
Douglas Gregor4923aa22010-07-02 20:37:36 +00007411 // Create the actual destructor declaration.
John McCalle23cf432010-12-14 08:05:40 +00007412 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redl60618fa2011-03-12 11:50:43 +00007413
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007414 CanQualType ClassType
7415 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007416 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007417 DeclarationName Name
7418 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007419 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007420 CXXDestructorDecl *Destructor
Sebastian Redl60618fa2011-03-12 11:50:43 +00007421 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7422 /*isInline=*/true,
7423 /*isImplicitlyDeclared=*/true);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007424 Destructor->setAccess(AS_public);
Sean Huntcb45a0f2011-05-12 22:46:25 +00007425 Destructor->setDefaulted();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007426 Destructor->setImplicit();
7427 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor4923aa22010-07-02 20:37:36 +00007428
7429 // Note that we have declared this destructor.
Douglas Gregor4923aa22010-07-02 20:37:36 +00007430 ++ASTContext::NumImplicitDestructorsDeclared;
7431
7432 // Introduce this destructor into its scope.
Douglas Gregor23c94db2010-07-02 17:43:08 +00007433 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor4923aa22010-07-02 20:37:36 +00007434 PushOnScopeChains(Destructor, S, false);
7435 ClassDecl->addDecl(Destructor);
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007436
7437 // This could be uniqued if it ever proves significant.
7438 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Sean Huntcb45a0f2011-05-12 22:46:25 +00007439
7440 if (ShouldDeleteDestructor(Destructor))
7441 Destructor->setDeletedAsWritten();
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007442
7443 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor4923aa22010-07-02 20:37:36 +00007444
Douglas Gregorfabd43a2010-07-01 19:09:28 +00007445 return Destructor;
7446}
7447
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007448void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregor4fe95f92009-09-04 19:04:08 +00007449 CXXDestructorDecl *Destructor) {
Sean Huntcd10dec2011-05-23 23:14:04 +00007450 assert((Destructor->isDefaulted() &&
7451 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007452 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson6d701392009-11-15 22:49:34 +00007453 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007454 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007455
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007456 if (Destructor->isInvalidDecl())
7457 return;
7458
Douglas Gregor39957dc2010-05-01 15:04:51 +00007459 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00007460
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007461 DiagnosticErrorTrap Trap(Diags);
John McCallef027fe2010-03-16 21:39:52 +00007462 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7463 Destructor->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +00007464
Douglas Gregorc63d2c82010-05-12 16:39:35 +00007465 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson37909802009-11-30 21:24:50 +00007466 Diag(CurrentLocation, diag::note_member_synthesized_at)
7467 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7468
7469 Destructor->setInvalidDecl();
7470 return;
7471 }
7472
Douglas Gregor4ada9d32010-09-20 16:48:21 +00007473 SourceLocation Loc = Destructor->getLocation();
7474 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregor690b2db2011-09-22 20:32:43 +00007475 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007476 Destructor->setUsed();
Douglas Gregor6fb745b2010-05-13 16:44:06 +00007477 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redl58a2cd82011-04-24 16:28:06 +00007478
7479 if (ASTMutationListener *L = getASTMutationListener()) {
7480 L->CompletedImplicitDefinition(Destructor);
7481 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007482}
7483
Sebastian Redl0ee33912011-05-19 05:13:44 +00007484void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7485 CXXDestructorDecl *destructor) {
7486 // C++11 [class.dtor]p3:
7487 // A declaration of a destructor that does not have an exception-
7488 // specification is implicitly considered to have the same exception-
7489 // specification as an implicit declaration.
7490 const FunctionProtoType *dtorType = destructor->getType()->
7491 getAs<FunctionProtoType>();
7492 if (dtorType->hasExceptionSpec())
7493 return;
7494
7495 ImplicitExceptionSpecification exceptSpec =
7496 ComputeDefaultedDtorExceptionSpec(classDecl);
7497
Chandler Carruth3f224b22011-09-20 04:55:26 +00007498 // Replace the destructor's type, building off the existing one. Fortunately,
7499 // the only thing of interest in the destructor type is its extended info.
7500 // The return and arguments are fixed.
7501 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl0ee33912011-05-19 05:13:44 +00007502 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7503 epi.NumExceptions = exceptSpec.size();
7504 epi.Exceptions = exceptSpec.data();
7505 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7506
7507 destructor->setType(ty);
7508
7509 // FIXME: If the destructor has a body that could throw, and the newly created
7510 // spec doesn't allow exceptions, we should emit a warning, because this
7511 // change in behavior can break conforming C++03 programs at runtime.
7512 // However, we don't have a body yet, so it needs to be done somewhere else.
7513}
7514
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007515/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregor06a9f362010-05-01 20:49:11 +00007516/// \c To.
7517///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007518/// This routine is used to copy/move the members of a class with an
7519/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregor06a9f362010-05-01 20:49:11 +00007520/// copied are arrays, this routine builds for loops to copy them.
7521///
7522/// \param S The Sema object used for type-checking.
7523///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007524/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007525///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007526/// \param T The type of the expressions being copied/moved. Both expressions
7527/// must have this type.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007528///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007529/// \param To The expression we are copying/moving to.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007530///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007531/// \param From The expression we are copying/moving from.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007532///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007533/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007534/// Otherwise, it's a non-static member subobject.
7535///
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007536/// \param Copying Whether we're copying or moving.
7537///
Douglas Gregor06a9f362010-05-01 20:49:11 +00007538/// \param Depth Internal parameter recording the depth of the recursion.
7539///
7540/// \returns A statement or a loop that copies the expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00007541static StmtResult
Douglas Gregor06a9f362010-05-01 20:49:11 +00007542BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCall9ae2f072010-08-23 23:25:46 +00007543 Expr *To, Expr *From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007544 bool CopyingBaseSubobject, bool Copying,
7545 unsigned Depth = 0) {
7546 // C++0x [class.copy]p28:
Douglas Gregor06a9f362010-05-01 20:49:11 +00007547 // Each subobject is assigned in the manner appropriate to its type:
7548 //
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007549 // - if the subobject is of class type, as if by a call to operator= with
7550 // the subobject as the object expression and the corresponding
7551 // subobject of x as a single function argument (as if by explicit
7552 // qualification; that is, ignoring any possible virtual overriding
7553 // functions in more derived classes);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007554 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7555 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7556
7557 // Look for operator=.
7558 DeclarationName Name
7559 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7560 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7561 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7562
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007563 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregor06a9f362010-05-01 20:49:11 +00007564 LookupResult::Filter F = OpLookup.makeFilter();
7565 while (F.hasNext()) {
7566 NamedDecl *D = F.next();
7567 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007568 if (Copying ? Method->isCopyAssignmentOperator() :
7569 Method->isMoveAssignmentOperator())
Douglas Gregor06a9f362010-05-01 20:49:11 +00007570 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007571
Douglas Gregor06a9f362010-05-01 20:49:11 +00007572 F.erase();
John McCallb0207482010-03-16 06:11:48 +00007573 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007574 F.done();
7575
Douglas Gregor6cdc1612010-05-04 15:20:55 +00007576 // Suppress the protected check (C++ [class.protected]) for each of the
7577 // assignment operators we found. This strange dance is required when
7578 // we're assigning via a base classes's copy-assignment operator. To
7579 // ensure that we're getting the right base class subobject (without
7580 // ambiguities), we need to cast "this" to that subobject type; to
7581 // ensure that we don't go through the virtual call mechanism, we need
7582 // to qualify the operator= name with the base class (see below). However,
7583 // this means that if the base class has a protected copy assignment
7584 // operator, the protected member access check will fail. So, we
7585 // rewrite "protected" access to "public" access in this case, since we
7586 // know by construction that we're calling from a derived class.
7587 if (CopyingBaseSubobject) {
7588 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7589 L != LEnd; ++L) {
7590 if (L.getAccess() == AS_protected)
7591 L.setAccess(AS_public);
7592 }
7593 }
7594
Douglas Gregor06a9f362010-05-01 20:49:11 +00007595 // Create the nested-name-specifier that will be used to qualify the
7596 // reference to operator=; this is required to suppress the virtual
7597 // call mechanism.
7598 CXXScopeSpec SS;
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007599 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregorc34348a2011-02-24 17:54:50 +00007600 SS.MakeTrivial(S.Context,
7601 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimek5b6a3dd2012-02-06 21:51:39 +00007602 CanonicalT),
Douglas Gregorc34348a2011-02-24 17:54:50 +00007603 Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007604
7605 // Create the reference to operator=.
John McCall60d7b3a2010-08-24 06:29:42 +00007606 ExprResult OpEqualRef
John McCall9ae2f072010-08-23 23:25:46 +00007607 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00007608 /*TemplateKWLoc=*/SourceLocation(),
7609 /*FirstQualifierInScope=*/0,
7610 OpLookup,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007611 /*TemplateArgs=*/0,
7612 /*SuppressQualifierCheck=*/true);
7613 if (OpEqualRef.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007614 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007615
7616 // Build the call to the assignment operator.
John McCall9ae2f072010-08-23 23:25:46 +00007617
John McCall60d7b3a2010-08-24 06:29:42 +00007618 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregora1a04782010-09-09 16:33:13 +00007619 OpEqualRef.takeAs<Expr>(),
7620 Loc, &From, 1, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007621 if (Call.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007622 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007623
7624 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007625 }
John McCallb0207482010-03-16 06:11:48 +00007626
Douglas Gregor06a9f362010-05-01 20:49:11 +00007627 // - if the subobject is of scalar type, the built-in assignment
7628 // operator is used.
7629 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7630 if (!ArrayTy) {
John McCall2de56d12010-08-25 11:45:40 +00007631 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007632 if (Assignment.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007633 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007634
7635 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007636 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00007637
7638 // - if the subobject is an array, each element is assigned, in the
7639 // manner appropriate to the element type;
7640
7641 // Construct a loop over the array bounds, e.g.,
7642 //
7643 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7644 //
7645 // that will copy each of the array elements.
7646 QualType SizeType = S.Context.getSizeType();
7647
7648 // Create the iteration variable.
7649 IdentifierInfo *IterationVarName = 0;
7650 {
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00007651 SmallString<8> Str;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007652 llvm::raw_svector_ostream OS(Str);
7653 OS << "__i" << Depth;
7654 IterationVarName = &S.Context.Idents.get(OS.str());
7655 }
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007656 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007657 IterationVarName, SizeType,
7658 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCalld931b082010-08-26 03:08:43 +00007659 SC_None, SC_None);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007660
7661 // Initialize the iteration variable to zero.
7662 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007663 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregor06a9f362010-05-01 20:49:11 +00007664
7665 // Create a reference to the iteration variable; we'll use this several
7666 // times throughout.
7667 Expr *IterationVarRef
Eli Friedman8c382062012-01-23 02:35:22 +00007668 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007669 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman8c382062012-01-23 02:35:22 +00007670 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7671 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7672
Douglas Gregor06a9f362010-05-01 20:49:11 +00007673 // Create the DeclStmt that holds the iteration variable.
7674 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7675
7676 // Create the comparison against the array bound.
Jay Foad9f71a8f2010-12-07 08:25:34 +00007677 llvm::APInt Upper
7678 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCall9ae2f072010-08-23 23:25:46 +00007679 Expr *Comparison
Eli Friedman8c382062012-01-23 02:35:22 +00007680 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCallf89e55a2010-11-18 06:31:45 +00007681 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7682 BO_NE, S.Context.BoolTy,
7683 VK_RValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007684
7685 // Create the pre-increment of the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007686 Expr *Increment
John McCallf89e55a2010-11-18 06:31:45 +00007687 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7688 VK_LValue, OK_Ordinary, Loc);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007689
7690 // Subscript the "from" and "to" expressions with the iteration variable.
John McCall9ae2f072010-08-23 23:25:46 +00007691 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007692 IterationVarRefRVal,
7693 Loc));
John McCall9ae2f072010-08-23 23:25:46 +00007694 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman8c382062012-01-23 02:35:22 +00007695 IterationVarRefRVal,
7696 Loc));
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007697 if (!Copying) // Cast to rvalue
7698 From = CastForMoving(S, From);
7699
7700 // Build the copy/move for an individual element of the array.
John McCallf89e55a2010-11-18 06:31:45 +00007701 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7702 To, From, CopyingBaseSubobject,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007703 Copying, Depth + 1);
Douglas Gregorff331c12010-07-25 18:17:45 +00007704 if (Copy.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007705 return StmtError();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007706
7707 // Construct the loop that copies all elements of this array.
John McCall9ae2f072010-08-23 23:25:46 +00007708 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregor06a9f362010-05-01 20:49:11 +00007709 S.MakeFullExpr(Comparison),
John McCalld226f652010-08-21 09:40:31 +00007710 0, S.MakeFullExpr(Increment),
John McCall9ae2f072010-08-23 23:25:46 +00007711 Loc, Copy.take());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007712}
7713
Sean Hunt30de05c2011-05-14 05:23:20 +00007714std::pair<Sema::ImplicitExceptionSpecification, bool>
7715Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7716 CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007717 if (ClassDecl->isInvalidDecl())
7718 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7719
Douglas Gregord3c35902010-07-01 16:36:15 +00007720 // C++ [class.copy]p10:
7721 // If the class definition does not explicitly declare a copy
7722 // assignment operator, one is declared implicitly.
7723 // The implicitly-defined copy assignment operator for a class X
7724 // will have the form
7725 //
7726 // X& X::operator=(const X&)
7727 //
7728 // if
7729 bool HasConstCopyAssignment = true;
7730
7731 // -- each direct base class B of X has a copy assignment operator
7732 // whose parameter is of type const B&, const volatile B& or B,
7733 // and
7734 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7735 BaseEnd = ClassDecl->bases_end();
7736 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007737 // We'll handle this below
7738 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7739 continue;
7740
Douglas Gregord3c35902010-07-01 16:36:15 +00007741 assert(!Base->getType()->isDependentType() &&
7742 "Cannot generate implicit members for class with dependent bases.");
Sean Hunt661c67a2011-06-21 23:42:56 +00007743 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7744 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7745 &HasConstCopyAssignment);
7746 }
7747
Richard Smithebaf0e62011-10-18 20:49:44 +00007748 // In C++11, the above citation has "or virtual" added
Sean Hunt661c67a2011-06-21 23:42:56 +00007749 if (LangOpts.CPlusPlus0x) {
7750 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7751 BaseEnd = ClassDecl->vbases_end();
7752 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7753 assert(!Base->getType()->isDependentType() &&
7754 "Cannot generate implicit members for class with dependent bases.");
7755 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7756 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7757 &HasConstCopyAssignment);
7758 }
Douglas Gregord3c35902010-07-01 16:36:15 +00007759 }
7760
7761 // -- for all the nonstatic data members of X that are of a class
7762 // type M (or array thereof), each such class type has a copy
7763 // assignment operator whose parameter is of type const M&,
7764 // const volatile M& or M.
7765 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7766 FieldEnd = ClassDecl->field_end();
7767 HasConstCopyAssignment && Field != FieldEnd;
7768 ++Field) {
7769 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007770 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7771 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7772 &HasConstCopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007773 }
7774 }
7775
7776 // Otherwise, the implicitly declared copy assignment operator will
7777 // have the form
7778 //
7779 // X& X::operator=(X&)
Douglas Gregord3c35902010-07-01 16:36:15 +00007780
Douglas Gregorb87786f2010-07-01 17:48:08 +00007781 // C++ [except.spec]p14:
7782 // An implicitly declared special member function (Clause 12) shall have an
7783 // exception-specification. [...]
Sean Hunt661c67a2011-06-21 23:42:56 +00007784
7785 // It is unspecified whether or not an implicit copy assignment operator
7786 // attempts to deduplicate calls to assignment operators of virtual bases are
7787 // made. As such, this exception specification is effectively unspecified.
7788 // Based on a similar decision made for constness in C++0x, we're erring on
7789 // the side of assuming such calls to be made regardless of whether they
7790 // actually happen.
Douglas Gregorb87786f2010-07-01 17:48:08 +00007791 ImplicitExceptionSpecification ExceptSpec(Context);
Sean Hunt661c67a2011-06-21 23:42:56 +00007792 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregorb87786f2010-07-01 17:48:08 +00007793 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7794 BaseEnd = ClassDecl->bases_end();
7795 Base != BaseEnd; ++Base) {
Sean Hunt661c67a2011-06-21 23:42:56 +00007796 if (Base->isVirtual())
7797 continue;
7798
Douglas Gregora376d102010-07-02 21:50:04 +00007799 CXXRecordDecl *BaseClassDecl
Douglas Gregorb87786f2010-07-01 17:48:08 +00007800 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00007801 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7802 ArgQuals, false, 0))
Douglas Gregorb87786f2010-07-01 17:48:08 +00007803 ExceptSpec.CalledDecl(CopyAssign);
7804 }
Sean Hunt661c67a2011-06-21 23:42:56 +00007805
7806 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7807 BaseEnd = ClassDecl->vbases_end();
7808 Base != BaseEnd; ++Base) {
7809 CXXRecordDecl *BaseClassDecl
7810 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7811 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7812 ArgQuals, false, 0))
7813 ExceptSpec.CalledDecl(CopyAssign);
7814 }
7815
Douglas Gregorb87786f2010-07-01 17:48:08 +00007816 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7817 FieldEnd = ClassDecl->field_end();
7818 Field != FieldEnd;
7819 ++Field) {
7820 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Hunt661c67a2011-06-21 23:42:56 +00007821 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7822 if (CXXMethodDecl *CopyAssign =
7823 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7824 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaracdb80762011-07-11 08:52:40 +00007825 }
Douglas Gregorb87786f2010-07-01 17:48:08 +00007826 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00007827
Sean Hunt30de05c2011-05-14 05:23:20 +00007828 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7829}
7830
7831CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7832 // Note: The following rules are largely analoguous to the copy
7833 // constructor rules. Note that virtual bases are not taken into account
7834 // for determining the argument type of the operator. Note also that
7835 // operators taking an object instead of a reference are allowed.
7836
7837 ImplicitExceptionSpecification Spec(Context);
7838 bool Const;
7839 llvm::tie(Spec, Const) =
7840 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7841
7842 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7843 QualType RetType = Context.getLValueReferenceType(ArgType);
7844 if (Const)
7845 ArgType = ArgType.withConst();
7846 ArgType = Context.getLValueReferenceType(ArgType);
7847
Douglas Gregord3c35902010-07-01 16:36:15 +00007848 // An implicitly-declared copy assignment operator is an inline public
7849 // member of its class.
Sean Hunt30de05c2011-05-14 05:23:20 +00007850 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregord3c35902010-07-01 16:36:15 +00007851 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007852 SourceLocation ClassLoc = ClassDecl->getLocation();
7853 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregord3c35902010-07-01 16:36:15 +00007854 CXXMethodDecl *CopyAssignment
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007855 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalle23cf432010-12-14 08:05:40 +00007856 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregord3c35902010-07-01 16:36:15 +00007857 /*TInfo=*/0, /*isStatic=*/false,
John McCalld931b082010-08-26 03:08:43 +00007858 /*StorageClassAsWritten=*/SC_None,
Richard Smithaf1fc7a2011-08-15 21:04:07 +00007859 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf5251602011-03-08 17:10:18 +00007860 SourceLocation());
Douglas Gregord3c35902010-07-01 16:36:15 +00007861 CopyAssignment->setAccess(AS_public);
Sean Hunt7f410192011-05-14 05:23:24 +00007862 CopyAssignment->setDefaulted();
Douglas Gregord3c35902010-07-01 16:36:15 +00007863 CopyAssignment->setImplicit();
7864 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregord3c35902010-07-01 16:36:15 +00007865
7866 // Add the parameter to the operator.
7867 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00007868 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregord3c35902010-07-01 16:36:15 +00007869 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00007870 SC_None,
7871 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00007872 CopyAssignment->setParams(FromParam);
Douglas Gregord3c35902010-07-01 16:36:15 +00007873
Douglas Gregora376d102010-07-02 21:50:04 +00007874 // Note that we have added this copy-assignment operator.
Douglas Gregora376d102010-07-02 21:50:04 +00007875 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Sean Hunt7f410192011-05-14 05:23:24 +00007876
Douglas Gregor23c94db2010-07-02 17:43:08 +00007877 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora376d102010-07-02 21:50:04 +00007878 PushOnScopeChains(CopyAssignment, S, false);
7879 ClassDecl->addDecl(CopyAssignment);
Douglas Gregord3c35902010-07-01 16:36:15 +00007880
Nico Weberafcc96a2012-01-23 03:19:29 +00007881 // C++0x [class.copy]p19:
7882 // .... If the class definition does not explicitly declare a copy
7883 // assignment operator, there is no user-declared move constructor, and
7884 // there is no user-declared move assignment operator, a copy assignment
7885 // operator is implicitly declared as defaulted.
7886 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber28976602012-01-23 04:01:33 +00007887 !getLangOptions().MicrosoftMode) ||
7888 ClassDecl->hasUserDeclaredMoveAssignment() ||
Sean Hunt1ccbc542011-06-22 01:05:13 +00007889 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Sean Hunt71a682f2011-05-18 03:41:58 +00007890 CopyAssignment->setDeletedAsWritten();
7891
Douglas Gregord3c35902010-07-01 16:36:15 +00007892 AddOverriddenMethods(ClassDecl, CopyAssignment);
7893 return CopyAssignment;
7894}
7895
Douglas Gregor06a9f362010-05-01 20:49:11 +00007896void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7897 CXXMethodDecl *CopyAssignOperator) {
Sean Hunt7f410192011-05-14 05:23:24 +00007898 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007899 CopyAssignOperator->isOverloadedOperator() &&
7900 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Sean Huntcd10dec2011-05-23 23:14:04 +00007901 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregor06a9f362010-05-01 20:49:11 +00007902 "DefineImplicitCopyAssignment called for wrong function");
7903
7904 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7905
7906 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7907 CopyAssignOperator->setInvalidDecl();
7908 return;
7909 }
7910
7911 CopyAssignOperator->setUsed();
7912
7913 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00007914 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007915
7916 // C++0x [class.copy]p30:
7917 // The implicitly-defined or explicitly-defaulted copy assignment operator
7918 // for a non-union class X performs memberwise copy assignment of its
7919 // subobjects. The direct base classes of X are assigned first, in the
7920 // order of their declaration in the base-specifier-list, and then the
7921 // immediate non-static data members of X are assigned, in the order in
7922 // which they were declared in the class definition.
7923
7924 // The statements that form the synthesized function body.
John McCallca0408f2010-08-23 06:44:23 +00007925 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007926
7927 // The parameter for the "other" object, which we are copying from.
7928 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7929 Qualifiers OtherQuals = Other->getType().getQualifiers();
7930 QualType OtherRefType = Other->getType();
7931 if (const LValueReferenceType *OtherRef
7932 = OtherRefType->getAs<LValueReferenceType>()) {
7933 OtherRefType = OtherRef->getPointeeType();
7934 OtherQuals = OtherRefType.getQualifiers();
7935 }
7936
7937 // Our location for everything implicitly-generated.
7938 SourceLocation Loc = CopyAssignOperator->getLocation();
7939
7940 // Construct a reference to the "other" object. We'll be using this
7941 // throughout the generated ASTs.
John McCall09431682010-11-18 19:01:18 +00007942 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007943 assert(OtherRef && "Reference to parameter cannot fail!");
7944
7945 // Construct the "this" pointer. We'll be using this throughout the generated
7946 // ASTs.
7947 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7948 assert(This && "Reference to this cannot fail!");
7949
7950 // Assign base classes.
7951 bool Invalid = false;
7952 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7953 E = ClassDecl->bases_end(); Base != E; ++Base) {
7954 // Form the assignment:
7955 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7956 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskindec09842011-01-18 02:00:16 +00007957 if (!BaseType->isRecordType()) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00007958 Invalid = true;
7959 continue;
7960 }
7961
John McCallf871d0c2010-08-07 06:22:56 +00007962 CXXCastPath BasePath;
7963 BasePath.push_back(Base);
7964
Douglas Gregor06a9f362010-05-01 20:49:11 +00007965 // Construct the "from" expression, which is an implicit cast to the
7966 // appropriately-qualified base type.
John McCall3fa5cae2010-10-26 07:05:15 +00007967 Expr *From = OtherRef;
John Wiegley429bb272011-04-08 18:41:53 +00007968 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7969 CK_UncheckedDerivedToBase,
7970 VK_LValue, &BasePath).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00007971
7972 // Dereference "this".
John McCall5baba9d2010-08-25 10:28:54 +00007973 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007974
7975 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley429bb272011-04-08 18:41:53 +00007976 To = ImpCastExprToType(To.take(),
7977 Context.getCVRQualifiedType(BaseType,
7978 CopyAssignOperator->getTypeQualifiers()),
7979 CK_UncheckedDerivedToBase,
7980 VK_LValue, &BasePath);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007981
7982 // Build the copy.
John McCall60d7b3a2010-08-24 06:29:42 +00007983 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00007984 To.get(), From,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00007985 /*CopyingBaseSubobject=*/true,
7986 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00007987 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00007988 Diag(CurrentLocation, diag::note_member_synthesized_at)
7989 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7990 CopyAssignOperator->setInvalidDecl();
7991 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00007992 }
7993
7994 // Success! Record the copy.
7995 Statements.push_back(Copy.takeAs<Expr>());
7996 }
7997
7998 // \brief Reference to the __builtin_memcpy function.
7999 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008000 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008001 Expr *CollectableMemCpyRef = 0;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008002
8003 // Assign non-static members.
8004 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8005 FieldEnd = ClassDecl->field_end();
8006 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008007 if (Field->isUnnamedBitfield())
8008 continue;
8009
Douglas Gregor06a9f362010-05-01 20:49:11 +00008010 // Check for members of reference type; we can't copy those.
8011 if (Field->getType()->isReferenceType()) {
8012 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8013 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8014 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008015 Diag(CurrentLocation, diag::note_member_synthesized_at)
8016 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008017 Invalid = true;
8018 continue;
8019 }
8020
8021 // Check for members of const-qualified, non-class type.
8022 QualType BaseType = Context.getBaseElementType(Field->getType());
8023 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8024 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8025 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8026 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008027 Diag(CurrentLocation, diag::note_member_synthesized_at)
8028 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008029 Invalid = true;
8030 continue;
8031 }
John McCallb77115d2011-06-17 00:18:42 +00008032
8033 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008034 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8035 continue;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008036
8037 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian4142ceb2010-05-26 20:19:07 +00008038 if (FieldType->isIncompleteArrayType()) {
8039 assert(ClassDecl->hasFlexibleArrayMember() &&
8040 "Incomplete array type is not valid");
8041 continue;
8042 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008043
8044 // Build references to the field in the object we're copying from and to.
8045 CXXScopeSpec SS; // Intentionally empty
8046 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8047 LookupMemberName);
8048 MemberLookup.addDecl(*Field);
8049 MemberLookup.resolveKind();
John McCall60d7b3a2010-08-24 06:29:42 +00008050 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall09431682010-11-18 19:01:18 +00008051 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008052 SS, SourceLocation(), 0,
8053 MemberLookup, 0);
John McCall60d7b3a2010-08-24 06:29:42 +00008054 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall09431682010-11-18 19:01:18 +00008055 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008056 SS, SourceLocation(), 0,
8057 MemberLookup, 0);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008058 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8059 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8060
8061 // If the field should be copied with __builtin_memcpy rather than via
8062 // explicit assignments, do so. This optimization only applies for arrays
8063 // of scalars and arrays of class type with trivial copy-assignment
8064 // operators.
Fariborz Jahanian6b167f42011-08-09 00:26:11 +00008065 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008066 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008067 // Compute the size of the memory buffer to be copied.
8068 QualType SizeType = Context.getSizeType();
8069 llvm::APInt Size(Context.getTypeSize(SizeType),
8070 Context.getTypeSizeInChars(BaseType).getQuantity());
8071 for (const ConstantArrayType *Array
8072 = Context.getAsConstantArrayType(FieldType);
8073 Array;
8074 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad9f71a8f2010-12-07 08:25:34 +00008075 llvm::APInt ArraySize
8076 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008077 Size *= ArraySize;
8078 }
8079
8080 // Take the address of the field references for "from" and "to".
John McCall2de56d12010-08-25 11:45:40 +00008081 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8082 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008083
8084 bool NeedsCollectableMemCpy =
8085 (BaseType->isRecordType() &&
8086 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8087
8088 if (NeedsCollectableMemCpy) {
8089 if (!CollectableMemCpyRef) {
Fariborz Jahanian8e2eab22010-06-16 16:22:04 +00008090 // Create a reference to the __builtin_objc_memmove_collectable function.
8091 LookupResult R(*this,
8092 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008093 Loc, LookupOrdinaryName);
8094 LookupName(R, TUScope, true);
8095
8096 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8097 if (!CollectableMemCpy) {
8098 // Something went horribly wrong earlier, and we will have
8099 // complained about it.
8100 Invalid = true;
8101 continue;
8102 }
8103
8104 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8105 CollectableMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008106 VK_LValue, Loc, 0).take();
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008107 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8108 }
8109 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008110 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00008111 else if (!BuiltinMemCpyRef) {
Douglas Gregor06a9f362010-05-01 20:49:11 +00008112 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8113 LookupOrdinaryName);
8114 LookupName(R, TUScope, true);
8115
8116 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8117 if (!BuiltinMemCpy) {
8118 // Something went horribly wrong earlier, and we will have complained
8119 // about it.
8120 Invalid = true;
8121 continue;
8122 }
8123
8124 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8125 BuiltinMemCpy->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008126 VK_LValue, Loc, 0).take();
Douglas Gregor06a9f362010-05-01 20:49:11 +00008127 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8128 }
8129
John McCallca0408f2010-08-23 06:44:23 +00008130 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008131 CallArgs.push_back(To.takeAs<Expr>());
8132 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008133 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCall60d7b3a2010-08-24 06:29:42 +00008134 ExprResult Call = ExprError();
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008135 if (NeedsCollectableMemCpy)
8136 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008137 CollectableMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008138 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008139 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008140 else
8141 Call = ActOnCallExpr(/*Scope=*/0,
John McCall9ae2f072010-08-23 23:25:46 +00008142 BuiltinMemCpyRef,
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008143 Loc, move_arg(CallArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008144 Loc);
Fariborz Jahanianff2d05f2010-06-16 00:16:38 +00008145
Douglas Gregor06a9f362010-05-01 20:49:11 +00008146 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8147 Statements.push_back(Call.takeAs<Expr>());
8148 continue;
8149 }
8150
8151 // Build the copy of this field.
John McCall60d7b3a2010-08-24 06:29:42 +00008152 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008153 To.get(), From.get(),
8154 /*CopyingBaseSubobject=*/false,
8155 /*Copying=*/true);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008156 if (Copy.isInvalid()) {
Douglas Gregor60a8fbb2010-05-05 22:38:15 +00008157 Diag(CurrentLocation, diag::note_member_synthesized_at)
8158 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8159 CopyAssignOperator->setInvalidDecl();
8160 return;
Douglas Gregor06a9f362010-05-01 20:49:11 +00008161 }
8162
8163 // Success! Record the copy.
8164 Statements.push_back(Copy.takeAs<Stmt>());
8165 }
8166
8167 if (!Invalid) {
8168 // Add a "return *this;"
John McCall2de56d12010-08-25 11:45:40 +00008169 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregor06a9f362010-05-01 20:49:11 +00008170
John McCall60d7b3a2010-08-24 06:29:42 +00008171 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregor06a9f362010-05-01 20:49:11 +00008172 if (Return.isInvalid())
8173 Invalid = true;
8174 else {
8175 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008176
8177 if (Trap.hasErrorOccurred()) {
8178 Diag(CurrentLocation, diag::note_member_synthesized_at)
8179 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8180 Invalid = true;
8181 }
Douglas Gregor06a9f362010-05-01 20:49:11 +00008182 }
8183 }
8184
8185 if (Invalid) {
8186 CopyAssignOperator->setInvalidDecl();
8187 return;
8188 }
8189
John McCall60d7b3a2010-08-24 06:29:42 +00008190 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregor06a9f362010-05-01 20:49:11 +00008191 /*isStmtExpr=*/false);
8192 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8193 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008194
8195 if (ASTMutationListener *L = getASTMutationListener()) {
8196 L->CompletedImplicitDefinition(CopyAssignOperator);
8197 }
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00008198}
8199
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008200Sema::ImplicitExceptionSpecification
8201Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8202 ImplicitExceptionSpecification ExceptSpec(Context);
8203
8204 if (ClassDecl->isInvalidDecl())
8205 return ExceptSpec;
8206
8207 // C++0x [except.spec]p14:
8208 // An implicitly declared special member function (Clause 12) shall have an
8209 // exception-specification. [...]
8210
8211 // It is unspecified whether or not an implicit move assignment operator
8212 // attempts to deduplicate calls to assignment operators of virtual bases are
8213 // made. As such, this exception specification is effectively unspecified.
8214 // Based on a similar decision made for constness in C++0x, we're erring on
8215 // the side of assuming such calls to be made regardless of whether they
8216 // actually happen.
8217 // Note that a move constructor is not implicitly declared when there are
8218 // virtual bases, but it can still be user-declared and explicitly defaulted.
8219 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8220 BaseEnd = ClassDecl->bases_end();
8221 Base != BaseEnd; ++Base) {
8222 if (Base->isVirtual())
8223 continue;
8224
8225 CXXRecordDecl *BaseClassDecl
8226 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8227 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8228 false, 0))
8229 ExceptSpec.CalledDecl(MoveAssign);
8230 }
8231
8232 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8233 BaseEnd = ClassDecl->vbases_end();
8234 Base != BaseEnd; ++Base) {
8235 CXXRecordDecl *BaseClassDecl
8236 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8237 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8238 false, 0))
8239 ExceptSpec.CalledDecl(MoveAssign);
8240 }
8241
8242 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8243 FieldEnd = ClassDecl->field_end();
8244 Field != FieldEnd;
8245 ++Field) {
8246 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8247 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8248 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8249 false, 0))
8250 ExceptSpec.CalledDecl(MoveAssign);
8251 }
8252 }
8253
8254 return ExceptSpec;
8255}
8256
8257CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8258 // Note: The following rules are largely analoguous to the move
8259 // constructor rules.
8260
8261 ImplicitExceptionSpecification Spec(
8262 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8263
8264 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8265 QualType RetType = Context.getLValueReferenceType(ArgType);
8266 ArgType = Context.getRValueReferenceType(ArgType);
8267
8268 // An implicitly-declared move assignment operator is an inline public
8269 // member of its class.
8270 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8271 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8272 SourceLocation ClassLoc = ClassDecl->getLocation();
8273 DeclarationNameInfo NameInfo(Name, ClassLoc);
8274 CXXMethodDecl *MoveAssignment
8275 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8276 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8277 /*TInfo=*/0, /*isStatic=*/false,
8278 /*StorageClassAsWritten=*/SC_None,
8279 /*isInline=*/true,
8280 /*isConstexpr=*/false,
8281 SourceLocation());
8282 MoveAssignment->setAccess(AS_public);
8283 MoveAssignment->setDefaulted();
8284 MoveAssignment->setImplicit();
8285 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8286
8287 // Add the parameter to the operator.
8288 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8289 ClassLoc, ClassLoc, /*Id=*/0,
8290 ArgType, /*TInfo=*/0,
8291 SC_None,
8292 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008293 MoveAssignment->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008294
8295 // Note that we have added this copy-assignment operator.
8296 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8297
8298 // C++0x [class.copy]p9:
8299 // If the definition of a class X does not explicitly declare a move
8300 // assignment operator, one will be implicitly declared as defaulted if and
8301 // only if:
8302 // [...]
8303 // - the move assignment operator would not be implicitly defined as
8304 // deleted.
8305 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8306 // Cache this result so that we don't try to generate this over and over
8307 // on every lookup, leaking memory and wasting time.
8308 ClassDecl->setFailedImplicitMoveAssignment();
8309 return 0;
8310 }
8311
8312 if (Scope *S = getScopeForContext(ClassDecl))
8313 PushOnScopeChains(MoveAssignment, S, false);
8314 ClassDecl->addDecl(MoveAssignment);
8315
8316 AddOverriddenMethods(ClassDecl, MoveAssignment);
8317 return MoveAssignment;
8318}
8319
8320void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8321 CXXMethodDecl *MoveAssignOperator) {
8322 assert((MoveAssignOperator->isDefaulted() &&
8323 MoveAssignOperator->isOverloadedOperator() &&
8324 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8325 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8326 "DefineImplicitMoveAssignment called for wrong function");
8327
8328 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8329
8330 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8331 MoveAssignOperator->setInvalidDecl();
8332 return;
8333 }
8334
8335 MoveAssignOperator->setUsed();
8336
8337 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8338 DiagnosticErrorTrap Trap(Diags);
8339
8340 // C++0x [class.copy]p28:
8341 // The implicitly-defined or move assignment operator for a non-union class
8342 // X performs memberwise move assignment of its subobjects. The direct base
8343 // classes of X are assigned first, in the order of their declaration in the
8344 // base-specifier-list, and then the immediate non-static data members of X
8345 // are assigned, in the order in which they were declared in the class
8346 // definition.
8347
8348 // The statements that form the synthesized function body.
8349 ASTOwningVector<Stmt*> Statements(*this);
8350
8351 // The parameter for the "other" object, which we are move from.
8352 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8353 QualType OtherRefType = Other->getType()->
8354 getAs<RValueReferenceType>()->getPointeeType();
8355 assert(OtherRefType.getQualifiers() == 0 &&
8356 "Bad argument type of defaulted move assignment");
8357
8358 // Our location for everything implicitly-generated.
8359 SourceLocation Loc = MoveAssignOperator->getLocation();
8360
8361 // Construct a reference to the "other" object. We'll be using this
8362 // throughout the generated ASTs.
8363 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8364 assert(OtherRef && "Reference to parameter cannot fail!");
8365 // Cast to rvalue.
8366 OtherRef = CastForMoving(*this, OtherRef);
8367
8368 // Construct the "this" pointer. We'll be using this throughout the generated
8369 // ASTs.
8370 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8371 assert(This && "Reference to this cannot fail!");
8372
8373 // Assign base classes.
8374 bool Invalid = false;
8375 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8376 E = ClassDecl->bases_end(); Base != E; ++Base) {
8377 // Form the assignment:
8378 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8379 QualType BaseType = Base->getType().getUnqualifiedType();
8380 if (!BaseType->isRecordType()) {
8381 Invalid = true;
8382 continue;
8383 }
8384
8385 CXXCastPath BasePath;
8386 BasePath.push_back(Base);
8387
8388 // Construct the "from" expression, which is an implicit cast to the
8389 // appropriately-qualified base type.
8390 Expr *From = OtherRef;
8391 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregorb2b56582011-09-06 16:26:56 +00008392 VK_XValue, &BasePath).take();
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008393
8394 // Dereference "this".
8395 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8396
8397 // Implicitly cast "this" to the appropriately-qualified base type.
8398 To = ImpCastExprToType(To.take(),
8399 Context.getCVRQualifiedType(BaseType,
8400 MoveAssignOperator->getTypeQualifiers()),
8401 CK_UncheckedDerivedToBase,
8402 VK_LValue, &BasePath);
8403
8404 // Build the move.
8405 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8406 To.get(), From,
8407 /*CopyingBaseSubobject=*/true,
8408 /*Copying=*/false);
8409 if (Move.isInvalid()) {
8410 Diag(CurrentLocation, diag::note_member_synthesized_at)
8411 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8412 MoveAssignOperator->setInvalidDecl();
8413 return;
8414 }
8415
8416 // Success! Record the move.
8417 Statements.push_back(Move.takeAs<Expr>());
8418 }
8419
8420 // \brief Reference to the __builtin_memcpy function.
8421 Expr *BuiltinMemCpyRef = 0;
8422 // \brief Reference to the __builtin_objc_memmove_collectable function.
8423 Expr *CollectableMemCpyRef = 0;
8424
8425 // Assign non-static members.
8426 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8427 FieldEnd = ClassDecl->field_end();
8428 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +00008429 if (Field->isUnnamedBitfield())
8430 continue;
8431
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008432 // Check for members of reference type; we can't move those.
8433 if (Field->getType()->isReferenceType()) {
8434 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8435 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8436 Diag(Field->getLocation(), diag::note_declared_at);
8437 Diag(CurrentLocation, diag::note_member_synthesized_at)
8438 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8439 Invalid = true;
8440 continue;
8441 }
8442
8443 // Check for members of const-qualified, non-class type.
8444 QualType BaseType = Context.getBaseElementType(Field->getType());
8445 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8446 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8447 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8448 Diag(Field->getLocation(), diag::note_declared_at);
8449 Diag(CurrentLocation, diag::note_member_synthesized_at)
8450 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8451 Invalid = true;
8452 continue;
8453 }
8454
8455 // Suppress assigning zero-width bitfields.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00008456 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8457 continue;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008458
8459 QualType FieldType = Field->getType().getNonReferenceType();
8460 if (FieldType->isIncompleteArrayType()) {
8461 assert(ClassDecl->hasFlexibleArrayMember() &&
8462 "Incomplete array type is not valid");
8463 continue;
8464 }
8465
8466 // Build references to the field in the object we're copying from and to.
8467 CXXScopeSpec SS; // Intentionally empty
8468 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8469 LookupMemberName);
8470 MemberLookup.addDecl(*Field);
8471 MemberLookup.resolveKind();
8472 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8473 Loc, /*IsArrow=*/false,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008474 SS, SourceLocation(), 0,
8475 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008476 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8477 Loc, /*IsArrow=*/true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00008478 SS, SourceLocation(), 0,
8479 MemberLookup, 0);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008480 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8481 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8482
8483 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8484 "Member reference with rvalue base must be rvalue except for reference "
8485 "members, which aren't allowed for move assignment.");
8486
8487 // If the field should be copied with __builtin_memcpy rather than via
8488 // explicit assignments, do so. This optimization only applies for arrays
8489 // of scalars and arrays of class type with trivial move-assignment
8490 // operators.
8491 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8492 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8493 // Compute the size of the memory buffer to be copied.
8494 QualType SizeType = Context.getSizeType();
8495 llvm::APInt Size(Context.getTypeSize(SizeType),
8496 Context.getTypeSizeInChars(BaseType).getQuantity());
8497 for (const ConstantArrayType *Array
8498 = Context.getAsConstantArrayType(FieldType);
8499 Array;
8500 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8501 llvm::APInt ArraySize
8502 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8503 Size *= ArraySize;
8504 }
8505
Douglas Gregor45d3d712011-09-01 02:09:07 +00008506 // Take the address of the field references for "from" and "to". We
8507 // directly construct UnaryOperators here because semantic analysis
8508 // does not permit us to take the address of an xvalue.
8509 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8510 Context.getPointerType(From.get()->getType()),
8511 VK_RValue, OK_Ordinary, Loc);
8512 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8513 Context.getPointerType(To.get()->getType()),
8514 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008515
8516 bool NeedsCollectableMemCpy =
8517 (BaseType->isRecordType() &&
8518 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8519
8520 if (NeedsCollectableMemCpy) {
8521 if (!CollectableMemCpyRef) {
8522 // Create a reference to the __builtin_objc_memmove_collectable function.
8523 LookupResult R(*this,
8524 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8525 Loc, LookupOrdinaryName);
8526 LookupName(R, TUScope, true);
8527
8528 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8529 if (!CollectableMemCpy) {
8530 // Something went horribly wrong earlier, and we will have
8531 // complained about it.
8532 Invalid = true;
8533 continue;
8534 }
8535
8536 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8537 CollectableMemCpy->getType(),
8538 VK_LValue, Loc, 0).take();
8539 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8540 }
8541 }
8542 // Create a reference to the __builtin_memcpy builtin function.
8543 else if (!BuiltinMemCpyRef) {
8544 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8545 LookupOrdinaryName);
8546 LookupName(R, TUScope, true);
8547
8548 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8549 if (!BuiltinMemCpy) {
8550 // Something went horribly wrong earlier, and we will have complained
8551 // about it.
8552 Invalid = true;
8553 continue;
8554 }
8555
8556 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8557 BuiltinMemCpy->getType(),
8558 VK_LValue, Loc, 0).take();
8559 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8560 }
8561
8562 ASTOwningVector<Expr*> CallArgs(*this);
8563 CallArgs.push_back(To.takeAs<Expr>());
8564 CallArgs.push_back(From.takeAs<Expr>());
8565 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8566 ExprResult Call = ExprError();
8567 if (NeedsCollectableMemCpy)
8568 Call = ActOnCallExpr(/*Scope=*/0,
8569 CollectableMemCpyRef,
8570 Loc, move_arg(CallArgs),
8571 Loc);
8572 else
8573 Call = ActOnCallExpr(/*Scope=*/0,
8574 BuiltinMemCpyRef,
8575 Loc, move_arg(CallArgs),
8576 Loc);
8577
8578 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8579 Statements.push_back(Call.takeAs<Expr>());
8580 continue;
8581 }
8582
8583 // Build the move of this field.
8584 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8585 To.get(), From.get(),
8586 /*CopyingBaseSubobject=*/false,
8587 /*Copying=*/false);
8588 if (Move.isInvalid()) {
8589 Diag(CurrentLocation, diag::note_member_synthesized_at)
8590 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8591 MoveAssignOperator->setInvalidDecl();
8592 return;
8593 }
8594
8595 // Success! Record the copy.
8596 Statements.push_back(Move.takeAs<Stmt>());
8597 }
8598
8599 if (!Invalid) {
8600 // Add a "return *this;"
8601 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8602
8603 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8604 if (Return.isInvalid())
8605 Invalid = true;
8606 else {
8607 Statements.push_back(Return.takeAs<Stmt>());
8608
8609 if (Trap.hasErrorOccurred()) {
8610 Diag(CurrentLocation, diag::note_member_synthesized_at)
8611 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8612 Invalid = true;
8613 }
8614 }
8615 }
8616
8617 if (Invalid) {
8618 MoveAssignOperator->setInvalidDecl();
8619 return;
8620 }
8621
8622 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8623 /*isStmtExpr=*/false);
8624 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8625 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8626
8627 if (ASTMutationListener *L = getASTMutationListener()) {
8628 L->CompletedImplicitDefinition(MoveAssignOperator);
8629 }
8630}
8631
Sean Hunt49634cf2011-05-13 06:10:58 +00008632std::pair<Sema::ImplicitExceptionSpecification, bool>
8633Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaracdb80762011-07-11 08:52:40 +00008634 if (ClassDecl->isInvalidDecl())
8635 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8636
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008637 // C++ [class.copy]p5:
8638 // The implicitly-declared copy constructor for a class X will
8639 // have the form
8640 //
8641 // X::X(const X&)
8642 //
8643 // if
Sean Huntc530d172011-06-10 04:44:37 +00008644 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008645 bool HasConstCopyConstructor = true;
8646
8647 // -- each direct or virtual base class B of X has a copy
8648 // constructor whose first parameter is of type const B& or
8649 // const volatile B&, and
8650 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8651 BaseEnd = ClassDecl->bases_end();
8652 HasConstCopyConstructor && Base != BaseEnd;
8653 ++Base) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008654 // Virtual bases are handled below.
8655 if (Base->isVirtual())
8656 continue;
8657
Douglas Gregor22584312010-07-02 23:41:54 +00008658 CXXRecordDecl *BaseClassDecl
Douglas Gregor598a8542010-07-01 18:27:03 +00008659 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008660 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8661 &HasConstCopyConstructor);
Douglas Gregor598a8542010-07-01 18:27:03 +00008662 }
8663
8664 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8665 BaseEnd = ClassDecl->vbases_end();
8666 HasConstCopyConstructor && Base != BaseEnd;
8667 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008668 CXXRecordDecl *BaseClassDecl
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008669 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Hunt661c67a2011-06-21 23:42:56 +00008670 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8671 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008672 }
8673
8674 // -- for all the nonstatic data members of X that are of a
8675 // class type M (or array thereof), each such class type
8676 // has a copy constructor whose first parameter is of type
8677 // const M& or const volatile M&.
8678 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8679 FieldEnd = ClassDecl->field_end();
8680 HasConstCopyConstructor && Field != FieldEnd;
8681 ++Field) {
Douglas Gregor598a8542010-07-01 18:27:03 +00008682 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008683 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Sean Hunt661c67a2011-06-21 23:42:56 +00008684 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8685 &HasConstCopyConstructor);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008686 }
8687 }
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008688 // Otherwise, the implicitly declared copy constructor will have
8689 // the form
8690 //
8691 // X::X(X&)
Sean Hunt49634cf2011-05-13 06:10:58 +00008692
Douglas Gregor0d405db2010-07-01 20:59:04 +00008693 // C++ [except.spec]p14:
8694 // An implicitly declared special member function (Clause 12) shall have an
8695 // exception-specification. [...]
8696 ImplicitExceptionSpecification ExceptSpec(Context);
8697 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8698 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8699 BaseEnd = ClassDecl->bases_end();
8700 Base != BaseEnd;
8701 ++Base) {
8702 // Virtual bases are handled below.
8703 if (Base->isVirtual())
8704 continue;
8705
Douglas Gregor22584312010-07-02 23:41:54 +00008706 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008707 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008708 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008709 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008710 ExceptSpec.CalledDecl(CopyConstructor);
8711 }
8712 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8713 BaseEnd = ClassDecl->vbases_end();
8714 Base != BaseEnd;
8715 ++Base) {
Douglas Gregor22584312010-07-02 23:41:54 +00008716 CXXRecordDecl *BaseClassDecl
Douglas Gregor0d405db2010-07-01 20:59:04 +00008717 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Sean Huntc530d172011-06-10 04:44:37 +00008718 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008719 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor0d405db2010-07-01 20:59:04 +00008720 ExceptSpec.CalledDecl(CopyConstructor);
8721 }
8722 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8723 FieldEnd = ClassDecl->field_end();
8724 Field != FieldEnd;
8725 ++Field) {
8726 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Sean Huntc530d172011-06-10 04:44:37 +00008727 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8728 if (CXXConstructorDecl *CopyConstructor =
Sean Hunt661c67a2011-06-21 23:42:56 +00008729 LookupCopyingConstructor(FieldClassDecl, Quals))
Sean Huntc530d172011-06-10 04:44:37 +00008730 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor0d405db2010-07-01 20:59:04 +00008731 }
8732 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00008733
Sean Hunt49634cf2011-05-13 06:10:58 +00008734 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8735}
8736
8737CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8738 CXXRecordDecl *ClassDecl) {
8739 // C++ [class.copy]p4:
8740 // If the class definition does not explicitly declare a copy
8741 // constructor, one is declared implicitly.
8742
8743 ImplicitExceptionSpecification Spec(Context);
8744 bool Const;
8745 llvm::tie(Spec, Const) =
8746 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8747
8748 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8749 QualType ArgType = ClassType;
8750 if (Const)
8751 ArgType = ArgType.withConst();
8752 ArgType = Context.getLValueReferenceType(ArgType);
8753
8754 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8755
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008756 DeclarationName Name
8757 = Context.DeclarationNames.getCXXConstructorName(
8758 Context.getCanonicalType(ClassType));
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008759 SourceLocation ClassLoc = ClassDecl->getLocation();
8760 DeclarationNameInfo NameInfo(Name, ClassLoc);
Sean Hunt49634cf2011-05-13 06:10:58 +00008761
8762 // An implicitly-declared copy constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008763 // member of its class.
8764 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8765 Context, ClassDecl, ClassLoc, NameInfo,
8766 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8767 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8768 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8769 getLangOptions().CPlusPlus0x);
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008770 CopyConstructor->setAccess(AS_public);
Sean Hunt49634cf2011-05-13 06:10:58 +00008771 CopyConstructor->setDefaulted();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008772 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008773
Douglas Gregor22584312010-07-02 23:41:54 +00008774 // Note that we have declared this constructor.
Douglas Gregor22584312010-07-02 23:41:54 +00008775 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8776
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008777 // Add the parameter to the constructor.
8778 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00008779 ClassLoc, ClassLoc,
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008780 /*IdentifierInfo=*/0,
8781 ArgType, /*TInfo=*/0,
John McCalld931b082010-08-26 03:08:43 +00008782 SC_None,
8783 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008784 CopyConstructor->setParams(FromParam);
Sean Hunt49634cf2011-05-13 06:10:58 +00008785
Douglas Gregor23c94db2010-07-02 17:43:08 +00008786 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor22584312010-07-02 23:41:54 +00008787 PushOnScopeChains(CopyConstructor, S, false);
8788 ClassDecl->addDecl(CopyConstructor);
Sean Hunt71a682f2011-05-18 03:41:58 +00008789
Nico Weberafcc96a2012-01-23 03:19:29 +00008790 // C++11 [class.copy]p8:
8791 // ... If the class definition does not explicitly declare a copy
8792 // constructor, there is no user-declared move constructor, and there is no
8793 // user-declared move assignment operator, a copy constructor is implicitly
8794 // declared as defaulted.
Sean Hunt1ccbc542011-06-22 01:05:13 +00008795 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weberafcc96a2012-01-23 03:19:29 +00008796 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber28976602012-01-23 04:01:33 +00008797 !getLangOptions().MicrosoftMode) ||
Sean Huntc32d6842011-10-11 04:55:36 +00008798 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Sean Hunt71a682f2011-05-18 03:41:58 +00008799 CopyConstructor->setDeletedAsWritten();
Douglas Gregor4a0c26f2010-07-01 17:57:27 +00008800
8801 return CopyConstructor;
8802}
8803
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008804void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Sean Hunt49634cf2011-05-13 06:10:58 +00008805 CXXConstructorDecl *CopyConstructor) {
8806 assert((CopyConstructor->isDefaulted() &&
8807 CopyConstructor->isCopyConstructor() &&
Sean Huntcd10dec2011-05-23 23:14:04 +00008808 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008809 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump1eb44332009-09-09 15:08:12 +00008810
Anders Carlsson63010a72010-04-23 16:24:12 +00008811 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008812 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008813
Douglas Gregor39957dc2010-05-01 15:04:51 +00008814 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis9c4eb1f2010-11-19 00:19:12 +00008815 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008816
Sean Huntcbb67482011-01-08 20:30:50 +00008817 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregorc63d2c82010-05-12 16:39:35 +00008818 Trap.hasErrorOccurred()) {
Anders Carlsson59b7f152010-05-01 16:39:01 +00008819 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008820 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson59b7f152010-05-01 16:39:01 +00008821 CopyConstructor->setInvalidDecl();
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008822 } else {
8823 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8824 CopyConstructor->getLocation(),
8825 MultiStmtArg(*this, 0, 0),
8826 /*isStmtExpr=*/false)
8827 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008828 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson8e142cc2010-04-25 00:52:09 +00008829 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +00008830
8831 CopyConstructor->setUsed();
Sebastian Redl58a2cd82011-04-24 16:28:06 +00008832 if (ASTMutationListener *L = getASTMutationListener()) {
8833 L->CompletedImplicitDefinition(CopyConstructor);
8834 }
Fariborz Jahanian485f0872009-06-22 23:34:40 +00008835}
8836
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008837Sema::ImplicitExceptionSpecification
8838Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8839 // C++ [except.spec]p14:
8840 // An implicitly declared special member function (Clause 12) shall have an
8841 // exception-specification. [...]
8842 ImplicitExceptionSpecification ExceptSpec(Context);
8843 if (ClassDecl->isInvalidDecl())
8844 return ExceptSpec;
8845
8846 // Direct base-class constructors.
8847 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8848 BEnd = ClassDecl->bases_end();
8849 B != BEnd; ++B) {
8850 if (B->isVirtual()) // Handled below.
8851 continue;
8852
8853 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8854 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8855 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8856 // If this is a deleted function, add it anyway. This might be conformant
8857 // with the standard. This might not. I'm not sure. It might not matter.
8858 if (Constructor)
8859 ExceptSpec.CalledDecl(Constructor);
8860 }
8861 }
8862
8863 // Virtual base-class constructors.
8864 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8865 BEnd = ClassDecl->vbases_end();
8866 B != BEnd; ++B) {
8867 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8868 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8869 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8870 // If this is a deleted function, add it anyway. This might be conformant
8871 // with the standard. This might not. I'm not sure. It might not matter.
8872 if (Constructor)
8873 ExceptSpec.CalledDecl(Constructor);
8874 }
8875 }
8876
8877 // Field constructors.
8878 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8879 FEnd = ClassDecl->field_end();
8880 F != FEnd; ++F) {
Douglas Gregorf4853882011-11-28 20:03:15 +00008881 if (const RecordType *RecordTy
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008882 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8883 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8884 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8885 // If this is a deleted function, add it anyway. This might be conformant
8886 // with the standard. This might not. I'm not sure. It might not matter.
8887 // In particular, the problem is that this function never gets called. It
8888 // might just be ill-formed because this function attempts to refer to
8889 // a deleted function here.
8890 if (Constructor)
8891 ExceptSpec.CalledDecl(Constructor);
8892 }
8893 }
8894
8895 return ExceptSpec;
8896}
8897
8898CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8899 CXXRecordDecl *ClassDecl) {
8900 ImplicitExceptionSpecification Spec(
8901 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8902
8903 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8904 QualType ArgType = Context.getRValueReferenceType(ClassType);
8905
8906 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8907
8908 DeclarationName Name
8909 = Context.DeclarationNames.getCXXConstructorName(
8910 Context.getCanonicalType(ClassType));
8911 SourceLocation ClassLoc = ClassDecl->getLocation();
8912 DeclarationNameInfo NameInfo(Name, ClassLoc);
8913
8914 // C++0x [class.copy]p11:
8915 // An implicitly-declared copy/move constructor is an inline public
Richard Smith61802452011-12-22 02:22:31 +00008916 // member of its class.
8917 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8918 Context, ClassDecl, ClassLoc, NameInfo,
8919 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8920 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8921 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8922 getLangOptions().CPlusPlus0x);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008923 MoveConstructor->setAccess(AS_public);
8924 MoveConstructor->setDefaulted();
8925 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smith61802452011-12-22 02:22:31 +00008926
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008927 // Add the parameter to the constructor.
8928 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8929 ClassLoc, ClassLoc,
8930 /*IdentifierInfo=*/0,
8931 ArgType, /*TInfo=*/0,
8932 SC_None,
8933 SC_None, 0);
David Blaikie4278c652011-09-21 18:16:56 +00008934 MoveConstructor->setParams(FromParam);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008935
8936 // C++0x [class.copy]p9:
8937 // If the definition of a class X does not explicitly declare a move
8938 // constructor, one will be implicitly declared as defaulted if and only if:
8939 // [...]
8940 // - the move constructor would not be implicitly defined as deleted.
Sean Hunt769bb2d2011-10-11 06:43:29 +00008941 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008942 // Cache this result so that we don't try to generate this over and over
8943 // on every lookup, leaking memory and wasting time.
8944 ClassDecl->setFailedImplicitMoveConstructor();
8945 return 0;
8946 }
8947
8948 // Note that we have declared this constructor.
8949 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8950
8951 if (Scope *S = getScopeForContext(ClassDecl))
8952 PushOnScopeChains(MoveConstructor, S, false);
8953 ClassDecl->addDecl(MoveConstructor);
8954
8955 return MoveConstructor;
8956}
8957
8958void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8959 CXXConstructorDecl *MoveConstructor) {
8960 assert((MoveConstructor->isDefaulted() &&
8961 MoveConstructor->isMoveConstructor() &&
8962 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8963 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8964
8965 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8966 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8967
8968 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8969 DiagnosticErrorTrap Trap(Diags);
8970
8971 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8972 Trap.hasErrorOccurred()) {
8973 Diag(CurrentLocation, diag::note_member_synthesized_at)
8974 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8975 MoveConstructor->setInvalidDecl();
8976 } else {
8977 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8978 MoveConstructor->getLocation(),
8979 MultiStmtArg(*this, 0, 0),
8980 /*isStmtExpr=*/false)
8981 .takeAs<Stmt>());
Douglas Gregor690b2db2011-09-22 20:32:43 +00008982 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00008983 }
8984
8985 MoveConstructor->setUsed();
8986
8987 if (ASTMutationListener *L = getASTMutationListener()) {
8988 L->CompletedImplicitDefinition(MoveConstructor);
8989 }
8990}
8991
John McCall60d7b3a2010-08-24 06:29:42 +00008992ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00008993Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump1eb44332009-09-09 15:08:12 +00008994 CXXConstructorDecl *Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00008995 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008996 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00008997 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00008998 unsigned ConstructKind,
8999 SourceRange ParenRange) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009000 bool Elidable = false;
Mike Stump1eb44332009-09-09 15:08:12 +00009001
Douglas Gregor2f599792010-04-02 18:24:57 +00009002 // C++0x [class.copy]p34:
9003 // When certain criteria are met, an implementation is allowed to
9004 // omit the copy/move construction of a class object, even if the
9005 // copy/move constructor and/or destructor for the object have
9006 // side effects. [...]
9007 // - when a temporary class object that has not been bound to a
9008 // reference (12.2) would be copied/moved to a class object
9009 // with the same cv-unqualified type, the copy/move operation
9010 // can be omitted by constructing the temporary object
9011 // directly into the target of the omitted copy/move
John McCall558d2ab2010-09-15 10:14:12 +00009012 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor70a21de2011-01-27 23:24:55 +00009013 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor2f599792010-04-02 18:24:57 +00009014 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall558d2ab2010-09-15 10:14:12 +00009015 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009016 }
Mike Stump1eb44332009-09-09 15:08:12 +00009017
9018 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009019 Elidable, move(ExprArgs), HadMultipleCandidates,
9020 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00009021}
9022
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009023/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9024/// including handling of its default argument expressions.
John McCall60d7b3a2010-08-24 06:29:42 +00009025ExprResult
Anders Carlssonec8e5ea2009-09-05 07:40:38 +00009026Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9027 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor16006c92009-12-16 18:50:27 +00009028 MultiExprArg ExprArgs,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009029 bool HadMultipleCandidates,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00009030 bool RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009031 unsigned ConstructKind,
9032 SourceRange ParenRange) {
Anders Carlssonf47511a2009-09-07 22:23:31 +00009033 unsigned NumExprs = ExprArgs.size();
9034 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump1eb44332009-09-09 15:08:12 +00009035
Nick Lewycky909a70d2011-03-25 01:44:32 +00009036 for (specific_attr_iterator<NonNullAttr>
9037 i = Constructor->specific_attr_begin<NonNullAttr>(),
9038 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9039 const NonNullAttr *NonNull = *i;
9040 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9041 }
9042
Eli Friedman5f2987c2012-02-02 03:46:19 +00009043 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor99a2e602009-12-16 01:38:02 +00009044 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009045 Constructor, Elidable, Exprs, NumExprs,
9046 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00009047 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9048 ParenRange));
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009049}
9050
Mike Stump1eb44332009-09-09 15:08:12 +00009051bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00009052 CXXConstructorDecl *Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009053 MultiExprArg Exprs,
9054 bool HadMultipleCandidates) {
Chandler Carruth428edaf2010-10-25 08:47:36 +00009055 // FIXME: Provide the correct paren SourceRange when available.
John McCall60d7b3a2010-08-24 06:29:42 +00009056 ExprResult TempResult =
Fariborz Jahanianc0fcce42009-10-28 18:41:06 +00009057 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009058 move(Exprs), HadMultipleCandidates, false,
9059 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonfe2de492009-08-25 05:18:00 +00009060 if (TempResult.isInvalid())
9061 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00009062
Anders Carlssonda3f4e22009-08-25 05:12:04 +00009063 Expr *Temp = TempResult.takeAs<Expr>();
John McCallb4eb64d2010-10-08 02:01:28 +00009064 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedman5f2987c2012-02-02 03:46:19 +00009065 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall4765fa02010-12-06 08:20:24 +00009066 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregor838db382010-02-11 01:19:42 +00009067 VD->setInit(Temp);
Mike Stump1eb44332009-09-09 15:08:12 +00009068
Anders Carlssonfe2de492009-08-25 05:18:00 +00009069 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00009070}
9071
John McCall68c6c9a2010-02-02 09:10:11 +00009072void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009073 if (VD->isInvalidDecl()) return;
9074
John McCall68c6c9a2010-02-02 09:10:11 +00009075 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009076 if (ClassDecl->isInvalidDecl()) return;
9077 if (ClassDecl->hasTrivialDestructor()) return;
9078 if (ClassDecl->isDependentContext()) return;
John McCall626e96e2010-08-01 20:20:59 +00009079
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009080 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedman5f2987c2012-02-02 03:46:19 +00009081 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009082 CheckDestructorAccess(VD->getLocation(), Destructor,
9083 PDiag(diag::err_access_dtor_var)
9084 << VD->getDeclName()
9085 << VD->getType());
Anders Carlsson2b32dad2011-03-24 01:01:41 +00009086
Chandler Carruth1d71cbf2011-03-27 21:26:48 +00009087 if (!VD->hasGlobalStorage()) return;
9088
9089 // Emit warning for non-trivial dtor in global scope (a real global,
9090 // class-static, function-static).
9091 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9092
9093 // TODO: this should be re-enabled for static locals by !CXAAtExit
9094 if (!VD->isStaticLocal())
9095 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00009096}
9097
Mike Stump1eb44332009-09-09 15:08:12 +00009098/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009099/// ActOnDeclarator, when a C++ direct initializer is present.
9100/// e.g: "int x(1);"
John McCalld226f652010-08-21 09:40:31 +00009101void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00009102 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00009103 MultiExprArg Exprs,
Richard Smith34b41d92011-02-20 03:19:35 +00009104 SourceLocation RParenLoc,
9105 bool TypeMayContainAuto) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009106 // If there is no declaration, there was an error parsing it. Just ignore
9107 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00009108 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009109 return;
Mike Stump1eb44332009-09-09 15:08:12 +00009110
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009111 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9112 if (!VDecl) {
9113 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9114 RealDecl->setInvalidDecl();
9115 return;
9116 }
9117
Eli Friedman6aeaa602012-01-05 22:34:08 +00009118 // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith34b41d92011-02-20 03:19:35 +00009119 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Eli Friedman6aeaa602012-01-05 22:34:08 +00009120 if (Exprs.size() == 0) {
9121 // It isn't possible to write this directly, but it is possible to
9122 // end up in this situation with "auto x(some_pack...);"
9123 Diag(LParenLoc, diag::err_auto_var_init_no_expression)
9124 << VDecl->getDeclName() << VDecl->getType()
9125 << VDecl->getSourceRange();
9126 RealDecl->setInvalidDecl();
9127 return;
9128 }
9129
Richard Smith34b41d92011-02-20 03:19:35 +00009130 if (Exprs.size() > 1) {
9131 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9132 diag::err_auto_var_init_multiple_expressions)
9133 << VDecl->getDeclName() << VDecl->getType()
9134 << VDecl->getSourceRange();
9135 RealDecl->setInvalidDecl();
9136 return;
9137 }
9138
9139 Expr *Init = Exprs.get()[0];
Richard Smitha085da82011-03-17 16:11:59 +00009140 TypeSourceInfo *DeducedType = 0;
Sebastian Redlb832f6d2012-01-23 22:09:39 +00009141 if (DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType) ==
9142 DAR_Failed)
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00009143 DiagnoseAutoDeductionFailure(VDecl, Init);
Richard Smitha085da82011-03-17 16:11:59 +00009144 if (!DeducedType) {
Richard Smith34b41d92011-02-20 03:19:35 +00009145 RealDecl->setInvalidDecl();
9146 return;
9147 }
Richard Smitha085da82011-03-17 16:11:59 +00009148 VDecl->setTypeSourceInfo(DeducedType);
9149 VDecl->setType(DeducedType->getType());
Richard Smith34b41d92011-02-20 03:19:35 +00009150
John McCallf85e1932011-06-15 23:02:42 +00009151 // In ARC, infer lifetime.
9152 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9153 VDecl->setInvalidDecl();
9154
Richard Smith34b41d92011-02-20 03:19:35 +00009155 // If this is a redeclaration, check that the type we just deduced matches
9156 // the previously declared type.
Douglas Gregoref96ee02012-01-14 16:38:05 +00009157 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith34b41d92011-02-20 03:19:35 +00009158 MergeVarDeclTypes(VDecl, Old);
9159 }
9160
Douglas Gregor83ddad32009-08-26 21:14:46 +00009161 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009162 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009163 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9164 //
9165 // Clients that want to distinguish between the two forms, can check for
9166 // direct initializer using VarDecl::hasCXXDirectInitializer().
9167 // A major benefit is that clients that don't particularly care about which
9168 // exactly form was it (like the CodeGen) can handle both cases without
9169 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009170
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009171 // C++ 8.5p11:
9172 // The form of initialization (using parentheses or '=') is generally
9173 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009174 // class type.
9175
Douglas Gregor4dffad62010-02-11 22:55:30 +00009176 if (!VDecl->getType()->isDependentType() &&
Douglas Gregord24c3062011-10-10 16:05:18 +00009177 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor4dffad62010-02-11 22:55:30 +00009178 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor615c5d42009-03-24 16:43:20 +00009179 diag::err_typecheck_decl_incomplete_type)) {
9180 VDecl->setInvalidDecl();
9181 return;
9182 }
9183
Douglas Gregor90f93822009-12-22 22:17:25 +00009184 // The variable can not have an abstract class type.
9185 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9186 diag::err_abstract_type_in_decl,
9187 AbstractVariableType))
9188 VDecl->setInvalidDecl();
9189
Sebastian Redl31310a22010-02-01 20:16:42 +00009190 const VarDecl *Def;
9191 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregor90f93822009-12-22 22:17:25 +00009192 Diag(VDecl->getLocation(), diag::err_redefinition)
9193 << VDecl->getDeclName();
9194 Diag(Def->getLocation(), diag::note_previous_definition);
9195 VDecl->setInvalidDecl();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00009196 return;
9197 }
Douglas Gregor4dffad62010-02-11 22:55:30 +00009198
Douglas Gregor3a91abf2010-08-24 05:27:49 +00009199 // C++ [class.static.data]p4
9200 // If a static data member is of const integral or const
9201 // enumeration type, its declaration in the class definition can
9202 // specify a constant-initializer which shall be an integral
9203 // constant expression (5.19). In that case, the member can appear
9204 // in integral constant expressions. The member shall still be
9205 // defined in a namespace scope if it is used in the program and the
9206 // namespace scope definition shall not contain an initializer.
9207 //
9208 // We already performed a redefinition check above, but for static
9209 // data members we also need to check whether there was an in-class
9210 // declaration with an initializer.
9211 const VarDecl* PrevInit = 0;
9212 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9213 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9214 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9215 return;
9216 }
9217
Douglas Gregora31040f2010-12-16 01:31:22 +00009218 bool IsDependent = false;
9219 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9220 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9221 VDecl->setInvalidDecl();
9222 return;
9223 }
9224
9225 if (Exprs.get()[I]->isTypeDependent())
9226 IsDependent = true;
9227 }
9228
Douglas Gregor4dffad62010-02-11 22:55:30 +00009229 // If either the declaration has a dependent type or if any of the
9230 // expressions is type-dependent, we represent the initialization
9231 // via a ParenListExpr for later use during template instantiation.
Douglas Gregora31040f2010-12-16 01:31:22 +00009232 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor4dffad62010-02-11 22:55:30 +00009233 // Let clients know that initialization was done with a direct initializer.
9234 VDecl->setCXXDirectInitializer(true);
9235
9236 // Store the initialization expressions as a ParenListExpr.
9237 unsigned NumExprs = Exprs.size();
Manuel Klimek0d9106f2011-06-22 20:02:16 +00009238 VDecl->setInit(new (Context) ParenListExpr(
9239 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9240 VDecl->getType().getNonReferenceType()));
Douglas Gregor4dffad62010-02-11 22:55:30 +00009241 return;
9242 }
Douglas Gregor90f93822009-12-22 22:17:25 +00009243
9244 // Capture the variable that is being initialized and the style of
9245 // initialization.
9246 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9247
9248 // FIXME: Poor source location information.
9249 InitializationKind Kind
9250 = InitializationKind::CreateDirect(VDecl->getLocation(),
9251 LParenLoc, RParenLoc);
9252
Douglas Gregord24c3062011-10-10 16:05:18 +00009253 QualType T = VDecl->getType();
Douglas Gregor90f93822009-12-22 22:17:25 +00009254 InitializationSequence InitSeq(*this, Entity, Kind,
John McCall9ae2f072010-08-23 23:25:46 +00009255 Exprs.get(), Exprs.size());
Douglas Gregord24c3062011-10-10 16:05:18 +00009256 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregor90f93822009-12-22 22:17:25 +00009257 if (Result.isInvalid()) {
9258 VDecl->setInvalidDecl();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009259 return;
Douglas Gregord24c3062011-10-10 16:05:18 +00009260 } else if (T != VDecl->getType()) {
9261 VDecl->setType(T);
9262 Result.get()->setType(T);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009263 }
John McCallb4eb64d2010-10-08 02:01:28 +00009264
Douglas Gregord24c3062011-10-10 16:05:18 +00009265
Richard Smithc6d990a2011-09-29 19:11:37 +00009266 Expr *Init = Result.get();
9267 CheckImplicitConversions(Init, LParenLoc);
Richard Smithc6d990a2011-09-29 19:11:37 +00009268
9269 Init = MaybeCreateExprWithCleanups(Init);
9270 VDecl->setInit(Init);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009271 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00009272
John McCall2998d6b2011-01-19 11:48:09 +00009273 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00009274}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00009275
Douglas Gregor39da0b82009-09-09 23:08:42 +00009276/// \brief Given a constructor and the set of arguments provided for the
9277/// constructor, convert the arguments and add any required default arguments
9278/// to form a proper call to this constructor.
9279///
9280/// \returns true if an error occurred, false otherwise.
9281bool
9282Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9283 MultiExprArg ArgsPtr,
9284 SourceLocation Loc,
John McCallca0408f2010-08-23 06:44:23 +00009285 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor39da0b82009-09-09 23:08:42 +00009286 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9287 unsigned NumArgs = ArgsPtr.size();
9288 Expr **Args = (Expr **)ArgsPtr.get();
9289
9290 const FunctionProtoType *Proto
9291 = Constructor->getType()->getAs<FunctionProtoType>();
9292 assert(Proto && "Constructor without a prototype?");
9293 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor39da0b82009-09-09 23:08:42 +00009294
9295 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009296 if (NumArgs < NumArgsInProto)
Douglas Gregor39da0b82009-09-09 23:08:42 +00009297 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009298 else
Douglas Gregor39da0b82009-09-09 23:08:42 +00009299 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009300
9301 VariadicCallType CallType =
9302 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009303 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00009304 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9305 Proto, 0, Args, NumArgs, AllArgs,
9306 CallType);
9307 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9308 ConvertedArgs.push_back(AllArgs[i]);
9309 return Invalid;
Douglas Gregor18fe5682008-11-03 20:45:27 +00009310}
9311
Anders Carlsson20d45d22009-12-12 00:32:00 +00009312static inline bool
9313CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9314 const FunctionDecl *FnDecl) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00009315 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlsson20d45d22009-12-12 00:32:00 +00009316 if (isa<NamespaceDecl>(DC)) {
9317 return SemaRef.Diag(FnDecl->getLocation(),
9318 diag::err_operator_new_delete_declared_in_namespace)
9319 << FnDecl->getDeclName();
9320 }
9321
9322 if (isa<TranslationUnitDecl>(DC) &&
John McCalld931b082010-08-26 03:08:43 +00009323 FnDecl->getStorageClass() == SC_Static) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009324 return SemaRef.Diag(FnDecl->getLocation(),
9325 diag::err_operator_new_delete_declared_static)
9326 << FnDecl->getDeclName();
9327 }
9328
Anders Carlssonfcfdb2b2009-12-12 02:43:16 +00009329 return false;
Anders Carlsson20d45d22009-12-12 00:32:00 +00009330}
9331
Anders Carlsson156c78e2009-12-13 17:53:43 +00009332static inline bool
9333CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9334 CanQualType ExpectedResultType,
9335 CanQualType ExpectedFirstParamType,
9336 unsigned DependentParamTypeDiag,
9337 unsigned InvalidParamTypeDiag) {
9338 QualType ResultType =
9339 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9340
9341 // Check that the result type is not dependent.
9342 if (ResultType->isDependentType())
9343 return SemaRef.Diag(FnDecl->getLocation(),
9344 diag::err_operator_new_delete_dependent_result_type)
9345 << FnDecl->getDeclName() << ExpectedResultType;
9346
9347 // Check that the result type is what we expect.
9348 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9349 return SemaRef.Diag(FnDecl->getLocation(),
9350 diag::err_operator_new_delete_invalid_result_type)
9351 << FnDecl->getDeclName() << ExpectedResultType;
9352
9353 // A function template must have at least 2 parameters.
9354 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9355 return SemaRef.Diag(FnDecl->getLocation(),
9356 diag::err_operator_new_delete_template_too_few_parameters)
9357 << FnDecl->getDeclName();
9358
9359 // The function decl must have at least 1 parameter.
9360 if (FnDecl->getNumParams() == 0)
9361 return SemaRef.Diag(FnDecl->getLocation(),
9362 diag::err_operator_new_delete_too_few_parameters)
9363 << FnDecl->getDeclName();
9364
9365 // Check the the first parameter type is not dependent.
9366 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9367 if (FirstParamType->isDependentType())
9368 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9369 << FnDecl->getDeclName() << ExpectedFirstParamType;
9370
9371 // Check that the first parameter type is what we expect.
Douglas Gregor6e790ab2009-12-22 23:42:49 +00009372 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson156c78e2009-12-13 17:53:43 +00009373 ExpectedFirstParamType)
9374 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9375 << FnDecl->getDeclName() << ExpectedFirstParamType;
9376
9377 return false;
9378}
9379
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009380static bool
Anders Carlsson156c78e2009-12-13 17:53:43 +00009381CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlsson20d45d22009-12-12 00:32:00 +00009382 // C++ [basic.stc.dynamic.allocation]p1:
9383 // A program is ill-formed if an allocation function is declared in a
9384 // namespace scope other than global scope or declared static in global
9385 // scope.
9386 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9387 return true;
Anders Carlsson156c78e2009-12-13 17:53:43 +00009388
9389 CanQualType SizeTy =
9390 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9391
9392 // C++ [basic.stc.dynamic.allocation]p1:
9393 // The return type shall be void*. The first parameter shall have type
9394 // std::size_t.
9395 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9396 SizeTy,
9397 diag::err_operator_new_dependent_param_type,
9398 diag::err_operator_new_param_type))
9399 return true;
9400
9401 // C++ [basic.stc.dynamic.allocation]p1:
9402 // The first parameter shall not have an associated default argument.
9403 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlssona3ccda52009-12-12 00:26:23 +00009404 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson156c78e2009-12-13 17:53:43 +00009405 diag::err_operator_new_default_arg)
9406 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9407
9408 return false;
Anders Carlssona3ccda52009-12-12 00:26:23 +00009409}
9410
9411static bool
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009412CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9413 // C++ [basic.stc.dynamic.deallocation]p1:
9414 // A program is ill-formed if deallocation functions are declared in a
9415 // namespace scope other than global scope or declared static in global
9416 // scope.
Anders Carlsson20d45d22009-12-12 00:32:00 +00009417 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9418 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009419
9420 // C++ [basic.stc.dynamic.deallocation]p2:
9421 // Each deallocation function shall return void and its first parameter
9422 // shall be void*.
Anders Carlsson156c78e2009-12-13 17:53:43 +00009423 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9424 SemaRef.Context.VoidPtrTy,
9425 diag::err_operator_delete_dependent_param_type,
9426 diag::err_operator_delete_param_type))
9427 return true;
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009428
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009429 return false;
9430}
9431
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009432/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9433/// of this overloaded operator is well-formed. If so, returns false;
9434/// otherwise, emits appropriate diagnostics and returns true.
9435bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009436 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009437 "Expected an overloaded operator declaration");
9438
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009439 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9440
Mike Stump1eb44332009-09-09 15:08:12 +00009441 // C++ [over.oper]p5:
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009442 // The allocation and deallocation functions, operator new,
9443 // operator new[], operator delete and operator delete[], are
9444 // described completely in 3.7.3. The attributes and restrictions
9445 // found in the rest of this subclause do not apply to them unless
9446 // explicitly stated in 3.7.3.
Anders Carlsson1152c392009-12-11 23:31:21 +00009447 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson9d59ecb2009-12-11 23:23:22 +00009448 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanianb03bfa52009-11-10 23:47:18 +00009449
Anders Carlssona3ccda52009-12-12 00:26:23 +00009450 if (Op == OO_New || Op == OO_Array_New)
9451 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009452
9453 // C++ [over.oper]p6:
9454 // An operator function shall either be a non-static member
9455 // function or be a non-member function and have at least one
9456 // parameter whose type is a class, a reference to a class, an
9457 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009458 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9459 if (MethodDecl->isStatic())
9460 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009461 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009462 } else {
9463 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009464 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9465 ParamEnd = FnDecl->param_end();
9466 Param != ParamEnd; ++Param) {
9467 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00009468 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9469 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009470 ClassOrEnumParam = true;
9471 break;
9472 }
9473 }
9474
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009475 if (!ClassOrEnumParam)
9476 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009477 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009478 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009479 }
9480
9481 // C++ [over.oper]p8:
9482 // An operator function cannot have default arguments (8.3.6),
9483 // except where explicitly stated below.
9484 //
Mike Stump1eb44332009-09-09 15:08:12 +00009485 // Only the function-call operator allows default arguments
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009486 // (C++ [over.call]p1).
9487 if (Op != OO_Call) {
9488 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9489 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson156c78e2009-12-13 17:53:43 +00009490 if ((*Param)->hasDefaultArg())
Mike Stump1eb44332009-09-09 15:08:12 +00009491 return Diag((*Param)->getLocation(),
Douglas Gregor61366e92008-12-24 00:01:03 +00009492 diag::err_operator_overload_default_arg)
Anders Carlsson156c78e2009-12-13 17:53:43 +00009493 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009494 }
9495 }
9496
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009497 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9498 { false, false, false }
9499#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9500 , { Unary, Binary, MemberOnly }
9501#include "clang/Basic/OperatorKinds.def"
9502 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009503
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009504 bool CanBeUnaryOperator = OperatorUses[Op][0];
9505 bool CanBeBinaryOperator = OperatorUses[Op][1];
9506 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009507
9508 // C++ [over.oper]p8:
9509 // [...] Operator functions cannot have more or fewer parameters
9510 // than the number required for the corresponding operator, as
9511 // described in the rest of this subclause.
Mike Stump1eb44332009-09-09 15:08:12 +00009512 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009513 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009514 if (Op != OO_Call &&
9515 ((NumParams == 1 && !CanBeUnaryOperator) ||
9516 (NumParams == 2 && !CanBeBinaryOperator) ||
9517 (NumParams < 1) || (NumParams > 2))) {
9518 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00009519 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009520 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009521 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009522 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00009523 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009524 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009525 assert(CanBeBinaryOperator &&
9526 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00009527 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00009528 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009529
Chris Lattner416e46f2008-11-21 07:57:12 +00009530 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009531 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009532 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00009533
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009534 // Overloaded operators other than operator() cannot be variadic.
9535 if (Op != OO_Call &&
John McCall183700f2009-09-21 23:43:11 +00009536 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009537 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009538 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009539 }
9540
9541 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009542 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9543 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00009544 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00009545 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009546 }
9547
9548 // C++ [over.inc]p1:
9549 // The user-defined function called operator++ implements the
9550 // prefix and postfix ++ operator. If this function is a member
9551 // function with no parameters, or a non-member function with one
9552 // parameter of class or enumeration type, it defines the prefix
9553 // increment operator ++ for objects of that type. If the function
9554 // is a member function with one parameter (which shall be of type
9555 // int) or a non-member function with two parameters (the second
9556 // of which shall be of type int), it defines the postfix
9557 // increment operator ++ for objects of that type.
9558 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9559 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9560 bool ParamIsInt = false;
John McCall183700f2009-09-21 23:43:11 +00009561 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009562 ParamIsInt = BT->getKind() == BuiltinType::Int;
9563
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00009564 if (!ParamIsInt)
9565 return Diag(LastParam->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00009566 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00009567 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009568 }
9569
Douglas Gregor43c7bad2008-11-17 16:14:12 +00009570 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00009571}
Chris Lattner5a003a42008-12-17 07:09:26 +00009572
Sean Hunta6c058d2010-01-13 09:01:02 +00009573/// CheckLiteralOperatorDeclaration - Check whether the declaration
9574/// of this literal operator function is well-formed. If so, returns
9575/// false; otherwise, emits appropriate diagnostics and returns true.
9576bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9577 DeclContext *DC = FnDecl->getDeclContext();
9578 Decl::Kind Kind = DC->getDeclKind();
9579 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9580 Kind != Decl::LinkageSpec) {
9581 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9582 << FnDecl->getDeclName();
9583 return true;
9584 }
9585
9586 bool Valid = false;
9587
Sean Hunt216c2782010-04-07 23:11:06 +00009588 // template <char...> type operator "" name() is the only valid template
9589 // signature, and the only valid signature with no parameters.
9590 if (FnDecl->param_size() == 0) {
9591 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9592 // Must have only one template parameter
9593 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9594 if (Params->size() == 1) {
9595 NonTypeTemplateParmDecl *PmDecl =
9596 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Sean Hunta6c058d2010-01-13 09:01:02 +00009597
Sean Hunt216c2782010-04-07 23:11:06 +00009598 // The template parameter must be a char parameter pack.
Sean Hunt216c2782010-04-07 23:11:06 +00009599 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9600 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9601 Valid = true;
9602 }
9603 }
9604 } else {
Sean Hunta6c058d2010-01-13 09:01:02 +00009605 // Check the first parameter
Sean Hunt216c2782010-04-07 23:11:06 +00009606 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9607
Sean Hunta6c058d2010-01-13 09:01:02 +00009608 QualType T = (*Param)->getType();
9609
Sean Hunt30019c02010-04-07 22:57:35 +00009610 // unsigned long long int, long double, and any character type are allowed
9611 // as the only parameters.
Sean Hunta6c058d2010-01-13 09:01:02 +00009612 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9613 Context.hasSameType(T, Context.LongDoubleTy) ||
9614 Context.hasSameType(T, Context.CharTy) ||
9615 Context.hasSameType(T, Context.WCharTy) ||
9616 Context.hasSameType(T, Context.Char16Ty) ||
9617 Context.hasSameType(T, Context.Char32Ty)) {
9618 if (++Param == FnDecl->param_end())
9619 Valid = true;
9620 goto FinishedParams;
9621 }
9622
Sean Hunt30019c02010-04-07 22:57:35 +00009623 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Sean Hunta6c058d2010-01-13 09:01:02 +00009624 const PointerType *PT = T->getAs<PointerType>();
9625 if (!PT)
9626 goto FinishedParams;
9627 T = PT->getPointeeType();
9628 if (!T.isConstQualified())
9629 goto FinishedParams;
9630 T = T.getUnqualifiedType();
9631
9632 // Move on to the second parameter;
9633 ++Param;
9634
9635 // If there is no second parameter, the first must be a const char *
9636 if (Param == FnDecl->param_end()) {
9637 if (Context.hasSameType(T, Context.CharTy))
9638 Valid = true;
9639 goto FinishedParams;
9640 }
9641
9642 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9643 // are allowed as the first parameter to a two-parameter function
9644 if (!(Context.hasSameType(T, Context.CharTy) ||
9645 Context.hasSameType(T, Context.WCharTy) ||
9646 Context.hasSameType(T, Context.Char16Ty) ||
9647 Context.hasSameType(T, Context.Char32Ty)))
9648 goto FinishedParams;
9649
9650 // The second and final parameter must be an std::size_t
9651 T = (*Param)->getType().getUnqualifiedType();
9652 if (Context.hasSameType(T, Context.getSizeType()) &&
9653 ++Param == FnDecl->param_end())
9654 Valid = true;
9655 }
9656
9657 // FIXME: This diagnostic is absolutely terrible.
9658FinishedParams:
9659 if (!Valid) {
9660 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9661 << FnDecl->getDeclName();
9662 return true;
9663 }
9664
Douglas Gregor1155c422011-08-30 22:40:35 +00009665 StringRef LiteralName
9666 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9667 if (LiteralName[0] != '_') {
9668 // C++0x [usrlit.suffix]p1:
9669 // Literal suffix identifiers that do not start with an underscore are
9670 // reserved for future standardization.
9671 bool IsHexFloat = true;
9672 if (LiteralName.size() > 1 &&
9673 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9674 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9675 if (!isdigit(LiteralName[I])) {
9676 IsHexFloat = false;
9677 break;
9678 }
9679 }
9680 }
9681
9682 if (IsHexFloat)
9683 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9684 << LiteralName;
9685 else
9686 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9687 }
9688
Sean Hunta6c058d2010-01-13 09:01:02 +00009689 return false;
9690}
9691
Douglas Gregor074149e2009-01-05 19:45:36 +00009692/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9693/// linkage specification, including the language and (if present)
9694/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9695/// the location of the language string literal, which is provided
9696/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9697/// the '{' brace. Otherwise, this linkage specification does not
9698/// have any braces.
Chris Lattner7d642712010-11-09 20:15:55 +00009699Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9700 SourceLocation LangLoc,
Chris Lattner5f9e2722011-07-23 10:55:15 +00009701 StringRef Lang,
Chris Lattner7d642712010-11-09 20:15:55 +00009702 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00009703 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009704 if (Lang == "\"C\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009705 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerd5663812010-05-03 13:08:54 +00009706 else if (Lang == "\"C++\"")
Chris Lattnercc98eac2008-12-17 07:13:27 +00009707 Language = LinkageSpecDecl::lang_cxx;
9708 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00009709 Diag(LangLoc, diag::err_bad_language);
John McCalld226f652010-08-21 09:40:31 +00009710 return 0;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009711 }
Mike Stump1eb44332009-09-09 15:08:12 +00009712
Chris Lattnercc98eac2008-12-17 07:13:27 +00009713 // FIXME: Add all the various semantics of linkage specifications
Mike Stump1eb44332009-09-09 15:08:12 +00009714
Douglas Gregor074149e2009-01-05 19:45:36 +00009715 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009716 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009717 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00009718 PushDeclContext(S, D);
John McCalld226f652010-08-21 09:40:31 +00009719 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00009720}
9721
Abramo Bagnara35f9a192010-07-30 16:47:02 +00009722/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor074149e2009-01-05 19:45:36 +00009723/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9724/// valid, it's the position of the closing '}' brace in a linkage
9725/// specification that uses braces.
John McCalld226f652010-08-21 09:40:31 +00009726Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009727 Decl *LinkageSpec,
9728 SourceLocation RBraceLoc) {
9729 if (LinkageSpec) {
9730 if (RBraceLoc.isValid()) {
9731 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9732 LSDecl->setRBraceLoc(RBraceLoc);
9733 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009734 PopDeclContext();
Abramo Bagnara5f6bcbe2011-03-03 14:52:38 +00009735 }
Douglas Gregor074149e2009-01-05 19:45:36 +00009736 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00009737}
9738
Douglas Gregord308e622009-05-18 20:51:54 +00009739/// \brief Perform semantic analysis for the variable declaration that
9740/// occurs within a C++ catch clause, returning the newly-created
9741/// variable.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009742VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCalla93c9342009-12-07 02:54:59 +00009743 TypeSourceInfo *TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009744 SourceLocation StartLoc,
9745 SourceLocation Loc,
9746 IdentifierInfo *Name) {
Douglas Gregord308e622009-05-18 20:51:54 +00009747 bool Invalid = false;
Douglas Gregor83cb9422010-09-09 17:09:21 +00009748 QualType ExDeclType = TInfo->getType();
9749
Sebastian Redl4b07b292008-12-22 19:15:10 +00009750 // Arrays and functions decay.
9751 if (ExDeclType->isArrayType())
9752 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9753 else if (ExDeclType->isFunctionType())
9754 ExDeclType = Context.getPointerType(ExDeclType);
9755
9756 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9757 // The exception-declaration shall not denote a pointer or reference to an
9758 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009759 // N2844 forbids rvalue references.
Mike Stump1eb44332009-09-09 15:08:12 +00009760 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00009761 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009762 Invalid = true;
9763 }
Douglas Gregord308e622009-05-18 20:51:54 +00009764
Sebastian Redl4b07b292008-12-22 19:15:10 +00009765 QualType BaseType = ExDeclType;
9766 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00009767 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00009768 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009769 BaseType = Ptr->getPointeeType();
9770 Mode = 1;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009771 DK = diag::err_catch_incomplete_ptr;
Mike Stump1eb44332009-09-09 15:08:12 +00009772 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009773 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009774 BaseType = Ref->getPointeeType();
9775 Mode = 2;
Douglas Gregorecd7b042012-01-24 19:01:26 +00009776 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009777 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00009778 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorecd7b042012-01-24 19:01:26 +00009779 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00009780 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009781
Mike Stump1eb44332009-09-09 15:08:12 +00009782 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregord308e622009-05-18 20:51:54 +00009783 RequireNonAbstractType(Loc, ExDeclType,
9784 diag::err_abstract_type_in_decl,
9785 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00009786 Invalid = true;
9787
John McCall5a180392010-07-24 00:37:23 +00009788 // Only the non-fragile NeXT runtime currently supports C++ catches
9789 // of ObjC types, and no runtime supports catching ObjC types by value.
9790 if (!Invalid && getLangOptions().ObjC1) {
9791 QualType T = ExDeclType;
9792 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9793 T = RT->getPointeeType();
9794
9795 if (T->isObjCObjectType()) {
9796 Diag(Loc, diag::err_objc_object_catch);
9797 Invalid = true;
9798 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahaniancf5abc72011-06-23 19:00:08 +00009799 if (!getLangOptions().ObjCNonFragileABI)
9800 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall5a180392010-07-24 00:37:23 +00009801 }
9802 }
9803
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009804 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9805 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00009806 ExDecl->setExceptionVariable(true);
9807
Douglas Gregor9aab9c42011-12-10 01:22:52 +00009808 // In ARC, infer 'retaining' for variables of retainable type.
9809 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9810 Invalid = true;
9811
Douglas Gregorc41b8782011-07-06 18:14:43 +00009812 if (!Invalid && !ExDeclType->isDependentType()) {
John McCalle996ffd2011-02-16 08:02:54 +00009813 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6d182892010-03-05 23:38:39 +00009814 // C++ [except.handle]p16:
9815 // The object declared in an exception-declaration or, if the
9816 // exception-declaration does not specify a name, a temporary (12.2) is
9817 // copy-initialized (8.5) from the exception object. [...]
9818 // The object is destroyed when the handler exits, after the destruction
9819 // of any automatic objects initialized within the handler.
9820 //
9821 // We just pretend to initialize the object with itself, then make sure
9822 // it can be destroyed later.
John McCalle996ffd2011-02-16 08:02:54 +00009823 QualType initType = ExDeclType;
9824
9825 InitializedEntity entity =
9826 InitializedEntity::InitializeVariable(ExDecl);
9827 InitializationKind initKind =
9828 InitializationKind::CreateCopy(Loc, SourceLocation());
9829
9830 Expr *opaqueValue =
9831 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9832 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9833 ExprResult result = sequence.Perform(*this, entity, initKind,
9834 MultiExprArg(&opaqueValue, 1));
9835 if (result.isInvalid())
Douglas Gregor6d182892010-03-05 23:38:39 +00009836 Invalid = true;
John McCalle996ffd2011-02-16 08:02:54 +00009837 else {
9838 // If the constructor used was non-trivial, set this as the
9839 // "initializer".
9840 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9841 if (!construct->getConstructor()->isTrivial()) {
9842 Expr *init = MaybeCreateExprWithCleanups(construct);
9843 ExDecl->setInit(init);
9844 }
9845
9846 // And make sure it's destructable.
9847 FinalizeVarWithDestructor(ExDecl, recordType);
9848 }
Douglas Gregor6d182892010-03-05 23:38:39 +00009849 }
9850 }
9851
Douglas Gregord308e622009-05-18 20:51:54 +00009852 if (Invalid)
9853 ExDecl->setInvalidDecl();
9854
9855 return ExDecl;
9856}
9857
9858/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9859/// handler.
John McCalld226f652010-08-21 09:40:31 +00009860Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbf1a0282010-06-04 23:28:52 +00009861 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregora669c532010-12-16 17:48:04 +00009862 bool Invalid = D.isInvalidType();
9863
9864 // Check for unexpanded parameter packs.
9865 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9866 UPPC_ExceptionType)) {
9867 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9868 D.getIdentifierLoc());
9869 Invalid = true;
9870 }
9871
Sebastian Redl4b07b292008-12-22 19:15:10 +00009872 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +00009873 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +00009874 LookupOrdinaryName,
9875 ForRedeclaration)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009876 // The scope should be freshly made just for us. There is just no way
9877 // it contains any previous declaration.
John McCalld226f652010-08-21 09:40:31 +00009878 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl4b07b292008-12-22 19:15:10 +00009879 if (PrevDecl->isTemplateParameter()) {
9880 // Maybe we will complain about the shadowed template parameter.
9881 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorcb8f9512011-10-20 17:58:49 +00009882 PrevDecl = 0;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009883 }
9884 }
9885
Chris Lattnereaaebc72009-04-25 08:06:05 +00009886 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00009887 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9888 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00009889 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009890 }
9891
Douglas Gregor83cb9422010-09-09 17:09:21 +00009892 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00009893 D.getSourceRange().getBegin(),
9894 D.getIdentifierLoc(),
9895 D.getIdentifier());
Chris Lattnereaaebc72009-04-25 08:06:05 +00009896 if (Invalid)
9897 ExDecl->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00009898
Sebastian Redl4b07b292008-12-22 19:15:10 +00009899 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00009900 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00009901 PushOnScopeChains(ExDecl, S);
9902 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009903 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00009904
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00009905 ProcessDeclAttributes(S, ExDecl, D);
John McCalld226f652010-08-21 09:40:31 +00009906 return ExDecl;
Sebastian Redl4b07b292008-12-22 19:15:10 +00009907}
Anders Carlssonfb311762009-03-14 00:25:26 +00009908
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009909Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009910 Expr *AssertExpr,
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009911 Expr *AssertMessageExpr_,
9912 SourceLocation RParenLoc) {
John McCall9ae2f072010-08-23 23:25:46 +00009913 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlssonfb311762009-03-14 00:25:26 +00009914
Anders Carlssonc3082412009-03-14 00:33:21 +00009915 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smith282e7e62012-02-04 09:53:13 +00009916 // In a static_assert-declaration, the constant-expression shall be a
9917 // constant expression that can be contextually converted to bool.
9918 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9919 if (Converted.isInvalid())
9920 return 0;
9921
Richard Smithdaaefc52011-12-14 23:32:26 +00009922 llvm::APSInt Cond;
Richard Smith282e7e62012-02-04 09:53:13 +00009923 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9924 PDiag(diag::err_static_assert_expression_is_not_constant),
9925 /*AllowFold=*/false).isInvalid())
John McCalld226f652010-08-21 09:40:31 +00009926 return 0;
Anders Carlssonfb311762009-03-14 00:25:26 +00009927
Richard Smithdaaefc52011-12-14 23:32:26 +00009928 if (!Cond)
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009929 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramer8d042582009-12-11 13:33:18 +00009930 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00009931 }
Mike Stump1eb44332009-09-09 15:08:12 +00009932
Douglas Gregor399ad972010-12-15 23:55:21 +00009933 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9934 return 0;
9935
Abramo Bagnaraa2026c92011-03-08 16:41:52 +00009936 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9937 AssertExpr, AssertMessage, RParenLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00009938
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00009939 CurContext->addDecl(Decl);
John McCalld226f652010-08-21 09:40:31 +00009940 return Decl;
Anders Carlssonfb311762009-03-14 00:25:26 +00009941}
Sebastian Redl50de12f2009-03-24 22:27:57 +00009942
Douglas Gregor1d869352010-04-07 16:53:43 +00009943/// \brief Perform semantic analysis of the given friend type declaration.
9944///
9945/// \returns A friend declaration that.
Abramo Bagnara0216df82011-10-29 20:52:52 +00009946FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9947 SourceLocation FriendLoc,
Douglas Gregor1d869352010-04-07 16:53:43 +00009948 TypeSourceInfo *TSInfo) {
9949 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9950
9951 QualType T = TSInfo->getType();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00009952 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor1d869352010-04-07 16:53:43 +00009953
Richard Smith6b130222011-10-18 21:39:00 +00009954 // C++03 [class.friend]p2:
9955 // An elaborated-type-specifier shall be used in a friend declaration
9956 // for a class.*
9957 //
9958 // * The class-key of the elaborated-type-specifier is required.
9959 if (!ActiveTemplateInstantiations.empty()) {
9960 // Do not complain about the form of friend template types during
9961 // template instantiation; we will already have complained when the
9962 // template was declared.
9963 } else if (!T->isElaboratedTypeSpecifier()) {
9964 // If we evaluated the type to a record type, suggest putting
9965 // a tag in front.
9966 if (const RecordType *RT = T->getAs<RecordType>()) {
9967 RecordDecl *RD = RT->getDecl();
9968
9969 std::string InsertionText = std::string(" ") + RD->getKindName();
9970
9971 Diag(TypeRange.getBegin(),
9972 getLangOptions().CPlusPlus0x ?
9973 diag::warn_cxx98_compat_unelaborated_friend_type :
9974 diag::ext_unelaborated_friend_type)
9975 << (unsigned) RD->getTagKind()
9976 << T
9977 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9978 InsertionText);
9979 } else {
9980 Diag(FriendLoc,
9981 getLangOptions().CPlusPlus0x ?
9982 diag::warn_cxx98_compat_nonclass_type_friend :
9983 diag::ext_nonclass_type_friend)
Douglas Gregor1d869352010-04-07 16:53:43 +00009984 << T
Douglas Gregor1d869352010-04-07 16:53:43 +00009985 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009986 }
Richard Smith6b130222011-10-18 21:39:00 +00009987 } else if (T->getAs<EnumType>()) {
9988 Diag(FriendLoc,
9989 getLangOptions().CPlusPlus0x ?
9990 diag::warn_cxx98_compat_enum_friend :
9991 diag::ext_enum_friend)
9992 << T
9993 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregor1d869352010-04-07 16:53:43 +00009994 }
9995
Douglas Gregor06245bf2010-04-07 17:57:12 +00009996 // C++0x [class.friend]p3:
9997 // If the type specifier in a friend declaration designates a (possibly
9998 // cv-qualified) class type, that class is declared as a friend; otherwise,
9999 // the friend declaration is ignored.
10000
10001 // FIXME: C++0x has some syntactic restrictions on friend type declarations
10002 // in [class.friend]p3 that we do not implement.
Douglas Gregor1d869352010-04-07 16:53:43 +000010003
Abramo Bagnara0216df82011-10-29 20:52:52 +000010004 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregor1d869352010-04-07 16:53:43 +000010005}
10006
John McCall9a34edb2010-10-19 01:40:49 +000010007/// Handle a friend tag declaration where the scope specifier was
10008/// templated.
10009Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10010 unsigned TagSpec, SourceLocation TagLoc,
10011 CXXScopeSpec &SS,
10012 IdentifierInfo *Name, SourceLocation NameLoc,
10013 AttributeList *Attr,
10014 MultiTemplateParamsArg TempParamLists) {
10015 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10016
10017 bool isExplicitSpecialization = false;
John McCall9a34edb2010-10-19 01:40:49 +000010018 bool Invalid = false;
10019
10020 if (TemplateParameterList *TemplateParams
Douglas Gregorc8406492011-05-10 18:27:06 +000010021 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCall9a34edb2010-10-19 01:40:49 +000010022 TempParamLists.get(),
10023 TempParamLists.size(),
10024 /*friend*/ true,
10025 isExplicitSpecialization,
10026 Invalid)) {
John McCall9a34edb2010-10-19 01:40:49 +000010027 if (TemplateParams->size() > 0) {
10028 // This is a declaration of a class template.
10029 if (Invalid)
10030 return 0;
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010031
Eric Christopher4110e132011-07-21 05:34:24 +000010032 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10033 SS, Name, NameLoc, Attr,
10034 TemplateParams, AS_public,
Douglas Gregore7612302011-09-09 19:05:14 +000010035 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher4110e132011-07-21 05:34:24 +000010036 TempParamLists.size() - 1,
Abramo Bagnarac57c17d2011-03-10 13:28:31 +000010037 (TemplateParameterList**) TempParamLists.release()).take();
John McCall9a34edb2010-10-19 01:40:49 +000010038 } else {
10039 // The "template<>" header is extraneous.
10040 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10041 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10042 isExplicitSpecialization = true;
10043 }
10044 }
10045
10046 if (Invalid) return 0;
10047
John McCall9a34edb2010-10-19 01:40:49 +000010048 bool isAllExplicitSpecializations = true;
Abramo Bagnara7f0a9152011-03-18 15:16:37 +000010049 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCall9a34edb2010-10-19 01:40:49 +000010050 if (TempParamLists.get()[I]->size()) {
10051 isAllExplicitSpecializations = false;
10052 break;
10053 }
10054 }
10055
10056 // FIXME: don't ignore attributes.
10057
10058 // If it's explicit specializations all the way down, just forget
10059 // about the template header and build an appropriate non-templated
10060 // friend. TODO: for source fidelity, remember the headers.
10061 if (isAllExplicitSpecializations) {
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010062 if (SS.isEmpty()) {
10063 bool Owned = false;
10064 bool IsDependent = false;
10065 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10066 Attr, AS_public,
10067 /*ModulePrivateLoc=*/SourceLocation(),
10068 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smithbdad7a22012-01-10 01:33:14 +000010069 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010070 /*ScopedEnumUsesClassTag=*/false,
10071 /*UnderlyingType=*/TypeResult());
10072 }
10073
Douglas Gregor2494dd02011-03-01 01:34:45 +000010074 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall9a34edb2010-10-19 01:40:49 +000010075 ElaboratedTypeKeyword Keyword
10076 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010077 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregore29425b2011-02-28 22:42:13 +000010078 *Name, NameLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010079 if (T.isNull())
10080 return 0;
10081
10082 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10083 if (isa<DependentNameType>(T)) {
10084 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010085 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010086 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010087 TL.setNameLoc(NameLoc);
10088 } else {
10089 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010090 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor9e876872011-03-01 18:12:44 +000010091 TL.setQualifierLoc(QualifierLoc);
John McCall9a34edb2010-10-19 01:40:49 +000010092 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10093 }
10094
10095 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10096 TSI, FriendLoc);
10097 Friend->setAccess(AS_public);
10098 CurContext->addDecl(Friend);
10099 return Friend;
10100 }
Douglas Gregorba4ee9a2011-10-20 15:58:54 +000010101
10102 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10103
10104
John McCall9a34edb2010-10-19 01:40:49 +000010105
10106 // Handle the case of a templated-scope friend class. e.g.
10107 // template <class T> class A<T>::B;
10108 // FIXME: we don't support these right now.
10109 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10110 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10111 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10112 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara38a42912012-02-06 19:09:27 +000010113 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor2494dd02011-03-01 01:34:45 +000010114 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCall9a34edb2010-10-19 01:40:49 +000010115 TL.setNameLoc(NameLoc);
10116
10117 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10118 TSI, FriendLoc);
10119 Friend->setAccess(AS_public);
10120 Friend->setUnsupportedFriend(true);
10121 CurContext->addDecl(Friend);
10122 return Friend;
10123}
10124
10125
John McCalldd4a3b02009-09-16 22:47:08 +000010126/// Handle a friend type declaration. This works in tandem with
10127/// ActOnTag.
10128///
10129/// Notes on friend class templates:
10130///
10131/// We generally treat friend class declarations as if they were
10132/// declaring a class. So, for example, the elaborated type specifier
10133/// in a friend declaration is required to obey the restrictions of a
10134/// class-head (i.e. no typedefs in the scope chain), template
10135/// parameters are required to match up with simple template-ids, &c.
10136/// However, unlike when declaring a template specialization, it's
10137/// okay to refer to a template specialization without an empty
10138/// template parameter declaration, e.g.
10139/// friend class A<T>::B<unsigned>;
10140/// We permit this as a special case; if there are any template
10141/// parameters present at all, require proper matching, i.e.
10142/// template <> template <class T> friend class A<int>::B;
John McCalld226f652010-08-21 09:40:31 +000010143Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallbe04b6d2010-10-16 07:23:36 +000010144 MultiTemplateParamsArg TempParams) {
John McCall02cace72009-08-28 07:59:38 +000010145 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +000010146
10147 assert(DS.isFriendSpecified());
10148 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10149
John McCalldd4a3b02009-09-16 22:47:08 +000010150 // Try to convert the decl specifier to a type. This works for
10151 // friend templates because ActOnTag never produces a ClassTemplateDecl
10152 // for a TUK_Friend.
Chris Lattnerc7f19042009-10-25 17:47:27 +000010153 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCallbf1a0282010-06-04 23:28:52 +000010154 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10155 QualType T = TSI->getType();
Chris Lattnerc7f19042009-10-25 17:47:27 +000010156 if (TheDeclarator.isInvalidType())
John McCalld226f652010-08-21 09:40:31 +000010157 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010158
Douglas Gregor6ccab972010-12-16 01:14:37 +000010159 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10160 return 0;
10161
John McCalldd4a3b02009-09-16 22:47:08 +000010162 // This is definitely an error in C++98. It's probably meant to
10163 // be forbidden in C++0x, too, but the specification is just
10164 // poorly written.
10165 //
10166 // The problem is with declarations like the following:
10167 // template <T> friend A<T>::foo;
10168 // where deciding whether a class C is a friend or not now hinges
10169 // on whether there exists an instantiation of A that causes
10170 // 'foo' to equal C. There are restrictions on class-heads
10171 // (which we declare (by fiat) elaborated friend declarations to
10172 // be) that makes this tractable.
10173 //
10174 // FIXME: handle "template <> friend class A<T>;", which
10175 // is possibly well-formed? Who even knows?
Douglas Gregor40336422010-03-31 22:19:08 +000010176 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCalldd4a3b02009-09-16 22:47:08 +000010177 Diag(Loc, diag::err_tagless_friend_type_template)
10178 << DS.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +000010179 return 0;
John McCalldd4a3b02009-09-16 22:47:08 +000010180 }
Douglas Gregor1d869352010-04-07 16:53:43 +000010181
John McCall02cace72009-08-28 07:59:38 +000010182 // C++98 [class.friend]p1: A friend of a class is a function
10183 // or class that is not a member of the class . . .
John McCalla236a552009-12-22 00:59:39 +000010184 // This is fixed in DR77, which just barely didn't make the C++03
10185 // deadline. It's also a very silly restriction that seriously
10186 // affects inner classes and which nobody else seems to implement;
10187 // thus we never diagnose it, not even in -pedantic.
John McCall32f2fb52010-03-25 18:04:51 +000010188 //
10189 // But note that we could warn about it: it's always useless to
10190 // friend one of your own members (it's not, however, worthless to
10191 // friend a member of an arbitrary specialization of your template).
John McCall02cace72009-08-28 07:59:38 +000010192
John McCalldd4a3b02009-09-16 22:47:08 +000010193 Decl *D;
Douglas Gregor1d869352010-04-07 16:53:43 +000010194 if (unsigned NumTempParamLists = TempParams.size())
John McCalldd4a3b02009-09-16 22:47:08 +000010195 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregor1d869352010-04-07 16:53:43 +000010196 NumTempParamLists,
John McCallbe04b6d2010-10-16 07:23:36 +000010197 TempParams.release(),
John McCall32f2fb52010-03-25 18:04:51 +000010198 TSI,
John McCalldd4a3b02009-09-16 22:47:08 +000010199 DS.getFriendSpecLoc());
10200 else
Abramo Bagnara0216df82011-10-29 20:52:52 +000010201 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregor1d869352010-04-07 16:53:43 +000010202
10203 if (!D)
John McCalld226f652010-08-21 09:40:31 +000010204 return 0;
Douglas Gregor1d869352010-04-07 16:53:43 +000010205
John McCalldd4a3b02009-09-16 22:47:08 +000010206 D->setAccess(AS_public);
10207 CurContext->addDecl(D);
John McCall02cace72009-08-28 07:59:38 +000010208
John McCalld226f652010-08-21 09:40:31 +000010209 return D;
John McCall02cace72009-08-28 07:59:38 +000010210}
10211
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010212Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCall337ec3d2010-10-12 23:13:28 +000010213 MultiTemplateParamsArg TemplateParams) {
John McCall02cace72009-08-28 07:59:38 +000010214 const DeclSpec &DS = D.getDeclSpec();
10215
10216 assert(DS.isFriendSpecified());
10217 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10218
10219 SourceLocation Loc = D.getIdentifierLoc();
John McCallbf1a0282010-06-04 23:28:52 +000010220 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall67d1a672009-08-06 02:15:43 +000010221
10222 // C++ [class.friend]p1
10223 // A friend of a class is a function or class....
10224 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +000010225 // It *doesn't* see through dependent types, which is correct
10226 // according to [temp.arg.type]p3:
10227 // If a declaration acquires a function type through a
10228 // type dependent on a template-parameter and this causes
10229 // a declaration that does not use the syntactic form of a
10230 // function declarator to have a function type, the program
10231 // is ill-formed.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010232 if (!TInfo->getType()->isFunctionType()) {
John McCall67d1a672009-08-06 02:15:43 +000010233 Diag(Loc, diag::err_unexpected_friend);
10234
10235 // It might be worthwhile to try to recover by creating an
10236 // appropriate declaration.
John McCalld226f652010-08-21 09:40:31 +000010237 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010238 }
10239
10240 // C++ [namespace.memdef]p3
10241 // - If a friend declaration in a non-local class first declares a
10242 // class or function, the friend class or function is a member
10243 // of the innermost enclosing namespace.
10244 // - The name of the friend is not found by simple name lookup
10245 // until a matching declaration is provided in that namespace
10246 // scope (either before or after the class declaration granting
10247 // friendship).
10248 // - If a friend function is called, its name may be found by the
10249 // name lookup that considers functions from namespaces and
10250 // classes associated with the types of the function arguments.
10251 // - When looking for a prior declaration of a class or a function
10252 // declared as a friend, scopes outside the innermost enclosing
10253 // namespace scope are not considered.
10254
John McCall337ec3d2010-10-12 23:13:28 +000010255 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnara25777432010-08-11 22:01:17 +000010256 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10257 DeclarationName Name = NameInfo.getName();
John McCall67d1a672009-08-06 02:15:43 +000010258 assert(Name);
10259
Douglas Gregor6ccab972010-12-16 01:14:37 +000010260 // Check for unexpanded parameter packs.
10261 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10262 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10263 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10264 return 0;
10265
John McCall67d1a672009-08-06 02:15:43 +000010266 // The context we found the declaration in, or in which we should
10267 // create the declaration.
10268 DeclContext *DC;
John McCall380aaa42010-10-13 06:22:15 +000010269 Scope *DCScope = S;
Abramo Bagnara25777432010-08-11 22:01:17 +000010270 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall68263142009-11-18 22:49:29 +000010271 ForRedeclaration);
John McCall67d1a672009-08-06 02:15:43 +000010272
John McCall337ec3d2010-10-12 23:13:28 +000010273 // FIXME: there are different rules in local classes
John McCall67d1a672009-08-06 02:15:43 +000010274
John McCall337ec3d2010-10-12 23:13:28 +000010275 // There are four cases here.
10276 // - There's no scope specifier, in which case we just go to the
John McCall29ae6e52010-10-13 05:45:15 +000010277 // appropriate scope and look for a function or function template
John McCall337ec3d2010-10-12 23:13:28 +000010278 // there as appropriate.
10279 // Recover from invalid scope qualifiers as if they just weren't there.
10280 if (SS.isInvalid() || !SS.isSet()) {
John McCall29ae6e52010-10-13 05:45:15 +000010281 // C++0x [namespace.memdef]p3:
10282 // If the name in a friend declaration is neither qualified nor
10283 // a template-id and the declaration is a function or an
10284 // elaborated-type-specifier, the lookup to determine whether
10285 // the entity has been previously declared shall not consider
10286 // any scopes outside the innermost enclosing namespace.
10287 // C++0x [class.friend]p11:
10288 // If a friend declaration appears in a local class and the name
10289 // specified is an unqualified name, a prior declaration is
10290 // looked up without considering scopes that are outside the
10291 // innermost enclosing non-class scope. For a friend function
10292 // declaration, if there is no prior declaration, the program is
10293 // ill-formed.
10294 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCall8a407372010-10-14 22:22:28 +000010295 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall67d1a672009-08-06 02:15:43 +000010296
John McCall29ae6e52010-10-13 05:45:15 +000010297 // Find the appropriate context according to the above.
John McCall67d1a672009-08-06 02:15:43 +000010298 DC = CurContext;
10299 while (true) {
10300 // Skip class contexts. If someone can cite chapter and verse
10301 // for this behavior, that would be nice --- it's what GCC and
10302 // EDG do, and it seems like a reasonable intent, but the spec
10303 // really only says that checks for unqualified existing
10304 // declarations should stop at the nearest enclosing namespace,
10305 // not that they should only consider the nearest enclosing
10306 // namespace.
Douglas Gregor182ddf02009-09-28 00:08:27 +000010307 while (DC->isRecord())
10308 DC = DC->getParent();
John McCall67d1a672009-08-06 02:15:43 +000010309
John McCall68263142009-11-18 22:49:29 +000010310 LookupQualifiedName(Previous, DC);
John McCall67d1a672009-08-06 02:15:43 +000010311
10312 // TODO: decide what we think about using declarations.
John McCall29ae6e52010-10-13 05:45:15 +000010313 if (isLocal || !Previous.empty())
John McCall67d1a672009-08-06 02:15:43 +000010314 break;
John McCall29ae6e52010-10-13 05:45:15 +000010315
John McCall8a407372010-10-14 22:22:28 +000010316 if (isTemplateId) {
10317 if (isa<TranslationUnitDecl>(DC)) break;
10318 } else {
10319 if (DC->isFileContext()) break;
10320 }
John McCall67d1a672009-08-06 02:15:43 +000010321 DC = DC->getParent();
10322 }
10323
10324 // C++ [class.friend]p1: A friend of a class is a function or
10325 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010326 // C++11 changes this for both friend types and functions.
John McCall7f27d922009-08-06 20:49:32 +000010327 // Most C++ 98 compilers do seem to give an error here, so
10328 // we do, too.
Richard Smithebaf0e62011-10-18 20:49:44 +000010329 if (!Previous.empty() && DC->Equals(CurContext))
10330 Diag(DS.getFriendSpecLoc(),
10331 getLangOptions().CPlusPlus0x ?
10332 diag::warn_cxx98_compat_friend_is_member :
10333 diag::err_friend_is_member);
John McCall337ec3d2010-10-12 23:13:28 +000010334
John McCall380aaa42010-10-13 06:22:15 +000010335 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010336
Douglas Gregor883af832011-10-10 01:11:59 +000010337 // C++ [class.friend]p6:
10338 // A function can be defined in a friend declaration of a class if and
10339 // only if the class is a non-local class (9.8), the function name is
10340 // unqualified, and the function has namespace scope.
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010341 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010342 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10343 }
10344
John McCall337ec3d2010-10-12 23:13:28 +000010345 // - There's a non-dependent scope specifier, in which case we
10346 // compute it and do a previous lookup there for a function
10347 // or function template.
10348 } else if (!SS.getScopeRep()->isDependent()) {
10349 DC = computeDeclContext(SS);
10350 if (!DC) return 0;
10351
10352 if (RequireCompleteDeclContext(SS, DC)) return 0;
10353
10354 LookupQualifiedName(Previous, DC);
10355
10356 // Ignore things found implicitly in the wrong scope.
10357 // TODO: better diagnostics for this case. Suggesting the right
10358 // qualified scope would be nice...
10359 LookupResult::Filter F = Previous.makeFilter();
10360 while (F.hasNext()) {
10361 NamedDecl *D = F.next();
10362 if (!DC->InEnclosingNamespaceSetOf(
10363 D->getDeclContext()->getRedeclContext()))
10364 F.erase();
10365 }
10366 F.done();
10367
10368 if (Previous.empty()) {
10369 D.setInvalidType();
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010370 Diag(Loc, diag::err_qualified_friend_not_found)
10371 << Name << TInfo->getType();
John McCall337ec3d2010-10-12 23:13:28 +000010372 return 0;
10373 }
10374
10375 // C++ [class.friend]p1: A friend of a class is a function or
10376 // class that is not a member of the class . . .
Richard Smithebaf0e62011-10-18 20:49:44 +000010377 if (DC->Equals(CurContext))
10378 Diag(DS.getFriendSpecLoc(),
10379 getLangOptions().CPlusPlus0x ?
10380 diag::warn_cxx98_compat_friend_is_member :
10381 diag::err_friend_is_member);
Douglas Gregor883af832011-10-10 01:11:59 +000010382
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010383 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010384 // C++ [class.friend]p6:
10385 // A function can be defined in a friend declaration of a class if and
10386 // only if the class is a non-local class (9.8), the function name is
10387 // unqualified, and the function has namespace scope.
10388 SemaDiagnosticBuilder DB
10389 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10390
10391 DB << SS.getScopeRep();
10392 if (DC->isFileContext())
10393 DB << FixItHint::CreateRemoval(SS.getRange());
10394 SS.clear();
10395 }
John McCall337ec3d2010-10-12 23:13:28 +000010396
10397 // - There's a scope specifier that does not match any template
10398 // parameter lists, in which case we use some arbitrary context,
10399 // create a method or method template, and wait for instantiation.
10400 // - There's a scope specifier that does match some template
10401 // parameter lists, which we don't handle right now.
10402 } else {
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010403 if (D.isFunctionDefinition()) {
Douglas Gregor883af832011-10-10 01:11:59 +000010404 // C++ [class.friend]p6:
10405 // A function can be defined in a friend declaration of a class if and
10406 // only if the class is a non-local class (9.8), the function name is
10407 // unqualified, and the function has namespace scope.
10408 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10409 << SS.getScopeRep();
10410 }
10411
John McCall337ec3d2010-10-12 23:13:28 +000010412 DC = CurContext;
10413 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall67d1a672009-08-06 02:15:43 +000010414 }
Douglas Gregor883af832011-10-10 01:11:59 +000010415
John McCall29ae6e52010-10-13 05:45:15 +000010416 if (!DC->isRecord()) {
John McCall67d1a672009-08-06 02:15:43 +000010417 // This implies that it has to be an operator or function.
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010418 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10419 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10420 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall67d1a672009-08-06 02:15:43 +000010421 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor3f9a0562009-11-03 01:35:08 +000010422 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10423 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCalld226f652010-08-21 09:40:31 +000010424 return 0;
John McCall67d1a672009-08-06 02:15:43 +000010425 }
John McCall67d1a672009-08-06 02:15:43 +000010426 }
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010427
Douglas Gregorfb35e8f2011-11-03 16:37:14 +000010428 // FIXME: This is an egregious hack to cope with cases where the scope stack
10429 // does not contain the declaration context, i.e., in an out-of-line
10430 // definition of a class.
10431 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10432 if (!DCScope) {
10433 FakeDCScope.setEntity(DC);
10434 DCScope = &FakeDCScope;
10435 }
10436
Francois Pichetaf0f4d02011-08-14 03:52:19 +000010437 bool AddToScope = true;
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +000010438 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10439 move(TemplateParams), AddToScope);
John McCalld226f652010-08-21 09:40:31 +000010440 if (!ND) return 0;
John McCallab88d972009-08-31 22:39:49 +000010441
Douglas Gregor182ddf02009-09-28 00:08:27 +000010442 assert(ND->getDeclContext() == DC);
10443 assert(ND->getLexicalDeclContext() == CurContext);
John McCall88232aa2009-08-18 00:00:49 +000010444
John McCallab88d972009-08-31 22:39:49 +000010445 // Add the function declaration to the appropriate lookup tables,
10446 // adjusting the redeclarations list as necessary. We don't
10447 // want to do this yet if the friending class is dependent.
Mike Stump1eb44332009-09-09 15:08:12 +000010448 //
John McCallab88d972009-08-31 22:39:49 +000010449 // Also update the scope-based lookup if the target context's
10450 // lookup context is in lexical scope.
10451 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +000010452 DC = DC->getRedeclContext();
Douglas Gregor182ddf02009-09-28 00:08:27 +000010453 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010454 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregor182ddf02009-09-28 00:08:27 +000010455 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCallab88d972009-08-31 22:39:49 +000010456 }
John McCall02cace72009-08-28 07:59:38 +000010457
10458 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregor182ddf02009-09-28 00:08:27 +000010459 D.getIdentifierLoc(), ND,
John McCall02cace72009-08-28 07:59:38 +000010460 DS.getFriendSpecLoc());
John McCall5fee1102009-08-29 03:50:18 +000010461 FrD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +000010462 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +000010463
John McCall337ec3d2010-10-12 23:13:28 +000010464 if (ND->isInvalidDecl())
10465 FrD->setInvalidDecl();
John McCall6102ca12010-10-16 06:59:13 +000010466 else {
10467 FunctionDecl *FD;
10468 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10469 FD = FTD->getTemplatedDecl();
10470 else
10471 FD = cast<FunctionDecl>(ND);
10472
10473 // Mark templated-scope function declarations as unsupported.
10474 if (FD->getNumTemplateParameterLists())
10475 FrD->setUnsupportedFriend(true);
10476 }
John McCall337ec3d2010-10-12 23:13:28 +000010477
John McCalld226f652010-08-21 09:40:31 +000010478 return ND;
Anders Carlsson00338362009-05-11 22:55:49 +000010479}
10480
John McCalld226f652010-08-21 09:40:31 +000010481void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10482 AdjustDeclIfTemplate(Dcl);
Mike Stump1eb44332009-09-09 15:08:12 +000010483
Sebastian Redl50de12f2009-03-24 22:27:57 +000010484 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10485 if (!Fn) {
10486 Diag(DelLoc, diag::err_deleted_non_function);
10487 return;
10488 }
Douglas Gregoref96ee02012-01-14 16:38:05 +000010489 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redl50de12f2009-03-24 22:27:57 +000010490 Diag(DelLoc, diag::err_deleted_decl_not_first);
10491 Diag(Prev->getLocation(), diag::note_previous_declaration);
10492 // If the declaration wasn't the first, we delete the function anyway for
10493 // recovery.
10494 }
Sean Hunt10620eb2011-05-06 20:44:56 +000010495 Fn->setDeletedAsWritten();
Sebastian Redl50de12f2009-03-24 22:27:57 +000010496}
Sebastian Redl13e88542009-04-27 21:33:24 +000010497
Sean Hunte4246a62011-05-12 06:15:49 +000010498void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10499 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10500
10501 if (MD) {
Sean Hunteb88ae52011-05-23 21:07:59 +000010502 if (MD->getParent()->isDependentType()) {
10503 MD->setDefaulted();
10504 MD->setExplicitlyDefaulted();
10505 return;
10506 }
10507
Sean Hunte4246a62011-05-12 06:15:49 +000010508 CXXSpecialMember Member = getSpecialMember(MD);
10509 if (Member == CXXInvalid) {
10510 Diag(DefaultLoc, diag::err_default_special_members);
10511 return;
10512 }
10513
10514 MD->setDefaulted();
10515 MD->setExplicitlyDefaulted();
10516
Sean Huntcd10dec2011-05-23 23:14:04 +000010517 // If this definition appears within the record, do the checking when
10518 // the record is complete.
10519 const FunctionDecl *Primary = MD;
10520 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10521 // Find the uninstantiated declaration that actually had the '= default'
10522 // on it.
10523 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10524
10525 if (Primary == Primary->getCanonicalDecl())
Sean Hunte4246a62011-05-12 06:15:49 +000010526 return;
10527
10528 switch (Member) {
10529 case CXXDefaultConstructor: {
10530 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10531 CheckExplicitlyDefaultedDefaultConstructor(CD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010532 if (!CD->isInvalidDecl())
10533 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10534 break;
10535 }
10536
10537 case CXXCopyConstructor: {
10538 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10539 CheckExplicitlyDefaultedCopyConstructor(CD);
10540 if (!CD->isInvalidDecl())
10541 DefineImplicitCopyConstructor(DefaultLoc, CD);
Sean Hunte4246a62011-05-12 06:15:49 +000010542 break;
10543 }
Sean Huntcb45a0f2011-05-12 22:46:25 +000010544
Sean Hunt2b188082011-05-14 05:23:28 +000010545 case CXXCopyAssignment: {
10546 CheckExplicitlyDefaultedCopyAssignment(MD);
10547 if (!MD->isInvalidDecl())
10548 DefineImplicitCopyAssignment(DefaultLoc, MD);
10549 break;
10550 }
10551
Sean Huntcb45a0f2011-05-12 22:46:25 +000010552 case CXXDestructor: {
10553 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10554 CheckExplicitlyDefaultedDestructor(DD);
Sean Hunt49634cf2011-05-13 06:10:58 +000010555 if (!DD->isInvalidDecl())
10556 DefineImplicitDestructor(DefaultLoc, DD);
Sean Huntcb45a0f2011-05-12 22:46:25 +000010557 break;
10558 }
10559
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010560 case CXXMoveConstructor: {
10561 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10562 CheckExplicitlyDefaultedMoveConstructor(CD);
10563 if (!CD->isInvalidDecl())
10564 DefineImplicitMoveConstructor(DefaultLoc, CD);
Sean Hunt82713172011-05-25 23:16:36 +000010565 break;
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010566 }
Sean Hunt82713172011-05-25 23:16:36 +000010567
Sebastian Redl85ea7aa2011-08-30 19:58:05 +000010568 case CXXMoveAssignment: {
10569 CheckExplicitlyDefaultedMoveAssignment(MD);
10570 if (!MD->isInvalidDecl())
10571 DefineImplicitMoveAssignment(DefaultLoc, MD);
10572 break;
10573 }
10574
10575 case CXXInvalid:
David Blaikieb219cfc2011-09-23 05:06:16 +000010576 llvm_unreachable("Invalid special member.");
Sean Hunte4246a62011-05-12 06:15:49 +000010577 }
10578 } else {
10579 Diag(DefaultLoc, diag::err_default_special_members);
10580 }
10581}
10582
Sebastian Redl13e88542009-04-27 21:33:24 +000010583static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +000010584 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl13e88542009-04-27 21:33:24 +000010585 Stmt *SubStmt = *CI;
10586 if (!SubStmt)
10587 continue;
10588 if (isa<ReturnStmt>(SubStmt))
10589 Self.Diag(SubStmt->getSourceRange().getBegin(),
10590 diag::err_return_in_constructor_handler);
10591 if (!isa<Expr>(SubStmt))
10592 SearchForReturnInStmt(Self, SubStmt);
10593 }
10594}
10595
10596void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10597 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10598 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10599 SearchForReturnInStmt(*this, Handler);
10600 }
10601}
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010602
Mike Stump1eb44332009-09-09 15:08:12 +000010603bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010604 const CXXMethodDecl *Old) {
John McCall183700f2009-09-21 23:43:11 +000010605 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10606 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010607
Chandler Carruth73857792010-02-15 11:53:20 +000010608 if (Context.hasSameType(NewTy, OldTy) ||
10609 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010610 return false;
Mike Stump1eb44332009-09-09 15:08:12 +000010611
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010612 // Check if the return types are covariant
10613 QualType NewClassTy, OldClassTy;
Mike Stump1eb44332009-09-09 15:08:12 +000010614
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010615 /// Both types must be pointers or references to classes.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010616 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10617 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010618 NewClassTy = NewPT->getPointeeType();
10619 OldClassTy = OldPT->getPointeeType();
10620 }
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010621 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10622 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10623 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10624 NewClassTy = NewRT->getPointeeType();
10625 OldClassTy = OldRT->getPointeeType();
10626 }
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010627 }
10628 }
Mike Stump1eb44332009-09-09 15:08:12 +000010629
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010630 // The return types aren't either both pointers or references to a class type.
10631 if (NewClassTy.isNull()) {
Mike Stump1eb44332009-09-09 15:08:12 +000010632 Diag(New->getLocation(),
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010633 diag::err_different_return_type_for_overriding_virtual_function)
10634 << New->getDeclName() << NewTy << OldTy;
10635 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump1eb44332009-09-09 15:08:12 +000010636
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010637 return true;
10638 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010639
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010640 // C++ [class.virtual]p6:
10641 // If the return type of D::f differs from the return type of B::f, the
10642 // class type in the return type of D::f shall be complete at the point of
10643 // declaration of D::f or shall be the class type D.
Anders Carlssonac4c9392009-12-31 18:54:35 +000010644 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10645 if (!RT->isBeingDefined() &&
10646 RequireCompleteType(New->getLocation(), NewClassTy,
10647 PDiag(diag::err_covariant_return_incomplete)
10648 << New->getDeclName()))
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010649 return true;
Anders Carlssonac4c9392009-12-31 18:54:35 +000010650 }
Anders Carlssonbe2e2052009-12-31 18:34:24 +000010651
Douglas Gregora4923eb2009-11-16 21:35:15 +000010652 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010653 // Check if the new class derives from the old class.
10654 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10655 Diag(New->getLocation(),
10656 diag::err_covariant_return_not_derived)
10657 << New->getDeclName() << NewTy << OldTy;
10658 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10659 return true;
10660 }
Mike Stump1eb44332009-09-09 15:08:12 +000010661
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010662 // Check if we the conversion from derived to base is valid.
John McCall58e6f342010-03-16 05:22:47 +000010663 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlssone25a96c2010-04-24 17:11:09 +000010664 diag::err_covariant_return_inaccessible_base,
10665 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10666 // FIXME: Should this point to the return type?
10667 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCalleee1d542011-02-14 07:13:47 +000010668 // FIXME: this note won't trigger for delayed access control
10669 // diagnostics, and it's impossible to get an undelayed error
10670 // here from access control during the original parse because
10671 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010672 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10673 return true;
10674 }
10675 }
Mike Stump1eb44332009-09-09 15:08:12 +000010676
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010677 // The qualifiers of the return types must be the same.
Anders Carlssonf2a04bf2010-01-22 17:37:20 +000010678 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010679 Diag(New->getLocation(),
10680 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010681 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010682 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10683 return true;
10684 };
Mike Stump1eb44332009-09-09 15:08:12 +000010685
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010686
10687 // The new class type must have the same or less qualifiers as the old type.
10688 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10689 Diag(New->getLocation(),
10690 diag::err_covariant_return_type_class_type_more_qualified)
10691 << New->getDeclName() << NewTy << OldTy;
10692 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10693 return true;
10694 };
Mike Stump1eb44332009-09-09 15:08:12 +000010695
Anders Carlssonc3a68b22009-05-14 19:52:19 +000010696 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +000010697}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010698
Douglas Gregor4ba31362009-12-01 17:24:26 +000010699/// \brief Mark the given method pure.
10700///
10701/// \param Method the method to be marked pure.
10702///
10703/// \param InitRange the source range that covers the "0" initializer.
10704bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnara796aa442011-03-12 11:17:06 +000010705 SourceLocation EndLoc = InitRange.getEnd();
10706 if (EndLoc.isValid())
10707 Method->setRangeEnd(EndLoc);
10708
Douglas Gregor4ba31362009-12-01 17:24:26 +000010709 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10710 Method->setPure();
Douglas Gregor4ba31362009-12-01 17:24:26 +000010711 return false;
Abramo Bagnara796aa442011-03-12 11:17:06 +000010712 }
Douglas Gregor4ba31362009-12-01 17:24:26 +000010713
10714 if (!Method->isInvalidDecl())
10715 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10716 << Method->getDeclName() << InitRange;
10717 return true;
10718}
10719
John McCall731ad842009-12-19 09:28:58 +000010720/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10721/// an initializer for the out-of-line declaration 'Dcl'. The scope
10722/// is a fresh scope pushed for just this purpose.
10723///
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010724/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10725/// static data member of class X, names should be looked up in the scope of
10726/// class X.
John McCalld226f652010-08-21 09:40:31 +000010727void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010728 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010729 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010730
John McCall731ad842009-12-19 09:28:58 +000010731 // We should only get called for declarations with scope specifiers, like:
10732 // int foo::bar;
10733 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010734 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010735}
10736
10737/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCalld226f652010-08-21 09:40:31 +000010738/// initializer for the out-of-line declaration 'D'.
10739void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010740 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidisb65abda2011-04-22 18:52:25 +000010741 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010742
John McCall731ad842009-12-19 09:28:58 +000010743 assert(D->isOutOfLine());
John McCall7a1dc562009-12-19 10:49:29 +000010744 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +000010745}
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010746
10747/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10748/// C++ if/switch/while/for statement.
10749/// e.g: "if (int x = f()) {...}"
John McCalld226f652010-08-21 09:40:31 +000010750DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010751 // C++ 6.4p2:
10752 // The declarator shall not specify a function or an array.
10753 // The type-specifier-seq shall not contain typedef and shall not declare a
10754 // new class or enumeration.
10755 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10756 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010757
10758 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor9a30c992011-07-05 16:13:20 +000010759 if (!Dcl)
10760 return true;
10761
Argyrios Kyrtzidisdb7abf72011-06-28 03:01:12 +000010762 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10763 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010764 << D.getSourceRange();
Douglas Gregor9a30c992011-07-05 16:13:20 +000010765 return true;
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010766 }
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010767
Douglas Gregor99e9b4d2009-11-25 00:27:52 +000010768 return Dcl;
10769}
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010770
Douglas Gregordfe65432011-07-28 19:11:31 +000010771void Sema::LoadExternalVTableUses() {
10772 if (!ExternalSource)
10773 return;
10774
10775 SmallVector<ExternalVTableUse, 4> VTables;
10776 ExternalSource->ReadUsedVTables(VTables);
10777 SmallVector<VTableUse, 4> NewUses;
10778 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10779 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10780 = VTablesUsed.find(VTables[I].Record);
10781 // Even if a definition wasn't required before, it may be required now.
10782 if (Pos != VTablesUsed.end()) {
10783 if (!Pos->second && VTables[I].DefinitionRequired)
10784 Pos->second = true;
10785 continue;
10786 }
10787
10788 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10789 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10790 }
10791
10792 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10793}
10794
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010795void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10796 bool DefinitionRequired) {
10797 // Ignore any vtable uses in unevaluated operands or for classes that do
10798 // not have a vtable.
10799 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10800 CurContext->isDependentContext() ||
Eli Friedman78a54242012-01-21 04:44:06 +000010801 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolabbf58bb2010-03-10 02:19:29 +000010802 return;
10803
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010804 // Try to insert this class into the map.
Douglas Gregordfe65432011-07-28 19:11:31 +000010805 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010806 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10807 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10808 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10809 if (!Pos.second) {
Daniel Dunbarb9aefa72010-05-25 00:33:13 +000010810 // If we already had an entry, check to see if we are promoting this vtable
10811 // to required a definition. If so, we need to reappend to the VTableUses
10812 // list, since we may have already processed the first entry.
10813 if (DefinitionRequired && !Pos.first->second) {
10814 Pos.first->second = true;
10815 } else {
10816 // Otherwise, we can early exit.
10817 return;
10818 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010819 }
10820
10821 // Local classes need to have their virtual members marked
10822 // immediately. For all other classes, we mark their virtual members
10823 // at the end of the translation unit.
10824 if (Class->isLocalClass())
10825 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar380c2132010-05-11 21:32:35 +000010826 else
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010827 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregorbbbe0742010-05-11 20:24:17 +000010828}
10829
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010830bool Sema::DefineUsedVTables() {
Douglas Gregordfe65432011-07-28 19:11:31 +000010831 LoadExternalVTableUses();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010832 if (VTableUses.empty())
Anders Carlssond6a637f2009-12-07 08:24:59 +000010833 return false;
Chandler Carruthaee543a2010-12-12 21:36:11 +000010834
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010835 // Note: The VTableUses vector could grow as a result of marking
10836 // the members of a class as "used", so we check the size each
10837 // time through the loop and prefer indices (with are stable) to
10838 // iterators (which are not).
Douglas Gregor78844032011-04-22 22:25:37 +000010839 bool DefinedAnything = false;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010840 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbare669f892010-05-25 00:32:58 +000010841 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010842 if (!Class)
10843 continue;
10844
10845 SourceLocation Loc = VTableUses[I].second;
10846
10847 // If this class has a key function, but that key function is
10848 // defined in another translation unit, we don't need to emit the
10849 // vtable even though we're using it.
10850 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +000010851 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010852 switch (KeyFunction->getTemplateSpecializationKind()) {
10853 case TSK_Undeclared:
10854 case TSK_ExplicitSpecialization:
10855 case TSK_ExplicitInstantiationDeclaration:
10856 // The key function is in another translation unit.
10857 continue;
10858
10859 case TSK_ExplicitInstantiationDefinition:
10860 case TSK_ImplicitInstantiation:
10861 // We will be instantiating the key function.
10862 break;
10863 }
10864 } else if (!KeyFunction) {
10865 // If we have a class with no key function that is the subject
10866 // of an explicit instantiation declaration, suppress the
10867 // vtable; it will live with the explicit instantiation
10868 // definition.
10869 bool IsExplicitInstantiationDeclaration
10870 = Class->getTemplateSpecializationKind()
10871 == TSK_ExplicitInstantiationDeclaration;
10872 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10873 REnd = Class->redecls_end();
10874 R != REnd; ++R) {
10875 TemplateSpecializationKind TSK
10876 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10877 if (TSK == TSK_ExplicitInstantiationDeclaration)
10878 IsExplicitInstantiationDeclaration = true;
10879 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10880 IsExplicitInstantiationDeclaration = false;
10881 break;
10882 }
10883 }
10884
10885 if (IsExplicitInstantiationDeclaration)
10886 continue;
10887 }
10888
10889 // Mark all of the virtual members of this class as referenced, so
10890 // that we can build a vtable. Then, tell the AST consumer that a
10891 // vtable for this class is required.
Douglas Gregor78844032011-04-22 22:25:37 +000010892 DefinedAnything = true;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010893 MarkVirtualMembersReferenced(Loc, Class);
10894 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10895 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10896
10897 // Optionally warn if we're emitting a weak vtable.
10898 if (Class->getLinkage() == ExternalLinkage &&
10899 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregora120d012011-09-23 19:04:03 +000010900 const FunctionDecl *KeyFunctionDef = 0;
10901 if (!KeyFunction ||
10902 (KeyFunction->hasBody(KeyFunctionDef) &&
10903 KeyFunctionDef->isInlined()))
David Blaikie44d95b52011-12-09 18:32:50 +000010904 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10905 TSK_ExplicitInstantiationDefinition
10906 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10907 << Class;
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010908 }
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010909 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +000010910 VTableUses.clear();
10911
Douglas Gregor78844032011-04-22 22:25:37 +000010912 return DefinedAnything;
Anders Carlsson5ec02ae2009-12-02 17:15:43 +000010913}
Anders Carlssond6a637f2009-12-07 08:24:59 +000010914
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010915void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10916 const CXXRecordDecl *RD) {
Anders Carlssond6a637f2009-12-07 08:24:59 +000010917 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10918 e = RD->method_end(); i != e; ++i) {
10919 CXXMethodDecl *MD = *i;
10920
10921 // C++ [basic.def.odr]p2:
10922 // [...] A virtual member function is used if it is not pure. [...]
10923 if (MD->isVirtual() && !MD->isPure())
Eli Friedman5f2987c2012-02-02 03:46:19 +000010924 MarkFunctionReferenced(Loc, MD);
Anders Carlssond6a637f2009-12-07 08:24:59 +000010925 }
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010926
10927 // Only classes that have virtual bases need a VTT.
10928 if (RD->getNumVBases() == 0)
10929 return;
10930
10931 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10932 e = RD->bases_end(); i != e; ++i) {
10933 const CXXRecordDecl *Base =
10934 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola3e1ae932010-03-26 00:36:59 +000010935 if (Base->getNumVBases() == 0)
10936 continue;
10937 MarkVirtualMembersReferenced(Loc, Base);
10938 }
Anders Carlssond6a637f2009-12-07 08:24:59 +000010939}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010940
10941/// SetIvarInitializers - This routine builds initialization ASTs for the
10942/// Objective-C implementation whose ivars need be initialized.
10943void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10944 if (!getLangOptions().CPlusPlus)
10945 return;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +000010946 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +000010947 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010948 CollectIvarsToConstructOrDestruct(OID, ivars);
10949 if (ivars.empty())
10950 return;
Chris Lattner5f9e2722011-07-23 10:55:15 +000010951 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010952 for (unsigned i = 0; i < ivars.size(); i++) {
10953 FieldDecl *Field = ivars[i];
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010954 if (Field->isInvalidDecl())
10955 continue;
10956
Sean Huntcbb67482011-01-08 20:30:50 +000010957 CXXCtorInitializer *Member;
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010958 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10959 InitializationKind InitKind =
10960 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10961
10962 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCall60d7b3a2010-08-24 06:29:42 +000010963 ExprResult MemberInit =
John McCallf312b1e2010-08-26 23:41:50 +000010964 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregor53c374f2010-12-07 00:41:46 +000010965 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010966 // Note, MemberInit could actually come back empty if no initialization
10967 // is required (e.g., because it would call a trivial default constructor)
10968 if (!MemberInit.get() || MemberInit.isInvalid())
10969 continue;
John McCallb4eb64d2010-10-08 02:01:28 +000010970
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010971 Member =
Sean Huntcbb67482011-01-08 20:30:50 +000010972 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10973 SourceLocation(),
10974 MemberInit.takeAs<Expr>(),
10975 SourceLocation());
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010976 AllToInit.push_back(Member);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010977
10978 // Be sure that the destructor is accessible and is marked as referenced.
10979 if (const RecordType *RecordTy
10980 = Context.getBaseElementType(Field->getType())
10981 ->getAs<RecordType>()) {
10982 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregordb89f282010-07-01 22:47:18 +000010983 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +000010984 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor68dd3ee2010-05-20 02:24:22 +000010985 CheckDestructorAccess(Field->getLocation(), Destructor,
10986 PDiag(diag::err_access_dtor_ivar)
10987 << Context.getBaseElementType(Field->getType()));
10988 }
10989 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +000010990 }
10991 ObjCImplementation->setIvarInitializers(Context,
10992 AllToInit.data(), AllToInit.size());
10993 }
10994}
Sean Huntfe57eef2011-05-04 05:57:24 +000010995
Sean Huntebcbe1d2011-05-04 23:29:54 +000010996static
10997void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10998 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10999 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11000 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11001 Sema &S) {
11002 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11003 CE = Current.end();
11004 if (Ctor->isInvalidDecl())
11005 return;
11006
11007 const FunctionDecl *FNTarget = 0;
11008 CXXConstructorDecl *Target;
11009
11010 // We ignore the result here since if we don't have a body, Target will be
11011 // null below.
11012 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
11013 Target
11014= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
11015
11016 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11017 // Avoid dereferencing a null pointer here.
11018 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11019
11020 if (!Current.insert(Canonical))
11021 return;
11022
11023 // We know that beyond here, we aren't chaining into a cycle.
11024 if (!Target || !Target->isDelegatingConstructor() ||
11025 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11026 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11027 Valid.insert(*CI);
11028 Current.clear();
11029 // We've hit a cycle.
11030 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11031 Current.count(TCanonical)) {
11032 // If we haven't diagnosed this cycle yet, do so now.
11033 if (!Invalid.count(TCanonical)) {
11034 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Sean Huntc1598702011-05-05 00:05:47 +000011035 diag::warn_delegating_ctor_cycle)
Sean Huntebcbe1d2011-05-04 23:29:54 +000011036 << Ctor;
11037
11038 // Don't add a note for a function delegating directo to itself.
11039 if (TCanonical != Canonical)
11040 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11041
11042 CXXConstructorDecl *C = Target;
11043 while (C->getCanonicalDecl() != Canonical) {
11044 (void)C->getTargetConstructor()->hasBody(FNTarget);
11045 assert(FNTarget && "Ctor cycle through bodiless function");
11046
11047 C
11048 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11049 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11050 }
11051 }
11052
11053 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11054 Invalid.insert(*CI);
11055 Current.clear();
11056 } else {
11057 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11058 }
11059}
11060
11061
Sean Huntfe57eef2011-05-04 05:57:24 +000011062void Sema::CheckDelegatingCtorCycles() {
11063 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11064
Sean Huntebcbe1d2011-05-04 23:29:54 +000011065 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11066 CE = Current.end();
Sean Huntfe57eef2011-05-04 05:57:24 +000011067
Douglas Gregor0129b562011-07-27 21:57:17 +000011068 for (DelegatingCtorDeclsType::iterator
11069 I = DelegatingCtorDecls.begin(ExternalSource),
Sean Huntebcbe1d2011-05-04 23:29:54 +000011070 E = DelegatingCtorDecls.end();
11071 I != E; ++I) {
11072 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Sean Huntfe57eef2011-05-04 05:57:24 +000011073 }
Sean Huntebcbe1d2011-05-04 23:29:54 +000011074
11075 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11076 (*CI)->setInvalidDecl();
Sean Huntfe57eef2011-05-04 05:57:24 +000011077}
Peter Collingbourne78dd67e2011-10-02 23:49:40 +000011078
11079/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11080Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11081 // Implicitly declared functions (e.g. copy constructors) are
11082 // __host__ __device__
11083 if (D->isImplicit())
11084 return CFT_HostDevice;
11085
11086 if (D->hasAttr<CUDAGlobalAttr>())
11087 return CFT_Global;
11088
11089 if (D->hasAttr<CUDADeviceAttr>()) {
11090 if (D->hasAttr<CUDAHostAttr>())
11091 return CFT_HostDevice;
11092 else
11093 return CFT_Device;
11094 }
11095
11096 return CFT_Host;
11097}
11098
11099bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11100 CUDAFunctionTarget CalleeTarget) {
11101 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11102 // Callable from the device only."
11103 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11104 return true;
11105
11106 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11107 // Callable from the host only."
11108 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11109 // Callable from the host only."
11110 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11111 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11112 return true;
11113
11114 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11115 return true;
11116
11117 return false;
11118}